Home > Articles > Data

📄 Contents

  1. By Steve Haines
  2. Setting Up an HBase Maven Project
  3. Summary
Like this article? We recommend

Setting Up an HBase Maven Project

To develop HBase client applications, you either need to download the HBase client library and add it to your CLASSPATH, or you can use Maven to manage your dependencies. You can download the source code for this article here, but if you want to follow along, execute the following Maven command to create the project:

mvn archetype:create -DgroupId=com.geekcap.informit -DartifactId=hbase-example

This creates a new directory named hbase-example in your working directory. The first thing you need to do is add the hbase-client dependency to your pom.xml file. Listing 1 shows the contents of my pom.xml file.

Listing 1. pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.geekcap.informit</groupId>
    <artifactId>hbase-example</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>hbase-example</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
             <groupId>org.apache.hbase</groupId>
             <artifactId>hbase-client</artifactId>
             <version>0.98.5-hadoop2</version>
        </dependency>

        <dependency>
             <groupId>junit</groupId>
             <artifactId>junit</artifactId>
             <version>4.11</version>
             <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.0.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                   <archive>
                       <manifest>
                           <addClasspath>true</addClasspath>
                           <classpathPrefix>lib/</classpathPrefix>
                           <mainClass>com.geekcap.informit.hbaseexample.HBaseExample</mainClass>
                       </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>copy</id>
                        <phase>install</phase>
                        <goals>
                            <goal>copy-dependencies</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${project.build.directory}/lib</outputDirectory>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

This pom.xml file has the hbase-client dependency in it:

<dependency>
    <groupId>org.apache.hbase</groupId>
    <artifactId>hbase-client</artifactId>
    <version>0.98.5-hadoop2</version>
</dependency>

It also has some build settings to compile the code against Java 1.6 to make the resultant JAR file executable and to include all dependencies in the build. When you build then you can execute our main() method with the following command from the target directory:

java –jar hbase-example-1.0-SNAPSHOT.jar

The first thing that we need to do in our application is to gain access to the PageViews table that we created in the previous article. We can ask HBase for a connection to the PageViews table in one of two ways:

  1. Create an HTable instance directly.
  2. Use a connection pool.

Using a connection pool performs better because creating a database connection is an expensive operation, but let’s start by creating the HTable instance directly:

Configuration conf = HBaseConfiguration.create();
HTableInterface pageViewTable = new HTable( conf, "PageViews" );

The HBaseConfiguration class has a static method, create(), that creates a configuration object. The default configuration is to connect to HBase running on the local machine, but if you want to change any of the connection parameters, you can do so by calling the Configuration class’s set() method. HBase runs on top of Hadoop, and Hadoop leverages a technology called ZooKeeper to handle its load distribution, so if you want to connect to a remote machine, you could do so as follows:

conf.set("hbase.zookeeper.quorum", "server’s IP address");

The HTable constructor takes a configuration object and the name of the table to connect to.

The alternative approach is to create an HTablePool:

HTablePool pool = new HTablePool();

Or you can specify a connection and a pool size as follows:

HTablePool pool = new HTablePool(conf,10);

This creates a new HTablePool with 10 as the maximum number of references to maintain for each table. This means that after accessing the PageViews table, you will get back the same connection without having to re-create it. And if you run concurrent threads, then you can have 10 simultaneous connections.) With an HTablePool youcan access the HTable with the following command:

HTableInterface pageViewsTable = pool.getTable("PageViews");

And then when you finish, you can close the table to return the connection back to the pool:

pageViewsTable.close();

To interact with HBase, I created a simple PageView POJO class, as shown in Listing 2.

Listing 2. PageView.java

package com.geekcap.informit.hbaseexample;

public class PageView
{

    private String userId;
    private String page;

    public PageView() {
    }

    public PageView(String userId, String page) {
        this.userId = userId;
        this.page = page;

    }
    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getPage() {
        return page;
    }

    public void setPage(String page) {
        this.page = page;
    }

}

In this example we’re going to store two pieces of information—the user ID and the page that the user visited—and we’re going to save the user ID as the row key. Programming against the HBase API is similar to what we learned in the previous article. Specifically, we accomplish the following actions with the following commands:

  • Get an object instance from the database: Createa Get object and pass it to the HTableInterface’s get() method.
  • Put an object instance into the database: Createa Put object and pass it to the HTableInterface’s put() method.
  • Delete an object instance from the database: Createa Delete object and pass it to the HTableInstance’s delete() method.
  • Scan the database for rows within start and end row values: Createa Scan object and pass it to the HTableInstance’s getScanner() method.

Listing 3 shows the source code for the HBaseExample class.

Listing 3. HBaseExample.java

package com.geekcap.informit.hbaseexample;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class HBaseExample
{

    private HTableInterface pageViewTable;

    public HBaseExample()
    {
        try
        {
            Configuration conf = HBaseConfiguration.create();
            pageViewTable = new HTable( conf, "PageViews");
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public void close()
    {
        try

        {
            pageViewTable.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public void put( PageView pageView )
    {
        // Create a new Put object with the Row Key as the bytes of the user id
        Put put = new Put( Bytes.toBytes( pageView.getUserId() ) );

        // Add the user id to the info column family
        put.add( Bytes.toBytes( "info" ),
                 Bytes.toBytes( "userId" ),
                 Bytes.toBytes( pageView.getUserId() ) );

        // Add the page to the info column family
        put.add( Bytes.toBytes( "info" ),
                 Bytes.toBytes( "page" ),
                 Bytes.toBytes( pageView.getPage() ) );
        try

        {

            // Add the PageView to the page view table
            pageViewTable.put( put );
        }
        catch( IOException e )
        {
            e.printStackTrace();
        }
    }

    public PageView get( String rowkey )

    {
        try
        {

            // Create a Get object with the rowkey (as a byte[])
            Get get = new Get( Bytes.toBytes( rowkey ) );

            // Execute the Get
            Result result = pageViewTable.get( get );

            // Retrieve the results
            PageView pageView = new PageView();
            byte[] bytes = result.getValue( Bytes.toBytes( "info" ),
                                            Bytes.toBytes( "userId" ) );
            pageView.setUserId( Bytes.toString( bytes ) );
            bytes = result.getValue( Bytes.toBytes( "info" ),
                                     Bytes.toBytes( "page" ) );
            pageView.setPage(Bytes.toString(bytes));


            // Return the newly constructed PageView
            return pageView;
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }
    public void delete( String rowkey )
    {
        try
        {
            Delete delete = new Delete( Bytes.toBytes( rowkey ) );
            pageViewTable.delete( delete );
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public List<PageView> scan( String startRowKey, String endRowKey )
    {
        try
        {
            // Build a list to hold our results
            List<PageView> pageViewResults = new ArrayList<PageView>();


            // Create and execute a scan
            Scan scan = new Scan( Bytes.toBytes( startRowKey ), Bytes.toBytes( endRowKey ) );
            ResultScanner results = pageViewTable.getScanner(scan);

            for( Result result : results )

            {
                // Build a new PageView
                PageView pageView = new PageView();
                byte[] bytes = result.getValue( Bytes.toBytes( "info" ),
                        Bytes.toBytes( "userId" ) );
                pageView.setUserId( Bytes.toString( bytes ) );
                bytes = result.getValue( Bytes.toBytes( "info" ),
                        Bytes.toBytes( "page" ) );
                pageView.setPage(Bytes.toString(bytes));

                // Add the PageView to our results
                pageViewResults.add( pageView );
            }

            // Return our results
            return pageViewResults;
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    public static void main( String[] args )

    {
        HBaseExample example = new HBaseExample();

        // Create two records
        example.put( new PageView( "User1", "/mypage" ) );
        example.put( new PageView( "User2","/mypage" ) );

        // Execute a Scan from "U" to "V"
        List<PageView> pageViews = example.scan( "U", "V" );
        if( pageViews != null ) {
            System.out.println("Page Views:");
            for (PageView pageView : pageViews) {
                System.out.println("\tUser ID: " + pageView.getUserId() + ", Page: " + pageView.getPage());
            }
        }

        // Get a specific row
        PageView pv = example.get( "User1" );
        System.out.println( "User ID: " + pv.getUserId() + ", Page: " + pv.getPage() );

        // Delete a row
        example.delete( "User1" );

        // Execute another scan, which should just have User2 in it
        pageViews = example.scan( "U", "V" );
        if( pageViews != null ) {
            System.out.println("Page Views:");
            for (PageView pageView : pageViews) {
                System.out.println("\tUser ID: " + pageView.getUserId() + ", Page: " + pageView.getPage());
            }
        }

        // Close our table
        example.close();
    }
}

Listing 3 creates a Configuration instance, connects to the PageViews database in its constructor, and then saves a reference to the HTableInterface as a class member variable. Let’s look at the methods one-by-one, starting withthe put() method:

public void put( PageView pageView )
    {
        // Create a new Put object with the Row Key as the bytes of the user id
        Put put = new Put( Bytes.toBytes( pageView.getUserId() ) );

        // Add the user id to the info column family
        put.add( Bytes.toBytes( "info" ),
                 Bytes.toBytes( "userId" ),
                 Bytes.toBytes( pageView.getUserId() ) );

        // Add the page to the info column family
        put.add( Bytes.toBytes( "info" ),
                 Bytes.toBytes( "page" ),
                 Bytes.toBytes( pageView.getPage() ) );

        try
        {
            // Add the PageView to the page view table
            pageViewTable.put( put );
        }
        catch( IOException e )
        {
            e.printStackTrace();
        }
}

The put() method creates a new Put object, passing it the row key. The only thing that you need to keep in mind is that all objects are stored as an array of bytes, so we need to convert the row key String value to a byte[]. We can do that with the Bytes.toBytes() method. The constructor for the Put objects requires the row key, but then we need to add our fields. Recall that we created a column family named (“info”) and now we have two column qualifiers: userId and page. Again we need to convert the column family, column qualifier, and associated value to byte arrays, and then we can add them to the Put object using the add() method. Finally, we can call the HTableInterface’s put() method with the Put object to insert the record in the database.

The next method we want to examine is the get() method:

public PageView get( String rowkey )
    {
        try
        {
            // Create a Get object with the rowkey (as a byte[])
            Get get = new Get( Bytes.toBytes( rowkey ) );

            // Execute the Get
            Result result = pageViewTable.get( get );

            // Retrieve the results
            PageView pageView = new PageView();
            byte[] bytes = result.getValue( Bytes.toBytes( "info" ),
                                            Bytes.toBytes( "userId" ) );
            pageView.setUserId( Bytes.toString( bytes ) );
            bytes = result.getValue( Bytes.toBytes( "info" ),
                                     Bytes.toBytes( "page" ) );
            pageView.setPage(Bytes.toString(bytes));

            // Return the newly constructed PageView
            return pageView;
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
}

The get() method creates a Get object, passing it a byte array representation of the row key, and then executes the HTableInterface’s get() method, passing it our Get instance. This method returns a Result instance that we can use to retrieve the values we’re looking for. We can pass the Result class’s getValue() method the column family (“info”) and the column qualifier we want, as byte arrays, and it returns a byte array that contains the requested value.

Next, let’s review the delete() method:

public void delete( String rowkey )
    {
        try
        {
            Delete delete = new Delete( Bytes.toBytes( rowkey ) );
            pageViewTable.delete( delete );
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

The delete() method is the simplest: It creates a Delete object with a byte array representation of the row key to delete, and then it invokes the HTableInterface’s delete() method.

Finally, let’s review the scan() method:

public List<PageView> scan( String startRowKey, String endRowKey )
    {
        try
        {
            // Build a list to hold our results
            List<PageView> pageViewResults = new ArrayList<PageView>();

            // Create and execute a scan
            Scan scan = new Scan( Bytes.toBytes( startRowKey ), Bytes.toBytes( endRowKey ) );
            ResultScanner results = pageViewTable.getScanner(scan);

            for( Result result : results )
            {
                // Build a new PageView
                PageView pageView = new PageView();
                byte[] bytes = result.getValue( Bytes.toBytes( "info" ),
                        Bytes.toBytes( "userId" ) );
                pageView.setUserId( Bytes.toString( bytes ) );
                bytes = result.getValue( Bytes.toBytes( "info" ),
                        Bytes.toBytes( "page" ) );
                pageView.setPage(Bytes.toString(bytes));

                // Add the PageView to our results
                pageViewResults.add( pageView );
            }
            // Return our results
            return pageViewResults;
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        return null;
    }

The scan() method is the most complicated method, but if you remember how table scans work from the first article, it should be straightforward. Recall that you cannot query a table, but you can retrieve all records between two row keys. So in this example we create a Scan object, passing it start and end row keys (as byte arrays). We then pass this Scan object to the HTableInterface’s getScanner() method, which returns a ResultScanner. We can iterate over the ResultScanner and handle the results just as we handle the Result in the get() method.

Finally, the main() method demonstrates how to exercise these methods. One note is that we have to close the table when we’re complete, so we added a close() method that closes the HTableInterface.

You can build this application with the following command:

mvn clean install

This creates a file in the target directory named hbase-example-1.0-SNAPSHOT.jar. You can execute it with the following command:

java -jar hbase-example-1.0-SNAPSHOT.jar
You should see output similar to the following:

Page Views:

  • User ID: User1, Page: /mypage
  • User ID: User2, Page: /mypage

User ID: User1, Page: /mypage

Page Views:

  • User ID: User2, Page: /mypage

We created two page views and then executed a table scan for rows between “U” and “V”; then we retrieved a specific row; we deleted the first page view; and finally we ran a second table scan.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020