001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hbase.archetypes.exemplars.shaded_client;
019
020import java.io.IOException;
021import java.util.Map.Entry;
022import java.util.NavigableMap;
023import org.apache.hadoop.hbase.NamespaceDescriptor;
024import org.apache.hadoop.hbase.NamespaceNotFoundException;
025import org.apache.hadoop.hbase.TableName;
026import org.apache.hadoop.hbase.client.Admin;
027import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
028import org.apache.hadoop.hbase.client.Connection;
029import org.apache.hadoop.hbase.client.ConnectionFactory;
030import org.apache.hadoop.hbase.client.Delete;
031import org.apache.hadoop.hbase.client.Get;
032import org.apache.hadoop.hbase.client.Put;
033import org.apache.hadoop.hbase.client.Result;
034import org.apache.hadoop.hbase.client.Table;
035import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
036import org.apache.hadoop.hbase.util.Bytes;
037
038/**
039 * Successful running of this application requires access to an active instance of HBase. For
040 * install instructions for a standalone instance of HBase, please refer to
041 * https://hbase.apache.org/book.html#quickstart
042 */
043public final class HelloHBase {
044
045  static final String MY_NAMESPACE_NAME = "myTestNamespace";
046  static final TableName MY_TABLE_NAME = TableName.valueOf("myTestTable");
047  static final byte[] MY_COLUMN_FAMILY_NAME = Bytes.toBytes("cf");
048  static final byte[] MY_FIRST_COLUMN_QUALIFIER = Bytes.toBytes("myFirstColumn");
049  static final byte[] MY_SECOND_COLUMN_QUALIFIER = Bytes.toBytes("mySecondColumn");
050  static final byte[] MY_ROW_ID = Bytes.toBytes("rowId01");
051
052  // Private constructor included here to avoid checkstyle warnings
053  private HelloHBase() {
054  }
055
056  public static void main(final String[] args) throws IOException {
057    final boolean deleteAllAtEOJ = true;
058
059    /**
060     * ConnectionFactory#createConnection() automatically looks for hbase-site.xml (HBase
061     * configuration parameters) on the system's CLASSPATH, to enable creation of Connection to
062     * HBase via ZooKeeper.
063     */
064    try (Connection connection = ConnectionFactory.createConnection();
065      Admin admin = connection.getAdmin()) {
066      admin.getClusterMetrics(); // assure connection successfully established
067      System.out
068        .println("\n*** Hello HBase! -- Connection has been " + "established via ZooKeeper!!\n");
069
070      createNamespaceAndTable(admin);
071
072      System.out.println("Getting a Table object for [" + MY_TABLE_NAME
073        + "] with which to perform CRUD operations in HBase.");
074      try (Table table = connection.getTable(MY_TABLE_NAME)) {
075
076        putRowToTable(table);
077        getAndPrintRowContents(table);
078
079        if (deleteAllAtEOJ) {
080          deleteRow(table);
081        }
082      }
083
084      if (deleteAllAtEOJ) {
085        deleteNamespaceAndTable(admin);
086      }
087    }
088  }
089
090  /**
091   * Invokes Admin#createNamespace and Admin#createTable to create a namespace with a table that has
092   * one column-family.
093   * @param admin Standard Admin object
094   * @throws IOException If IO problem encountered
095   */
096  static void createNamespaceAndTable(final Admin admin) throws IOException {
097
098    if (!namespaceExists(admin, MY_NAMESPACE_NAME)) {
099      System.out.println("Creating Namespace [" + MY_NAMESPACE_NAME + "].");
100
101      admin.createNamespace(NamespaceDescriptor.create(MY_NAMESPACE_NAME).build());
102    }
103    if (!admin.tableExists(MY_TABLE_NAME)) {
104      System.out.println("Creating Table [" + MY_TABLE_NAME.getNameAsString()
105        + "], with one Column Family [" + Bytes.toString(MY_COLUMN_FAMILY_NAME) + "].");
106
107      admin.createTable(TableDescriptorBuilder.newBuilder(MY_TABLE_NAME)
108        .setColumnFamily(ColumnFamilyDescriptorBuilder.of(MY_COLUMN_FAMILY_NAME)).build());
109    }
110  }
111
112  /**
113   * Invokes Table#put to store a row (with two new columns created 'on the fly') into the table.
114   * @param table Standard Table object (used for CRUD operations).
115   * @throws IOException If IO problem encountered
116   */
117  static void putRowToTable(final Table table) throws IOException {
118
119    table.put(new Put(MY_ROW_ID)
120      .addColumn(MY_COLUMN_FAMILY_NAME, MY_FIRST_COLUMN_QUALIFIER, Bytes.toBytes("Hello"))
121      .addColumn(MY_COLUMN_FAMILY_NAME, MY_SECOND_COLUMN_QUALIFIER, Bytes.toBytes("World!")));
122
123    System.out.println("Row [" + Bytes.toString(MY_ROW_ID) + "] was put into Table ["
124      + table.getName().getNameAsString() + "] in HBase;\n"
125      + "  the row's two columns (created 'on the fly') are: ["
126      + Bytes.toString(MY_COLUMN_FAMILY_NAME) + ":" + Bytes.toString(MY_FIRST_COLUMN_QUALIFIER)
127      + "] and [" + Bytes.toString(MY_COLUMN_FAMILY_NAME) + ":"
128      + Bytes.toString(MY_SECOND_COLUMN_QUALIFIER) + "]");
129  }
130
131  /**
132   * Invokes Table#get and prints out the contents of the retrieved row.
133   * @param table Standard Table object
134   * @throws IOException If IO problem encountered
135   */
136  static void getAndPrintRowContents(final Table table) throws IOException {
137
138    Result row = table.get(new Get(MY_ROW_ID));
139
140    System.out.println("Row [" + Bytes.toString(row.getRow()) + "] was retrieved from Table ["
141      + table.getName().getNameAsString() + "] in HBase, with the following content:");
142
143    for (Entry<byte[], NavigableMap<byte[], byte[]>> colFamilyEntry : row.getNoVersionMap()
144      .entrySet()) {
145      String columnFamilyName = Bytes.toString(colFamilyEntry.getKey());
146
147      System.out.println("  Columns in Column Family [" + columnFamilyName + "]:");
148
149      for (Entry<byte[], byte[]> columnNameAndValueMap : colFamilyEntry.getValue().entrySet()) {
150
151        System.out.println("    Value of Column [" + columnFamilyName + ":"
152          + Bytes.toString(columnNameAndValueMap.getKey()) + "] == "
153          + Bytes.toString(columnNameAndValueMap.getValue()));
154      }
155    }
156  }
157
158  /**
159   * Checks to see whether a namespace exists.
160   * @param admin         Standard Admin object
161   * @param namespaceName Name of namespace
162   * @return true If namespace exists
163   * @throws IOException If IO problem encountered
164   */
165  static boolean namespaceExists(final Admin admin, final String namespaceName) throws IOException {
166    try {
167      admin.getNamespaceDescriptor(namespaceName);
168    } catch (NamespaceNotFoundException e) {
169      return false;
170    }
171    return true;
172  }
173
174  /**
175   * Invokes Table#delete to delete test data (i.e. the row)
176   * @param table Standard Table object
177   * @throws IOException If IO problem is encountered
178   */
179  static void deleteRow(final Table table) throws IOException {
180    System.out.println("Deleting row [" + Bytes.toString(MY_ROW_ID) + "] from Table ["
181      + table.getName().getNameAsString() + "].");
182    table.delete(new Delete(MY_ROW_ID));
183  }
184
185  /**
186   * Invokes Admin#disableTable, Admin#deleteTable, and Admin#deleteNamespace to disable/delete
187   * Table and delete Namespace.
188   * @param admin Standard Admin object
189   * @throws IOException If IO problem is encountered
190   */
191  static void deleteNamespaceAndTable(final Admin admin) throws IOException {
192    if (admin.tableExists(MY_TABLE_NAME)) {
193      System.out.println("Disabling/deleting Table [" + MY_TABLE_NAME.getNameAsString() + "].");
194      admin.disableTable(MY_TABLE_NAME); // Disable a table before deleting it.
195      admin.deleteTable(MY_TABLE_NAME);
196    }
197    if (namespaceExists(admin, MY_NAMESPACE_NAME)) {
198      System.out.println("Deleting Namespace [" + MY_NAMESPACE_NAME + "].");
199      admin.deleteNamespace(MY_NAMESPACE_NAME);
200    }
201  }
202}