001/**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019package org.apache.hbase.archetypes.exemplars.shaded_client;
020
021import java.io.IOException;
022import java.util.Map.Entry;
023import java.util.NavigableMap;
024import org.apache.hadoop.hbase.HColumnDescriptor;
025import org.apache.hadoop.hbase.HTableDescriptor;
026import org.apache.hadoop.hbase.NamespaceDescriptor;
027import org.apache.hadoop.hbase.NamespaceNotFoundException;
028import org.apache.hadoop.hbase.TableName;
029import org.apache.hadoop.hbase.client.Admin;
030import org.apache.hadoop.hbase.client.Connection;
031import org.apache.hadoop.hbase.client.ConnectionFactory;
032import org.apache.hadoop.hbase.client.Delete;
033import org.apache.hadoop.hbase.client.Get;
034import org.apache.hadoop.hbase.client.Put;
035import org.apache.hadoop.hbase.client.Result;
036import org.apache.hadoop.hbase.client.Table;
037import org.apache.hadoop.hbase.util.Bytes;
038
039/**
040 * Successful running of this application requires access to an active instance
041 * of HBase. For install instructions for a standalone instance of HBase, please
042 * refer to https://hbase.apache.org/book.html#quickstart
043 */
044public final class HelloHBase {
045
046  protected static final String MY_NAMESPACE_NAME = "myTestNamespace";
047  static final TableName MY_TABLE_NAME = TableName.valueOf("myTestTable");
048  static final byte[] MY_COLUMN_FAMILY_NAME = Bytes.toBytes("cf");
049  static final byte[] MY_FIRST_COLUMN_QUALIFIER
050          = Bytes.toBytes("myFirstColumn");
051  static final byte[] MY_SECOND_COLUMN_QUALIFIER
052          = Bytes.toBytes("mySecondColumn");
053  static final byte[] MY_ROW_ID = Bytes.toBytes("rowId01");
054
055  // Private constructor included here to avoid checkstyle warnings
056  private HelloHBase() {
057  }
058
059  public static void main(final String[] args) throws IOException {
060    final boolean deleteAllAtEOJ = true;
061
062    /**
063     * ConnectionFactory#createConnection() automatically looks for
064     * hbase-site.xml (HBase configuration parameters) on the system's
065     * CLASSPATH, to enable creation of Connection to HBase via ZooKeeper.
066     */
067    try (Connection connection = ConnectionFactory.createConnection();
068            Admin admin = connection.getAdmin()) {
069
070      admin.getClusterStatus(); // assure connection successfully established
071      System.out.println("\n*** Hello HBase! -- Connection has been "
072              + "established via ZooKeeper!!\n");
073
074      createNamespaceAndTable(admin);
075
076      System.out.println("Getting a Table object for [" + MY_TABLE_NAME
077              + "] with which to perform CRUD operations in HBase.");
078      try (Table table = connection.getTable(MY_TABLE_NAME)) {
079
080        putRowToTable(table);
081        getAndPrintRowContents(table);
082
083        if (deleteAllAtEOJ) {
084          deleteRow(table);
085        }
086      }
087
088      if (deleteAllAtEOJ) {
089        deleteNamespaceAndTable(admin);
090      }
091    }
092  }
093
094  /**
095   * Invokes Admin#createNamespace and Admin#createTable to create a namespace
096   * with a table that has one column-family.
097   *
098   * @param admin Standard Admin object
099   * @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}