View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hbase.archetypes.exemplars.shaded_client;
20  
21  import java.io.IOException;
22  import java.util.Map.Entry;
23  import java.util.NavigableMap;
24  import org.apache.hadoop.hbase.HColumnDescriptor;
25  import org.apache.hadoop.hbase.HTableDescriptor;
26  import org.apache.hadoop.hbase.NamespaceDescriptor;
27  import org.apache.hadoop.hbase.NamespaceNotFoundException;
28  import org.apache.hadoop.hbase.TableName;
29  import org.apache.hadoop.hbase.client.Admin;
30  import org.apache.hadoop.hbase.client.Connection;
31  import org.apache.hadoop.hbase.client.ConnectionFactory;
32  import org.apache.hadoop.hbase.client.Delete;
33  import org.apache.hadoop.hbase.client.Get;
34  import org.apache.hadoop.hbase.client.Put;
35  import org.apache.hadoop.hbase.client.Result;
36  import org.apache.hadoop.hbase.client.Table;
37  import org.apache.hadoop.hbase.util.Bytes;
38  
39  /**
40   * Successful running of this application requires access to an active instance
41   * of HBase. For install instructions for a standalone instance of HBase, please
42   * refer to https://hbase.apache.org/book.html#quickstart
43   */
44  public final class HelloHBase {
45  
46    protected static final String MY_NAMESPACE_NAME = "myTestNamespace";
47    static final TableName MY_TABLE_NAME = TableName.valueOf("myTestTable");
48    static final byte[] MY_COLUMN_FAMILY_NAME = Bytes.toBytes("cf");
49    static final byte[] MY_FIRST_COLUMN_QUALIFIER
50            = Bytes.toBytes("myFirstColumn");
51    static final byte[] MY_SECOND_COLUMN_QUALIFIER
52            = Bytes.toBytes("mySecondColumn");
53    static final byte[] MY_ROW_ID = Bytes.toBytes("rowId01");
54  
55    // Private constructor included here to avoid checkstyle warnings
56    private HelloHBase() {
57    }
58  
59    public static void main(final String[] args) throws IOException {
60      final boolean deleteAllAtEOJ = true;
61  
62      /**
63       * ConnectionFactory#createConnection() automatically looks for
64       * hbase-site.xml (HBase configuration parameters) on the system's
65       * CLASSPATH, to enable creation of Connection to HBase via Zookeeper.
66       */
67      try (Connection connection = ConnectionFactory.createConnection();
68              Admin admin = connection.getAdmin()) {
69  
70        admin.getClusterStatus(); // assure connection successfully established
71        System.out.println("\n*** Hello HBase! -- Connection has been "
72                + "established via Zookeeper!!\n");
73  
74        createNamespaceAndTable(admin);
75  
76        System.out.println("Getting a Table object for [" + MY_TABLE_NAME
77                + "] with which to perform CRUD operations in HBase.");
78        try (Table table = connection.getTable(MY_TABLE_NAME)) {
79  
80          putRowToTable(table);
81          getAndPrintRowContents(table);
82  
83          if (deleteAllAtEOJ) {
84            deleteRow(table);
85          }
86        }
87  
88        if (deleteAllAtEOJ) {
89          deleteNamespaceAndTable(admin);
90        }
91      }
92    }
93  
94    /**
95     * Invokes Admin#createNamespace and Admin#createTable to create a namespace
96     * with a table that has one column-family.
97     *
98     * @param admin Standard Admin object
99     * @throws IOException If IO problem encountered
100    */
101   static void createNamespaceAndTable(final Admin admin) throws IOException {
102 
103     if (!namespaceExists(admin, MY_NAMESPACE_NAME)) {
104       System.out.println("Creating Namespace [" + MY_NAMESPACE_NAME + "].");
105 
106       admin.createNamespace(NamespaceDescriptor
107               .create(MY_NAMESPACE_NAME).build());
108     }
109     if (!admin.tableExists(MY_TABLE_NAME)) {
110       System.out.println("Creating Table [" + MY_TABLE_NAME.getNameAsString()
111               + "], with one Column Family ["
112               + Bytes.toString(MY_COLUMN_FAMILY_NAME) + "].");
113 
114       admin.createTable(new HTableDescriptor(MY_TABLE_NAME)
115               .addFamily(new HColumnDescriptor(MY_COLUMN_FAMILY_NAME)));
116     }
117   }
118 
119   /**
120    * Invokes Table#put to store a row (with two new columns created 'on the
121    * fly') into the table.
122    *
123    * @param table Standard Table object (used for CRUD operations).
124    * @throws IOException If IO problem encountered
125    */
126   static void putRowToTable(final Table table) throws IOException {
127 
128     table.put(new Put(MY_ROW_ID).addColumn(MY_COLUMN_FAMILY_NAME,
129             MY_FIRST_COLUMN_QUALIFIER,
130             Bytes.toBytes("Hello")).addColumn(MY_COLUMN_FAMILY_NAME,
131                     MY_SECOND_COLUMN_QUALIFIER,
132                     Bytes.toBytes("World!")));
133 
134     System.out.println("Row [" + Bytes.toString(MY_ROW_ID)
135             + "] was put into Table ["
136             + table.getName().getNameAsString() + "] in HBase;\n"
137             + "  the row's two columns (created 'on the fly') are: ["
138             + Bytes.toString(MY_COLUMN_FAMILY_NAME) + ":"
139             + Bytes.toString(MY_FIRST_COLUMN_QUALIFIER)
140             + "] and [" + Bytes.toString(MY_COLUMN_FAMILY_NAME) + ":"
141             + Bytes.toString(MY_SECOND_COLUMN_QUALIFIER) + "]");
142   }
143 
144   /**
145    * Invokes Table#get and prints out the contents of the retrieved row.
146    *
147    * @param table Standard Table object
148    * @throws IOException If IO problem encountered
149    */
150   static void getAndPrintRowContents(final Table table) throws IOException {
151 
152     Result row = table.get(new Get(MY_ROW_ID));
153 
154     System.out.println("Row [" + Bytes.toString(row.getRow())
155             + "] was retrieved from Table ["
156             + table.getName().getNameAsString()
157             + "] in HBase, with the following content:");
158 
159     for (Entry<byte[], NavigableMap<byte[], byte[]>> colFamilyEntry
160             : row.getNoVersionMap().entrySet()) {
161       String columnFamilyName = Bytes.toString(colFamilyEntry.getKey());
162 
163       System.out.println("  Columns in Column Family [" + columnFamilyName
164               + "]:");
165 
166       for (Entry<byte[], byte[]> columnNameAndValueMap
167               : colFamilyEntry.getValue().entrySet()) {
168 
169         System.out.println("    Value of Column [" + columnFamilyName + ":"
170                 + Bytes.toString(columnNameAndValueMap.getKey()) + "] == "
171                 + Bytes.toString(columnNameAndValueMap.getValue()));
172       }
173     }
174   }
175 
176   /**
177    * Checks to see whether a namespace exists.
178    *
179    * @param admin Standard Admin object
180    * @param namespaceName Name of namespace
181    * @return true If namespace exists
182    * @throws IOException If IO problem encountered
183    */
184   static boolean namespaceExists(final Admin admin, final String namespaceName)
185           throws IOException {
186     try {
187       admin.getNamespaceDescriptor(namespaceName);
188     } catch (NamespaceNotFoundException e) {
189       return false;
190     }
191     return true;
192   }
193 
194   /**
195    * Invokes Table#delete to delete test data (i.e. the row)
196    *
197    * @param table Standard Table object
198    * @throws IOException If IO problem is encountered
199    */
200   static void deleteRow(final Table table) throws IOException {
201     System.out.println("Deleting row [" + Bytes.toString(MY_ROW_ID)
202             + "] from Table ["
203             + table.getName().getNameAsString() + "].");
204     table.delete(new Delete(MY_ROW_ID));
205   }
206 
207   /**
208    * Invokes Admin#disableTable, Admin#deleteTable, and Admin#deleteNamespace to
209    * disable/delete Table and delete Namespace.
210    *
211    * @param admin Standard Admin object
212    * @throws IOException If IO problem is encountered
213    */
214   static void deleteNamespaceAndTable(final Admin admin) throws IOException {
215     if (admin.tableExists(MY_TABLE_NAME)) {
216       System.out.println("Disabling/deleting Table ["
217               + MY_TABLE_NAME.getNameAsString() + "].");
218       admin.disableTable(MY_TABLE_NAME); // Disable a table before deleting it.
219       admin.deleteTable(MY_TABLE_NAME);
220     }
221     if (namespaceExists(admin, MY_NAMESPACE_NAME)) {
222       System.out.println("Deleting Namespace [" + MY_NAMESPACE_NAME + "].");
223       admin.deleteNamespace(MY_NAMESPACE_NAME);
224     }
225   }
226 }