【Hbase学习之三】Hbase Java API

环境
  虚拟机:VMware 10
  Linux版本:CentOS-6.5-x86_64
  客户端:Xshell4
  FTP:Xftp4
  jdk8
  hadoop-2.6.5
  hbase-0.98.12.1-hadoop2

一、Protocol 

Google Protocol Buffer( 简称 Protobuf) 是 Google 公司内部的混合语言数据标准,目前已经正在使用的有超过 48,162 种报文格式定义和超过 12,183 个 .proto 文件。他们用于 RPC 系统和持续数据存储系统。
Protocol Buffers 是一种轻便高效的结构化数据存储格式,可以用于结构化数据串行化,或者说序列化。它很适合做数据存储或 RPC 数据交换格式。可用于通讯协议、数据存储等领域的语言无关、平台无关、可扩展的序列化结构数据格式。目前提供了 C++、Java、Python 三种语言的 API。

1、安装protobuf

[root@PCS102 src]# tar -zxvf protobuf-2.5.0.tar.gz -C /usr/local
[root@PCS102 src]# ./configure && make && make check && make install
[root@PCS102 protobuf-2.5.0]# whereis protoc
protoc: /usr/local/bin/protoc
[root@PCS102 protobuf-2.5.0]# /usr/local/bin/protoc --help
Usage: /usr/local/bin/protoc [OPTION] PROTO_FILES
Parse PROTO_FILES and generate output based on the options given:
-IPATH, --proto_path=PATH Specify the directory in which to search for
imports. May be specified multiple times;
directories will be searched in order. If not
given, the current working directory is used.
--version Show version info and exit.
-h, --help Show this text and exit.
--encode=MESSAGE_TYPE Read a text-format message of the given type
from standard input and write it in binary
to standard output. The message type must
be defined in PROTO_FILES or their imports.
--decode=MESSAGE_TYPE Read a binary message of the given type from
standard input and write it in text format
to standard output. The message type must
be defined in PROTO_FILES or their imports.
--decode_raw Read an arbitrary protocol message from
standard input and write the raw tag/value
pairs in text format to standard output. No
PROTO_FILES should be given when using this
flag.
-oFILE, Writes a FileDescriptorSet (a protocol buffer,
--descriptor_set_out=FILE defined in descriptor.proto) containing all of
the input files to FILE.
--include_imports When using --descriptor_set_out, also include
all dependencies of the input files in the
set, so that the set is self-contained.
--include_source_info When using --descriptor_set_out, do not strip
SourceCodeInfo from the FileDescriptorProto.
This results in vastly larger descriptors that
include information about the original
location of each decl in the source file as
well as surrounding comments.
--error_format=FORMAT Set the format in which to print errors.
FORMAT may be 'gcc' (the default) or 'msvs'
(Microsoft Visual Studio format).
--plugin=EXECUTABLE Specifies a plugin executable to use.
Normally, protoc searches the PATH for
plugins, but you may specify additional
executables not in the path using this flag.
Additionally, EXECUTABLE may be of the form
NAME=PATH, in which case the given plugin name
is mapped to the given executable even if
the executable's own name differs.
--cpp_out=OUT_DIR Generate C++ header and source.
--java_out=OUT_DIR Generate Java source file.
--python_out=OUT_DIR Generate Python source file.

 

2、使用
(1)、编写 .proto 文件
文件命名规则:小写类名.proto,注意类名不要和内部的消息名相同
举例:phone.proto

package com.wjy.hbase;
message PhoneDetail
{
  required string dnum=1;
  required string length=2;
  required string type=3;
  required string date=4;
}

message dayPhoneDetail
{
  repeated PhoneDetail dayPhoneDetail=1;
}

 

注意:里面等号后面的值不要相同 否则不成功

(2)、编译.proto 文件
命令语法:
protoc -I=源文件目录 --java_out=生成文件目录 .proto文件
示例:

[root@PCS102 ~]# /usr/local/bin/protoc -I=/root --java_out=/root /root/phone.proto
[root@PCS102 hbase]# pwd
/root/com/wjy/hbase
[root@PCS102 hbase]# ls
Phone.java
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: phone.proto

package com.wjy.hbase;

public final class Phone {
  private Phone() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
  }
  public interface PhoneDetailOrBuilder
      extends com.google.protobuf.MessageOrBuilder {

    // required string dnum = 1;
    /**
     * <code>required string dnum = 1;</code>
     */
    boolean hasDnum();
    /**
     * <code>required string dnum = 1;</code>
     */
    java.lang.String getDnum();
    /**
     * <code>required string dnum = 1;</code>
     */
    com.google.protobuf.ByteString
        getDnumBytes();

    // required string length = 2;
    /**
     * <code>required string length = 2;</code>
     */
    boolean hasLength();
    /**
     * <code>required string length = 2;</code>
     */
    java.lang.String getLength();
    /**
     * <code>required string length = 2;</code>
     */
    com.google.protobuf.ByteString
        getLengthBytes();

    // required string type = 3;
    /**
     * <code>required string type = 3;</code>
     */
    boolean hasType();
    /**
     * <code>required string type = 3;</code>
     */
    java.lang.String getType();
    /**
     * <code>required string type = 3;</code>
     */
    com.google.protobuf.ByteString
        getTypeBytes();

    // required string date = 4;
    /**
     * <code>required string date = 4;</code>
     */
    boolean hasDate();
    /**
     * <code>required string date = 4;</code>
     */
    java.lang.String getDate();
    /**
     * <code>required string date = 4;</code>
     */
    com.google.protobuf.ByteString
        getDateBytes();
  }
  /**
   * Protobuf type {@code com.wjy.hbase.PhoneDetail}
   */
  public static final class PhoneDetail extends
      com.google.protobuf.GeneratedMessage
      implements PhoneDetailOrBuilder {
    // Use PhoneDetail.newBuilder() to construct.
    private PhoneDetail(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
      super(builder);
      this.unknownFields = builder.getUnknownFields();
    }
    private PhoneDetail(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }

    private static final PhoneDetail defaultInstance;
    public static PhoneDetail getDefaultInstance() {
      return defaultInstance;
    }

    public PhoneDetail getDefaultInstanceForType() {
      return defaultInstance;
    }

    private final com.google.protobuf.UnknownFieldSet unknownFields;
    @java.lang.Override
    public final com.google.protobuf.UnknownFieldSet
        getUnknownFields() {
      return this.unknownFields;
    }
    private PhoneDetail(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      initFields();
      int mutable_bitField0_ = 0;
      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
          com.google.protobuf.UnknownFieldSet.newBuilder();
      try {
        boolean done = false;
        while (!done) {
          int tag = input.readTag();
          switch (tag) {
            case 0:
              done = true;
              break;
            default: {
              if (!parseUnknownField(input, unknownFields,
                                     extensionRegistry, tag)) {
                done = true;
              }
              break;
            }
            case 10: {
              bitField0_ |= 0x00000001;
              dnum_ = input.readBytes();
              break;
            }
            case 18: {
              bitField0_ |= 0x00000002;
              length_ = input.readBytes();
              break;
            }
            case 26: {
              bitField0_ |= 0x00000004;
              type_ = input.readBytes();
              break;
            }
            case 34: {
              bitField0_ |= 0x00000008;
              date_ = input.readBytes();
              break;
            }
          }
        }
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw e.setUnfinishedMessage(this);
      } catch (java.io.IOException e) {
        throw new com.google.protobuf.InvalidProtocolBufferException(
            e.getMessage()).setUnfinishedMessage(this);
      } finally {
        this.unknownFields = unknownFields.build();
        makeExtensionsImmutable();
      }
    }
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return com.wjy.hbase.Phone.internal_static_com_wjy_hbase_PhoneDetail_descriptor;
    }

    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return com.wjy.hbase.Phone.internal_static_com_wjy_hbase_PhoneDetail_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              com.wjy.hbase.Phone.PhoneDetail.class, com.wjy.hbase.Phone.PhoneDetail.Builder.class);
    }

    public static com.google.protobuf.Parser<PhoneDetail> PARSER =
        new com.google.protobuf.AbstractParser<PhoneDetail>() {
      public PhoneDetail parsePartialFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws com.google.protobuf.InvalidProtocolBufferException {
        return new PhoneDetail(input, extensionRegistry);
      }
    };

    @java.lang.Override
    public com.google.protobuf.Parser<PhoneDetail> getParserForType() {
      return PARSER;
    }

    private int bitField0_;
    // required string dnum = 1;
    public static final int DNUM_FIELD_NUMBER = 1;
    private java.lang.Object dnum_;
    /**
     * <code>required string dnum = 1;</code>
     */
    public boolean hasDnum() {
      return ((bitField0_ & 0x00000001) == 0x00000001);
    }
    /**
     * <code>required string dnum = 1;</code>
     */
    public java.lang.String getDnum() {
      java.lang.Object ref = dnum_;
      if (ref instanceof java.lang.String) {
        return (java.lang.String) ref;
      } else {
        com.google.protobuf.ByteString bs = 
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        if (bs.isValidUtf8()) {
          dnum_ = s;
        }
        return s;
      }
    }
    /**
     * <code>required string dnum = 1;</code>
     */
    public com.google.protobuf.ByteString
        getDnumBytes() {
      java.lang.Object ref = dnum_;
      if (ref instanceof java.lang.String) {
        com.google.protobuf.ByteString b = 
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        dnum_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

    // required string length = 2;
    public static final int LENGTH_FIELD_NUMBER = 2;
    private java.lang.Object length_;
    /**
     * <code>required string length = 2;</code>
     */
    public boolean hasLength() {
      return ((bitField0_ & 0x00000002) == 0x00000002);
    }
    /**
     * <code>required string length = 2;</code>
     */
    public java.lang.String getLength() {
      java.lang.Object ref = length_;
      if (ref instanceof java.lang.String) {
        return (java.lang.String) ref;
      } else {
        com.google.protobuf.ByteString bs = 
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        if (bs.isValidUtf8()) {
          length_ = s;
        }
        return s;
      }
    }
    /**
     * <code>required string length = 2;</code>
     */
    public com.google.protobuf.ByteString
        getLengthBytes() {
      java.lang.Object ref = length_;
      if (ref instanceof java.lang.String) {
        com.google.protobuf.ByteString b = 
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        length_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

    // required string type = 3;
    public static final int TYPE_FIELD_NUMBER = 3;
    private java.lang.Object type_;
    /**
     * <code>required string type = 3;</code>
     */
    public boolean hasType() {
      return ((bitField0_ & 0x00000004) == 0x00000004);
    }
    /**
     * <code>required string type = 3;</code>
     */
    public java.lang.String getType() {
      java.lang.Object ref = type_;
      if (ref instanceof java.lang.String) {
        return (java.lang.String) ref;
      } else {
        com.google.protobuf.ByteString bs = 
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        if (bs.isValidUtf8()) {
          type_ = s;
        }
        return s;
      }
    }
    /**
     * <code>required string type = 3;</code>
     */
    public com.google.protobuf.ByteString
        getTypeBytes() {
      java.lang.Object ref = type_;
      if (ref instanceof java.lang.String) {
        com.google.protobuf.ByteString b = 
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        type_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

    // required string date = 4;
    public static final int DATE_FIELD_NUMBER = 4;
    private java.lang.Object date_;
    /**
     * <code>required string date = 4;</code>
     */
    public boolean hasDate() {
      return ((bitField0_ & 0x00000008) == 0x00000008);
    }
    /**
     * <code>required string date = 4;</code>
     */
    public java.lang.String getDate() {
      java.lang.Object ref = date_;
      if (ref instanceof java.lang.String) {
        return (java.lang.String) ref;
      } else {
        com.google.protobuf.ByteString bs = 
            (com.google.protobuf.ByteString) ref;
        java.lang.String s = bs.toStringUtf8();
        if (bs.isValidUtf8()) {
          date_ = s;
        }
        return s;
      }
    }
    /**
     * <code>required string date = 4;</code>
     */
    public com.google.protobuf.ByteString
        getDateBytes() {
      java.lang.Object ref = date_;
      if (ref instanceof java.lang.String) {
        com.google.protobuf.ByteString b = 
            com.google.protobuf.ByteString.copyFromUtf8(
                (java.lang.String) ref);
        date_ = b;
        return b;
      } else {
        return (com.google.protobuf.ByteString) ref;
      }
    }

    private void initFields() {
      dnum_ = "";
      length_ = "";
      type_ = "";
      date_ = "";
    }
    private byte memoizedIsInitialized = -1;
    public final boolean isInitialized() {
      byte isInitialized = memoizedIsInitialized;
      if (isInitialized != -1) return isInitialized == 1;

      if (!hasDnum()) {
        memoizedIsInitialized = 0;
        return false;
      }
      if (!hasLength()) {
        memoizedIsInitialized = 0;
        return false;
      }
      if (!hasType()) {
        memoizedIsInitialized = 0;
        return false;
      }
      if (!hasDate()) {
        memoizedIsInitialized = 0;
        return false;
      }
      memoizedIsInitialized = 1;
      return true;
    }

    public void writeTo(com.google.protobuf.CodedOutputStream output)
                        throws java.io.IOException {
      getSerializedSize();
      if (((bitField0_ & 0x00000001) == 0x00000001)) {
        output.writeBytes(1, getDnumBytes());
      }
      if (((bitField0_ & 0x00000002) == 0x00000002)) {
        output.writeBytes(2, getLengthBytes());
      }
      if (((bitField0_ & 0x00000004) == 0x00000004)) {
        output.writeBytes(3, getTypeBytes());
      }
      if (((bitField0_ & 0x00000008) == 0x00000008)) {
        output.writeBytes(4, getDateBytes());
      }
      getUnknownFields().writeTo(output);
    }

    private int memoizedSerializedSize = -1;
    public int getSerializedSize() {
      int size = memoizedSerializedSize;
      if (size != -1) return size;

      size = 0;
      if (((bitField0_ & 0x00000001) == 0x00000001)) {
        size += com.google.protobuf.CodedOutputStream
          .computeBytesSize(1, getDnumBytes());
      }
      if (((bitField0_ & 0x00000002) == 0x00000002)) {
        size += com.google.protobuf.CodedOutputStream
          .computeBytesSize(2, getLengthBytes());
      }
      if (((bitField0_ & 0x00000004) == 0x00000004)) {
        size += com.google.protobuf.CodedOutputStream
          .computeBytesSize(3, getTypeBytes());
      }
      if (((bitField0_ & 0x00000008) == 0x00000008)) {
        size += com.google.protobuf.CodedOutputStream
          .computeBytesSize(4, getDateBytes());
      }
      size += getUnknownFields().getSerializedSize();
      memoizedSerializedSize = size;
      return size;
    }

    private static final long serialVersionUID = 0L;
    @java.lang.Override
    protected java.lang.Object writeReplace()
        throws java.io.ObjectStreamException {
      return super.writeReplace();
    }

    public static com.wjy.hbase.Phone.PhoneDetail parseFrom(
        com.google.protobuf.ByteString data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static com.wjy.hbase.Phone.PhoneDetail parseFrom(
        com.google.protobuf.ByteString data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static com.wjy.hbase.Phone.PhoneDetail parseFrom(byte[] data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static com.wjy.hbase.Phone.PhoneDetail parseFrom(
        byte[] data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static com.wjy.hbase.Phone.PhoneDetail parseFrom(java.io.InputStream input)
        throws java.io.IOException {
      return PARSER.parseFrom(input);
    }
    public static com.wjy.hbase.Phone.PhoneDetail parseFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseFrom(input, extensionRegistry);
    }
    public static com.wjy.hbase.Phone.PhoneDetail parseDelimitedFrom(java.io.InputStream input)
        throws java.io.IOException {
      return PARSER.parseDelimitedFrom(input);
    }
    public static com.wjy.hbase.Phone.PhoneDetail parseDelimitedFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseDelimitedFrom(input, extensionRegistry);
    }
    public static com.wjy.hbase.Phone.PhoneDetail parseFrom(
        com.google.protobuf.CodedInputStream input)
        throws java.io.IOException {
      return PARSER.parseFrom(input);
    }
    public static com.wjy.hbase.Phone.PhoneDetail parseFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseFrom(input, extensionRegistry);
    }

    public static Builder newBuilder() { return Builder.create(); }
    public Builder newBuilderForType() { return newBuilder(); }
    public static Builder newBuilder(com.wjy.hbase.Phone.PhoneDetail prototype) {
      return newBuilder().mergeFrom(prototype);
    }
    public Builder toBuilder() { return newBuilder(this); }

    @java.lang.Override
    protected Builder newBuilderForType(
        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
      Builder builder = new Builder(parent);
      return builder;
    }
    /**
     * Protobuf type {@code com.wjy.hbase.PhoneDetail}
     */
    public static final class Builder extends
        com.google.protobuf.GeneratedMessage.Builder<Builder>
       implements com.wjy.hbase.Phone.PhoneDetailOrBuilder {
      public static final com.google.protobuf.Descriptors.Descriptor
          getDescriptor() {
        return com.wjy.hbase.Phone.internal_static_com_wjy_hbase_PhoneDetail_descriptor;
      }

      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
          internalGetFieldAccessorTable() {
        return com.wjy.hbase.Phone.internal_static_com_wjy_hbase_PhoneDetail_fieldAccessorTable
            .ensureFieldAccessorsInitialized(
                com.wjy.hbase.Phone.PhoneDetail.class, com.wjy.hbase.Phone.PhoneDetail.Builder.class);
      }

      // Construct using com.wjy.hbase.Phone.PhoneDetail.newBuilder()
      private Builder() {
        maybeForceBuilderInitialization();
      }

      private Builder(
          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
        super(parent);
        maybeForceBuilderInitialization();
      }
      private void maybeForceBuilderInitialization() {
        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
        }
      }
      private static Builder create() {
        return new Builder();
      }

      public Builder clear() {
        super.clear();
        dnum_ = "";
        bitField0_ = (bitField0_ & ~0x00000001);
        length_ = "";
        bitField0_ = (bitField0_ & ~0x00000002);
        type_ = "";
        bitField0_ = (bitField0_ & ~0x00000004);
        date_ = "";
        bitField0_ = (bitField0_ & ~0x00000008);
        return this;
      }

      public Builder clone() {
        return create().mergeFrom(buildPartial());
      }

      public com.google.protobuf.Descriptors.Descriptor
          getDescriptorForType() {
        return com.wjy.hbase.Phone.internal_static_com_wjy_hbase_PhoneDetail_descriptor;
      }

      public com.wjy.hbase.Phone.PhoneDetail getDefaultInstanceForType() {
        return com.wjy.hbase.Phone.PhoneDetail.getDefaultInstance();
      }

      public com.wjy.hbase.Phone.PhoneDetail build() {
        com.wjy.hbase.Phone.PhoneDetail result = buildPartial();
        if (!result.isInitialized()) {
          throw newUninitializedMessageException(result);
        }
        return result;
      }

      public com.wjy.hbase.Phone.PhoneDetail buildPartial() {
        com.wjy.hbase.Phone.PhoneDetail result = new com.wjy.hbase.Phone.PhoneDetail(this);
        int from_bitField0_ = bitField0_;
        int to_bitField0_ = 0;
        if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
          to_bitField0_ |= 0x00000001;
        }
        result.dnum_ = dnum_;
        if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
          to_bitField0_ |= 0x00000002;
        }
        result.length_ = length_;
        if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
          to_bitField0_ |= 0x00000004;
        }
        result.type_ = type_;
        if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
          to_bitField0_ |= 0x00000008;
        }
        result.date_ = date_;
        result.bitField0_ = to_bitField0_;
        onBuilt();
        return result;
      }

      public Builder mergeFrom(com.google.protobuf.Message other) {
        if (other instanceof com.wjy.hbase.Phone.PhoneDetail) {
          return mergeFrom((com.wjy.hbase.Phone.PhoneDetail)other);
        } else {
          super.mergeFrom(other);
          return this;
        }
      }

      public Builder mergeFrom(com.wjy.hbase.Phone.PhoneDetail other) {
        if (other == com.wjy.hbase.Phone.PhoneDetail.getDefaultInstance()) return this;
        if (other.hasDnum()) {
          bitField0_ |= 0x00000001;
          dnum_ = other.dnum_;
          onChanged();
        }
        if (other.hasLength()) {
          bitField0_ |= 0x00000002;
          length_ = other.length_;
          onChanged();
        }
        if (other.hasType()) {
          bitField0_ |= 0x00000004;
          type_ = other.type_;
          onChanged();
        }
        if (other.hasDate()) {
          bitField0_ |= 0x00000008;
          date_ = other.date_;
          onChanged();
        }
        this.mergeUnknownFields(other.getUnknownFields());
        return this;
      }

      public final boolean isInitialized() {
        if (!hasDnum()) {
          
          return false;
        }
        if (!hasLength()) {
          
          return false;
        }
        if (!hasType()) {
          
          return false;
        }
        if (!hasDate()) {
          
          return false;
        }
        return true;
      }

      public Builder mergeFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws java.io.IOException {
        com.wjy.hbase.Phone.PhoneDetail parsedMessage = null;
        try {
          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
          parsedMessage = (com.wjy.hbase.Phone.PhoneDetail) e.getUnfinishedMessage();
          throw e;
        } finally {
          if (parsedMessage != null) {
            mergeFrom(parsedMessage);
          }
        }
        return this;
      }
      private int bitField0_;

      // required string dnum = 1;
      private java.lang.Object dnum_ = "";
      /**
       * <code>required string dnum = 1;</code>
       */
      public boolean hasDnum() {
        return ((bitField0_ & 0x00000001) == 0x00000001);
      }
      /**
       * <code>required string dnum = 1;</code>
       */
      public java.lang.String getDnum() {
        java.lang.Object ref = dnum_;
        if (!(ref instanceof java.lang.String)) {
          java.lang.String s = ((com.google.protobuf.ByteString) ref)
              .toStringUtf8();
          dnum_ = s;
          return s;
        } else {
          return (java.lang.String) ref;
        }
      }
      /**
       * <code>required string dnum = 1;</code>
       */
      public com.google.protobuf.ByteString
          getDnumBytes() {
        java.lang.Object ref = dnum_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b = 
              com.google.protobuf.ByteString.copyFromUtf8(
                  (java.lang.String) ref);
          dnum_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * <code>required string dnum = 1;</code>
       */
      public Builder setDnum(
          java.lang.String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000001;
        dnum_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>required string dnum = 1;</code>
       */
      public Builder clearDnum() {
        bitField0_ = (bitField0_ & ~0x00000001);
        dnum_ = getDefaultInstance().getDnum();
        onChanged();
        return this;
      }
      /**
       * <code>required string dnum = 1;</code>
       */
      public Builder setDnumBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000001;
        dnum_ = value;
        onChanged();
        return this;
      }

      // required string length = 2;
      private java.lang.Object length_ = "";
      /**
       * <code>required string length = 2;</code>
       */
      public boolean hasLength() {
        return ((bitField0_ & 0x00000002) == 0x00000002);
      }
      /**
       * <code>required string length = 2;</code>
       */
      public java.lang.String getLength() {
        java.lang.Object ref = length_;
        if (!(ref instanceof java.lang.String)) {
          java.lang.String s = ((com.google.protobuf.ByteString) ref)
              .toStringUtf8();
          length_ = s;
          return s;
        } else {
          return (java.lang.String) ref;
        }
      }
      /**
       * <code>required string length = 2;</code>
       */
      public com.google.protobuf.ByteString
          getLengthBytes() {
        java.lang.Object ref = length_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b = 
              com.google.protobuf.ByteString.copyFromUtf8(
                  (java.lang.String) ref);
          length_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * <code>required string length = 2;</code>
       */
      public Builder setLength(
          java.lang.String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000002;
        length_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>required string length = 2;</code>
       */
      public Builder clearLength() {
        bitField0_ = (bitField0_ & ~0x00000002);
        length_ = getDefaultInstance().getLength();
        onChanged();
        return this;
      }
      /**
       * <code>required string length = 2;</code>
       */
      public Builder setLengthBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000002;
        length_ = value;
        onChanged();
        return this;
      }

      // required string type = 3;
      private java.lang.Object type_ = "";
      /**
       * <code>required string type = 3;</code>
       */
      public boolean hasType() {
        return ((bitField0_ & 0x00000004) == 0x00000004);
      }
      /**
       * <code>required string type = 3;</code>
       */
      public java.lang.String getType() {
        java.lang.Object ref = type_;
        if (!(ref instanceof java.lang.String)) {
          java.lang.String s = ((com.google.protobuf.ByteString) ref)
              .toStringUtf8();
          type_ = s;
          return s;
        } else {
          return (java.lang.String) ref;
        }
      }
      /**
       * <code>required string type = 3;</code>
       */
      public com.google.protobuf.ByteString
          getTypeBytes() {
        java.lang.Object ref = type_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b = 
              com.google.protobuf.ByteString.copyFromUtf8(
                  (java.lang.String) ref);
          type_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * <code>required string type = 3;</code>
       */
      public Builder setType(
          java.lang.String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000004;
        type_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>required string type = 3;</code>
       */
      public Builder clearType() {
        bitField0_ = (bitField0_ & ~0x00000004);
        type_ = getDefaultInstance().getType();
        onChanged();
        return this;
      }
      /**
       * <code>required string type = 3;</code>
       */
      public Builder setTypeBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000004;
        type_ = value;
        onChanged();
        return this;
      }

      // required string date = 4;
      private java.lang.Object date_ = "";
      /**
       * <code>required string date = 4;</code>
       */
      public boolean hasDate() {
        return ((bitField0_ & 0x00000008) == 0x00000008);
      }
      /**
       * <code>required string date = 4;</code>
       */
      public java.lang.String getDate() {
        java.lang.Object ref = date_;
        if (!(ref instanceof java.lang.String)) {
          java.lang.String s = ((com.google.protobuf.ByteString) ref)
              .toStringUtf8();
          date_ = s;
          return s;
        } else {
          return (java.lang.String) ref;
        }
      }
      /**
       * <code>required string date = 4;</code>
       */
      public com.google.protobuf.ByteString
          getDateBytes() {
        java.lang.Object ref = date_;
        if (ref instanceof String) {
          com.google.protobuf.ByteString b = 
              com.google.protobuf.ByteString.copyFromUtf8(
                  (java.lang.String) ref);
          date_ = b;
          return b;
        } else {
          return (com.google.protobuf.ByteString) ref;
        }
      }
      /**
       * <code>required string date = 4;</code>
       */
      public Builder setDate(
          java.lang.String value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000008;
        date_ = value;
        onChanged();
        return this;
      }
      /**
       * <code>required string date = 4;</code>
       */
      public Builder clearDate() {
        bitField0_ = (bitField0_ & ~0x00000008);
        date_ = getDefaultInstance().getDate();
        onChanged();
        return this;
      }
      /**
       * <code>required string date = 4;</code>
       */
      public Builder setDateBytes(
          com.google.protobuf.ByteString value) {
        if (value == null) {
    throw new NullPointerException();
  }
  bitField0_ |= 0x00000008;
        date_ = value;
        onChanged();
        return this;
      }

      // @@protoc_insertion_point(builder_scope:com.wjy.hbase.PhoneDetail)
    }

    static {
      defaultInstance = new PhoneDetail(true);
      defaultInstance.initFields();
    }

    // @@protoc_insertion_point(class_scope:com.wjy.hbase.PhoneDetail)
  }

  public interface dayPhoneDetailOrBuilder
      extends com.google.protobuf.MessageOrBuilder {

    // repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;
    /**
     * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
     */
    java.util.List<com.wjy.hbase.Phone.PhoneDetail> 
        getDayPhoneDetailList();
    /**
     * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
     */
    com.wjy.hbase.Phone.PhoneDetail getDayPhoneDetail(int index);
    /**
     * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
     */
    int getDayPhoneDetailCount();
    /**
     * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
     */
    java.util.List<? extends com.wjy.hbase.Phone.PhoneDetailOrBuilder> 
        getDayPhoneDetailOrBuilderList();
    /**
     * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
     */
    com.wjy.hbase.Phone.PhoneDetailOrBuilder getDayPhoneDetailOrBuilder(
        int index);
  }
  /**
   * Protobuf type {@code com.wjy.hbase.dayPhoneDetail}
   */
  public static final class dayPhoneDetail extends
      com.google.protobuf.GeneratedMessage
      implements dayPhoneDetailOrBuilder {
    // Use dayPhoneDetail.newBuilder() to construct.
    private dayPhoneDetail(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
      super(builder);
      this.unknownFields = builder.getUnknownFields();
    }
    private dayPhoneDetail(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }

    private static final dayPhoneDetail defaultInstance;
    public static dayPhoneDetail getDefaultInstance() {
      return defaultInstance;
    }

    public dayPhoneDetail getDefaultInstanceForType() {
      return defaultInstance;
    }

    private final com.google.protobuf.UnknownFieldSet unknownFields;
    @java.lang.Override
    public final com.google.protobuf.UnknownFieldSet
        getUnknownFields() {
      return this.unknownFields;
    }
    private dayPhoneDetail(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      initFields();
      int mutable_bitField0_ = 0;
      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
          com.google.protobuf.UnknownFieldSet.newBuilder();
      try {
        boolean done = false;
        while (!done) {
          int tag = input.readTag();
          switch (tag) {
            case 0:
              done = true;
              break;
            default: {
              if (!parseUnknownField(input, unknownFields,
                                     extensionRegistry, tag)) {
                done = true;
              }
              break;
            }
            case 10: {
              if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
                dayPhoneDetail_ = new java.util.ArrayList<com.wjy.hbase.Phone.PhoneDetail>();
                mutable_bitField0_ |= 0x00000001;
              }
              dayPhoneDetail_.add(input.readMessage(com.wjy.hbase.Phone.PhoneDetail.PARSER, extensionRegistry));
              break;
            }
          }
        }
      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
        throw e.setUnfinishedMessage(this);
      } catch (java.io.IOException e) {
        throw new com.google.protobuf.InvalidProtocolBufferException(
            e.getMessage()).setUnfinishedMessage(this);
      } finally {
        if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
          dayPhoneDetail_ = java.util.Collections.unmodifiableList(dayPhoneDetail_);
        }
        this.unknownFields = unknownFields.build();
        makeExtensionsImmutable();
      }
    }
    public static final com.google.protobuf.Descriptors.Descriptor
        getDescriptor() {
      return com.wjy.hbase.Phone.internal_static_com_wjy_hbase_dayPhoneDetail_descriptor;
    }

    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
        internalGetFieldAccessorTable() {
      return com.wjy.hbase.Phone.internal_static_com_wjy_hbase_dayPhoneDetail_fieldAccessorTable
          .ensureFieldAccessorsInitialized(
              com.wjy.hbase.Phone.dayPhoneDetail.class, com.wjy.hbase.Phone.dayPhoneDetail.Builder.class);
    }

    public static com.google.protobuf.Parser<dayPhoneDetail> PARSER =
        new com.google.protobuf.AbstractParser<dayPhoneDetail>() {
      public dayPhoneDetail parsePartialFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws com.google.protobuf.InvalidProtocolBufferException {
        return new dayPhoneDetail(input, extensionRegistry);
      }
    };

    @java.lang.Override
    public com.google.protobuf.Parser<dayPhoneDetail> getParserForType() {
      return PARSER;
    }

    // repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;
    public static final int DAYPHONEDETAIL_FIELD_NUMBER = 1;
    private java.util.List<com.wjy.hbase.Phone.PhoneDetail> dayPhoneDetail_;
    /**
     * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
     */
    public java.util.List<com.wjy.hbase.Phone.PhoneDetail> getDayPhoneDetailList() {
      return dayPhoneDetail_;
    }
    /**
     * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
     */
    public java.util.List<? extends com.wjy.hbase.Phone.PhoneDetailOrBuilder> 
        getDayPhoneDetailOrBuilderList() {
      return dayPhoneDetail_;
    }
    /**
     * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
     */
    public int getDayPhoneDetailCount() {
      return dayPhoneDetail_.size();
    }
    /**
     * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
     */
    public com.wjy.hbase.Phone.PhoneDetail getDayPhoneDetail(int index) {
      return dayPhoneDetail_.get(index);
    }
    /**
     * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
     */
    public com.wjy.hbase.Phone.PhoneDetailOrBuilder getDayPhoneDetailOrBuilder(
        int index) {
      return dayPhoneDetail_.get(index);
    }

    private void initFields() {
      dayPhoneDetail_ = java.util.Collections.emptyList();
    }
    private byte memoizedIsInitialized = -1;
    public final boolean isInitialized() {
      byte isInitialized = memoizedIsInitialized;
      if (isInitialized != -1) return isInitialized == 1;

      for (int i = 0; i < getDayPhoneDetailCount(); i++) {
        if (!getDayPhoneDetail(i).isInitialized()) {
          memoizedIsInitialized = 0;
          return false;
        }
      }
      memoizedIsInitialized = 1;
      return true;
    }

    public void writeTo(com.google.protobuf.CodedOutputStream output)
                        throws java.io.IOException {
      getSerializedSize();
      for (int i = 0; i < dayPhoneDetail_.size(); i++) {
        output.writeMessage(1, dayPhoneDetail_.get(i));
      }
      getUnknownFields().writeTo(output);
    }

    private int memoizedSerializedSize = -1;
    public int getSerializedSize() {
      int size = memoizedSerializedSize;
      if (size != -1) return size;

      size = 0;
      for (int i = 0; i < dayPhoneDetail_.size(); i++) {
        size += com.google.protobuf.CodedOutputStream
          .computeMessageSize(1, dayPhoneDetail_.get(i));
      }
      size += getUnknownFields().getSerializedSize();
      memoizedSerializedSize = size;
      return size;
    }

    private static final long serialVersionUID = 0L;
    @java.lang.Override
    protected java.lang.Object writeReplace()
        throws java.io.ObjectStreamException {
      return super.writeReplace();
    }

    public static com.wjy.hbase.Phone.dayPhoneDetail parseFrom(
        com.google.protobuf.ByteString data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static com.wjy.hbase.Phone.dayPhoneDetail parseFrom(
        com.google.protobuf.ByteString data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static com.wjy.hbase.Phone.dayPhoneDetail parseFrom(byte[] data)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data);
    }
    public static com.wjy.hbase.Phone.dayPhoneDetail parseFrom(
        byte[] data,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws com.google.protobuf.InvalidProtocolBufferException {
      return PARSER.parseFrom(data, extensionRegistry);
    }
    public static com.wjy.hbase.Phone.dayPhoneDetail parseFrom(java.io.InputStream input)
        throws java.io.IOException {
      return PARSER.parseFrom(input);
    }
    public static com.wjy.hbase.Phone.dayPhoneDetail parseFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseFrom(input, extensionRegistry);
    }
    public static com.wjy.hbase.Phone.dayPhoneDetail parseDelimitedFrom(java.io.InputStream input)
        throws java.io.IOException {
      return PARSER.parseDelimitedFrom(input);
    }
    public static com.wjy.hbase.Phone.dayPhoneDetail parseDelimitedFrom(
        java.io.InputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseDelimitedFrom(input, extensionRegistry);
    }
    public static com.wjy.hbase.Phone.dayPhoneDetail parseFrom(
        com.google.protobuf.CodedInputStream input)
        throws java.io.IOException {
      return PARSER.parseFrom(input);
    }
    public static com.wjy.hbase.Phone.dayPhoneDetail parseFrom(
        com.google.protobuf.CodedInputStream input,
        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
        throws java.io.IOException {
      return PARSER.parseFrom(input, extensionRegistry);
    }

    public static Builder newBuilder() { return Builder.create(); }
    public Builder newBuilderForType() { return newBuilder(); }
    public static Builder newBuilder(com.wjy.hbase.Phone.dayPhoneDetail prototype) {
      return newBuilder().mergeFrom(prototype);
    }
    public Builder toBuilder() { return newBuilder(this); }

    @java.lang.Override
    protected Builder newBuilderForType(
        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
      Builder builder = new Builder(parent);
      return builder;
    }
    /**
     * Protobuf type {@code com.wjy.hbase.dayPhoneDetail}
     */
    public static final class Builder extends
        com.google.protobuf.GeneratedMessage.Builder<Builder>
       implements com.wjy.hbase.Phone.dayPhoneDetailOrBuilder {
      public static final com.google.protobuf.Descriptors.Descriptor
          getDescriptor() {
        return com.wjy.hbase.Phone.internal_static_com_wjy_hbase_dayPhoneDetail_descriptor;
      }

      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
          internalGetFieldAccessorTable() {
        return com.wjy.hbase.Phone.internal_static_com_wjy_hbase_dayPhoneDetail_fieldAccessorTable
            .ensureFieldAccessorsInitialized(
                com.wjy.hbase.Phone.dayPhoneDetail.class, com.wjy.hbase.Phone.dayPhoneDetail.Builder.class);
      }

      // Construct using com.wjy.hbase.Phone.dayPhoneDetail.newBuilder()
      private Builder() {
        maybeForceBuilderInitialization();
      }

      private Builder(
          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
        super(parent);
        maybeForceBuilderInitialization();
      }
      private void maybeForceBuilderInitialization() {
        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
          getDayPhoneDetailFieldBuilder();
        }
      }
      private static Builder create() {
        return new Builder();
      }

      public Builder clear() {
        super.clear();
        if (dayPhoneDetailBuilder_ == null) {
          dayPhoneDetail_ = java.util.Collections.emptyList();
          bitField0_ = (bitField0_ & ~0x00000001);
        } else {
          dayPhoneDetailBuilder_.clear();
        }
        return this;
      }

      public Builder clone() {
        return create().mergeFrom(buildPartial());
      }

      public com.google.protobuf.Descriptors.Descriptor
          getDescriptorForType() {
        return com.wjy.hbase.Phone.internal_static_com_wjy_hbase_dayPhoneDetail_descriptor;
      }

      public com.wjy.hbase.Phone.dayPhoneDetail getDefaultInstanceForType() {
        return com.wjy.hbase.Phone.dayPhoneDetail.getDefaultInstance();
      }

      public com.wjy.hbase.Phone.dayPhoneDetail build() {
        com.wjy.hbase.Phone.dayPhoneDetail result = buildPartial();
        if (!result.isInitialized()) {
          throw newUninitializedMessageException(result);
        }
        return result;
      }

      public com.wjy.hbase.Phone.dayPhoneDetail buildPartial() {
        com.wjy.hbase.Phone.dayPhoneDetail result = new com.wjy.hbase.Phone.dayPhoneDetail(this);
        int from_bitField0_ = bitField0_;
        if (dayPhoneDetailBuilder_ == null) {
          if (((bitField0_ & 0x00000001) == 0x00000001)) {
            dayPhoneDetail_ = java.util.Collections.unmodifiableList(dayPhoneDetail_);
            bitField0_ = (bitField0_ & ~0x00000001);
          }
          result.dayPhoneDetail_ = dayPhoneDetail_;
        } else {
          result.dayPhoneDetail_ = dayPhoneDetailBuilder_.build();
        }
        onBuilt();
        return result;
      }

      public Builder mergeFrom(com.google.protobuf.Message other) {
        if (other instanceof com.wjy.hbase.Phone.dayPhoneDetail) {
          return mergeFrom((com.wjy.hbase.Phone.dayPhoneDetail)other);
        } else {
          super.mergeFrom(other);
          return this;
        }
      }

      public Builder mergeFrom(com.wjy.hbase.Phone.dayPhoneDetail other) {
        if (other == com.wjy.hbase.Phone.dayPhoneDetail.getDefaultInstance()) return this;
        if (dayPhoneDetailBuilder_ == null) {
          if (!other.dayPhoneDetail_.isEmpty()) {
            if (dayPhoneDetail_.isEmpty()) {
              dayPhoneDetail_ = other.dayPhoneDetail_;
              bitField0_ = (bitField0_ & ~0x00000001);
            } else {
              ensureDayPhoneDetailIsMutable();
              dayPhoneDetail_.addAll(other.dayPhoneDetail_);
            }
            onChanged();
          }
        } else {
          if (!other.dayPhoneDetail_.isEmpty()) {
            if (dayPhoneDetailBuilder_.isEmpty()) {
              dayPhoneDetailBuilder_.dispose();
              dayPhoneDetailBuilder_ = null;
              dayPhoneDetail_ = other.dayPhoneDetail_;
              bitField0_ = (bitField0_ & ~0x00000001);
              dayPhoneDetailBuilder_ = 
                com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
                   getDayPhoneDetailFieldBuilder() : null;
            } else {
              dayPhoneDetailBuilder_.addAllMessages(other.dayPhoneDetail_);
            }
          }
        }
        this.mergeUnknownFields(other.getUnknownFields());
        return this;
      }

      public final boolean isInitialized() {
        for (int i = 0; i < getDayPhoneDetailCount(); i++) {
          if (!getDayPhoneDetail(i).isInitialized()) {
            
            return false;
          }
        }
        return true;
      }

      public Builder mergeFrom(
          com.google.protobuf.CodedInputStream input,
          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
          throws java.io.IOException {
        com.wjy.hbase.Phone.dayPhoneDetail parsedMessage = null;
        try {
          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
          parsedMessage = (com.wjy.hbase.Phone.dayPhoneDetail) e.getUnfinishedMessage();
          throw e;
        } finally {
          if (parsedMessage != null) {
            mergeFrom(parsedMessage);
          }
        }
        return this;
      }
      private int bitField0_;

      // repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;
      private java.util.List<com.wjy.hbase.Phone.PhoneDetail> dayPhoneDetail_ =
        java.util.Collections.emptyList();
      private void ensureDayPhoneDetailIsMutable() {
        if (!((bitField0_ & 0x00000001) == 0x00000001)) {
          dayPhoneDetail_ = new java.util.ArrayList<com.wjy.hbase.Phone.PhoneDetail>(dayPhoneDetail_);
          bitField0_ |= 0x00000001;
         }
      }

      private com.google.protobuf.RepeatedFieldBuilder<
          com.wjy.hbase.Phone.PhoneDetail, com.wjy.hbase.Phone.PhoneDetail.Builder, com.wjy.hbase.Phone.PhoneDetailOrBuilder> dayPhoneDetailBuilder_;

      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public java.util.List<com.wjy.hbase.Phone.PhoneDetail> getDayPhoneDetailList() {
        if (dayPhoneDetailBuilder_ == null) {
          return java.util.Collections.unmodifiableList(dayPhoneDetail_);
        } else {
          return dayPhoneDetailBuilder_.getMessageList();
        }
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public int getDayPhoneDetailCount() {
        if (dayPhoneDetailBuilder_ == null) {
          return dayPhoneDetail_.size();
        } else {
          return dayPhoneDetailBuilder_.getCount();
        }
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public com.wjy.hbase.Phone.PhoneDetail getDayPhoneDetail(int index) {
        if (dayPhoneDetailBuilder_ == null) {
          return dayPhoneDetail_.get(index);
        } else {
          return dayPhoneDetailBuilder_.getMessage(index);
        }
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public Builder setDayPhoneDetail(
          int index, com.wjy.hbase.Phone.PhoneDetail value) {
        if (dayPhoneDetailBuilder_ == null) {
          if (value == null) {
            throw new NullPointerException();
          }
          ensureDayPhoneDetailIsMutable();
          dayPhoneDetail_.set(index, value);
          onChanged();
        } else {
          dayPhoneDetailBuilder_.setMessage(index, value);
        }
        return this;
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public Builder setDayPhoneDetail(
          int index, com.wjy.hbase.Phone.PhoneDetail.Builder builderForValue) {
        if (dayPhoneDetailBuilder_ == null) {
          ensureDayPhoneDetailIsMutable();
          dayPhoneDetail_.set(index, builderForValue.build());
          onChanged();
        } else {
          dayPhoneDetailBuilder_.setMessage(index, builderForValue.build());
        }
        return this;
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public Builder addDayPhoneDetail(com.wjy.hbase.Phone.PhoneDetail value) {
        if (dayPhoneDetailBuilder_ == null) {
          if (value == null) {
            throw new NullPointerException();
          }
          ensureDayPhoneDetailIsMutable();
          dayPhoneDetail_.add(value);
          onChanged();
        } else {
          dayPhoneDetailBuilder_.addMessage(value);
        }
        return this;
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public Builder addDayPhoneDetail(
          int index, com.wjy.hbase.Phone.PhoneDetail value) {
        if (dayPhoneDetailBuilder_ == null) {
          if (value == null) {
            throw new NullPointerException();
          }
          ensureDayPhoneDetailIsMutable();
          dayPhoneDetail_.add(index, value);
          onChanged();
        } else {
          dayPhoneDetailBuilder_.addMessage(index, value);
        }
        return this;
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public Builder addDayPhoneDetail(
          com.wjy.hbase.Phone.PhoneDetail.Builder builderForValue) {
        if (dayPhoneDetailBuilder_ == null) {
          ensureDayPhoneDetailIsMutable();
          dayPhoneDetail_.add(builderForValue.build());
          onChanged();
        } else {
          dayPhoneDetailBuilder_.addMessage(builderForValue.build());
        }
        return this;
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public Builder addDayPhoneDetail(
          int index, com.wjy.hbase.Phone.PhoneDetail.Builder builderForValue) {
        if (dayPhoneDetailBuilder_ == null) {
          ensureDayPhoneDetailIsMutable();
          dayPhoneDetail_.add(index, builderForValue.build());
          onChanged();
        } else {
          dayPhoneDetailBuilder_.addMessage(index, builderForValue.build());
        }
        return this;
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public Builder addAllDayPhoneDetail(
          java.lang.Iterable<? extends com.wjy.hbase.Phone.PhoneDetail> values) {
        if (dayPhoneDetailBuilder_ == null) {
          ensureDayPhoneDetailIsMutable();
          super.addAll(values, dayPhoneDetail_);
          onChanged();
        } else {
          dayPhoneDetailBuilder_.addAllMessages(values);
        }
        return this;
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public Builder clearDayPhoneDetail() {
        if (dayPhoneDetailBuilder_ == null) {
          dayPhoneDetail_ = java.util.Collections.emptyList();
          bitField0_ = (bitField0_ & ~0x00000001);
          onChanged();
        } else {
          dayPhoneDetailBuilder_.clear();
        }
        return this;
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public Builder removeDayPhoneDetail(int index) {
        if (dayPhoneDetailBuilder_ == null) {
          ensureDayPhoneDetailIsMutable();
          dayPhoneDetail_.remove(index);
          onChanged();
        } else {
          dayPhoneDetailBuilder_.remove(index);
        }
        return this;
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public com.wjy.hbase.Phone.PhoneDetail.Builder getDayPhoneDetailBuilder(
          int index) {
        return getDayPhoneDetailFieldBuilder().getBuilder(index);
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public com.wjy.hbase.Phone.PhoneDetailOrBuilder getDayPhoneDetailOrBuilder(
          int index) {
        if (dayPhoneDetailBuilder_ == null) {
          return dayPhoneDetail_.get(index);  } else {
          return dayPhoneDetailBuilder_.getMessageOrBuilder(index);
        }
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public java.util.List<? extends com.wjy.hbase.Phone.PhoneDetailOrBuilder> 
           getDayPhoneDetailOrBuilderList() {
        if (dayPhoneDetailBuilder_ != null) {
          return dayPhoneDetailBuilder_.getMessageOrBuilderList();
        } else {
          return java.util.Collections.unmodifiableList(dayPhoneDetail_);
        }
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public com.wjy.hbase.Phone.PhoneDetail.Builder addDayPhoneDetailBuilder() {
        return getDayPhoneDetailFieldBuilder().addBuilder(
            com.wjy.hbase.Phone.PhoneDetail.getDefaultInstance());
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public com.wjy.hbase.Phone.PhoneDetail.Builder addDayPhoneDetailBuilder(
          int index) {
        return getDayPhoneDetailFieldBuilder().addBuilder(
            index, com.wjy.hbase.Phone.PhoneDetail.getDefaultInstance());
      }
      /**
       * <code>repeated .com.wjy.hbase.PhoneDetail dayPhoneDetail = 1;</code>
       */
      public java.util.List<com.wjy.hbase.Phone.PhoneDetail.Builder> 
           getDayPhoneDetailBuilderList() {
        return getDayPhoneDetailFieldBuilder().getBuilderList();
      }
      private com.google.protobuf.RepeatedFieldBuilder<
          com.wjy.hbase.Phone.PhoneDetail, com.wjy.hbase.Phone.PhoneDetail.Builder, com.wjy.hbase.Phone.PhoneDetailOrBuilder> 
          getDayPhoneDetailFieldBuilder() {
        if (dayPhoneDetailBuilder_ == null) {
          dayPhoneDetailBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
              com.wjy.hbase.Phone.PhoneDetail, com.wjy.hbase.Phone.PhoneDetail.Builder, com.wjy.hbase.Phone.PhoneDetailOrBuilder>(
                  dayPhoneDetail_,
                  ((bitField0_ & 0x00000001) == 0x00000001),
                  getParentForChildren(),
                  isClean());
          dayPhoneDetail_ = null;
        }
        return dayPhoneDetailBuilder_;
      }

      // @@protoc_insertion_point(builder_scope:com.wjy.hbase.dayPhoneDetail)
    }

    static {
      defaultInstance = new dayPhoneDetail(true);
      defaultInstance.initFields();
    }

    // @@protoc_insertion_point(class_scope:com.wjy.hbase.dayPhoneDetail)
  }

  private static com.google.protobuf.Descriptors.Descriptor
    internal_static_com_wjy_hbase_PhoneDetail_descriptor;
  private static
    com.google.protobuf.GeneratedMessage.FieldAccessorTable
      internal_static_com_wjy_hbase_PhoneDetail_fieldAccessorTable;
  private static com.google.protobuf.Descriptors.Descriptor
    internal_static_com_wjy_hbase_dayPhoneDetail_descriptor;
  private static
    com.google.protobuf.GeneratedMessage.FieldAccessorTable
      internal_static_com_wjy_hbase_dayPhoneDetail_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\n\013phone.proto\022\rcom.wjy.hbase\"G\n\013PhoneDet" +
      "ail\022\014\n\004dnum\030\001 \002(\t\022\016\n\006length\030\002 \002(\t\022\014\n\004typ" +
      "e\030\003 \002(\t\022\014\n\004date\030\004 \002(\t\"D\n\016dayPhoneDetail\022" +
      "2\n\016dayPhoneDetail\030\001 \003(\0132\032.com.wjy.hbase." +
      "PhoneDetail"
    };
    com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
      new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
        public com.google.protobuf.ExtensionRegistry assignDescriptors(
            com.google.protobuf.Descriptors.FileDescriptor root) {
          descriptor = root;
          internal_static_com_wjy_hbase_PhoneDetail_descriptor =
            getDescriptor().getMessageTypes().get(0);
          internal_static_com_wjy_hbase_PhoneDetail_fieldAccessorTable = new
            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
              internal_static_com_wjy_hbase_PhoneDetail_descriptor,
              new java.lang.String[] { "Dnum", "Length", "Type", "Date", });
          internal_static_com_wjy_hbase_dayPhoneDetail_descriptor =
            getDescriptor().getMessageTypes().get(1);
          internal_static_com_wjy_hbase_dayPhoneDetail_fieldAccessorTable = new
            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
              internal_static_com_wjy_hbase_dayPhoneDetail_descriptor,
              new java.lang.String[] { "DayPhoneDetail", });
          return null;
        }
      };
    com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
        }, assigner);
  }

  // @@protoc_insertion_point(outer_class_scope)
}

 

 

三、示例

建立一个java工程,导入hadoop 相关jar,导入hbase相关jar,使用客户端(java API)操作hbase: 

示例一

package hbase;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.PrefixFilter;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import hbase.Phone.PhoneDetail;
public class HBaseDemo {

    HBaseAdmin admin;
    HTable htable;
    String TN = "phone";

    @Before
    public void init() throws Exception {
        Configuration conf = new Configuration();
        //ZK配置 用于连接hbase集群
        conf.set("hbase.zookeeper.quorum", "node1,node2,node3");
        //HBaseAdmin属于数据库对象
        admin = new HBaseAdmin(conf);
        //HTable 表对象  非线程安全的
        htable = new HTable(conf, TN.getBytes());
    }

    @Test
    public void creatTable() throws Exception {

        if (admin.tableExists(TN)) {
            admin.disableTable(TN);
            admin.deleteTable(TN);
        }

        //表描述
        HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(TN));
        //列族
        HColumnDescriptor cf = new HColumnDescriptor("cf".getBytes());
        desc.addFamily(cf);
        //创建表
        admin.createTable(desc);
    }

    /**
     * 写入数据
     */
    @Test
    public void insertDB() throws Exception {
        String rowKey = "1231231312";
        Put put = new Put(rowKey.getBytes());
        put.add("cf".getBytes(), "name".getBytes(), "xiaohong".getBytes());
        put.add("cf".getBytes(), "age".getBytes(), "23".getBytes());
        put.add("cf".getBytes(), "sex".getBytes(), "women".getBytes());
        htable.put(put);
    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

    /**
     * 有10个用户,每个用户随机产生100条记录
     * 
     * @throws Exception
     */
    @Test
    public void insertDB2() throws Exception {
        List<Put> puts = new ArrayList<Put>();
        for (int i = 0; i < 10; i++) {
            String phoneNum = getPhoneNum("186");
            for (int j = 0; j < 100; j++) {
                //对方号码
                String dnum = getPhoneNum("158");
                //通话时长
                String length = r.nextInt(99) + "";
                //主叫 被叫类型
                String type = r.nextInt(2) + "";
                //时间
                String dateStr = getDate("2018");
                String rowkey = phoneNum + "_" + (Long.MAX_VALUE - sdf.parse(dateStr).getTime());
                Put put = new Put(rowkey.getBytes());
                put.add("cf".getBytes(), "dnum".getBytes(), dnum.getBytes());
                put.add("cf".getBytes(), "length".getBytes(), length.getBytes());
                put.add("cf".getBytes(), "type".getBytes(), type.getBytes());
                put.add("cf".getBytes(), "date".getBytes(), dateStr.getBytes());
                puts.add(put);
            }
        }
        htable.put(puts);
    }

    @Test
    public void insertDB3() throws Exception {
        List<Put> puts = new ArrayList<Put>();
        for (int i = 0; i < 10; i++) {
            String phoneNum = getPhoneNum("186");
            for (int j = 0; j < 100; j++) {
                String dnum = getPhoneNum("158");
                String length = r.nextInt(99) + "";
                String type = r.nextInt(2) + "";
                String dateStr = getDate("2018");
                String rowkey = phoneNum + "_" + (Long.MAX_VALUE - sdf.parse(dateStr).getTime());
                Phone2.PhoneDetail.Builder phoneDetail = Phone2.PhoneDetail.newBuilder();
                phoneDetail.setDate(dateStr);
                phoneDetail.setDnum(dnum);
                phoneDetail.setLength(length);
                phoneDetail.setType(type);
                Put put = new Put(rowkey.getBytes());
                put.add("cf".getBytes(), "phoneDetail".getBytes(), phoneDetail.build().toByteArray());
                puts.add(put);
            }
        }
        htable.put(puts);
    }

    /**
     * 有十个用户,每个用户每天产生100条记录,将100条记录放到一个集合进行存储
     * 
     * @throws Exception
     */
    @Test
    public void insertDB4() throws Exception {
        List<Put> puts = new ArrayList<Put>();
        for (int i = 0; i < 10000; i++) {
            String phoneNum = getPhoneNum("186");
            String rowkey = phoneNum + "_" + (Long.MAX_VALUE - sdf.parse(getDate2("20180529")).getTime());
            Phone.dayPhoneDetail.Builder dayPhone = Phone.dayPhoneDetail.newBuilder();
            for (int j = 0; j < 100; j++) {
                String dnum = getPhoneNum("158");
                String length = r.nextInt(99) + "";
                String type = r.nextInt(2) + "";
                String dateStr = getDate("2018");
                Phone.PhoneDetail.Builder phoneDetail = Phone.PhoneDetail.newBuilder();
                phoneDetail.setDate(dateStr);
                phoneDetail.setDnum(dnum);
                phoneDetail.setLength(length);
                phoneDetail.setType(type);
                dayPhone.addDayPhoneDetail(phoneDetail);
            }
            Put put = new Put(rowkey.getBytes());
            put.add("cf".getBytes(), "day".getBytes(), dayPhone.build().toByteArray());
            puts.add(put);
        }
        htable.put(puts);
    }

    @Test
    public void getDB2() throws Exception{
        Get get = new Get("18686966381_9223370509257224807".getBytes());
        Result result = htable.get(get);
        Cell cell = result.getColumnLatestCell("cf".getBytes(), "day".getBytes());
        Phone.dayPhoneDetail dayPhone = Phone.dayPhoneDetail.parseFrom(CellUtil.cloneValue(cell));
        for (PhoneDetail pd : dayPhone.getDayPhoneDetailList()) {
            System.out.println(pd);
        }
    }
    
    
    private String getDate(String year) {
        return year + String.format("%02d%02d%02d%02d%02d",
                new Object[] { r.nextInt(12) + 1, r.nextInt(31) + 1, r.nextInt(24), r.nextInt(60), r.nextInt(60) });
    }

    private String getDate2(String yearMonthDay) {
        return yearMonthDay
                + String.format("%02d%02d%02d", new Object[] { r.nextInt(24), r.nextInt(60), r.nextInt(60) });
    }

    Random r = new Random();

    /**
     * 生成随机的手机号码
     * 
     * @param string
     * @return
     */
    private String getPhoneNum(String string) {
        return string + String.format("%08d", r.nextInt(99999999));
    }

    @Test
    public void getDB() throws Exception {
        String rowKey = "1231231312";
        Get get = new Get(rowKey.getBytes());
        //设置过滤条件
        get.addColumn("cf".getBytes(), "name".getBytes());
        get.addColumn("cf".getBytes(), "age".getBytes());
        get.addColumn("cf".getBytes(), "sex".getBytes());
        Result rs = htable.get(get);
        //rs.advance();//true if the next cell is found and CellScanner.current() will return a valid Cell
        Cell cell = rs.getColumnLatestCell("cf".getBytes(), "name".getBytes());
        Cell cell2 = rs.getColumnLatestCell("cf".getBytes(), "age".getBytes());
        Cell cell3 = rs.getColumnLatestCell("cf".getBytes(), "sex".getBytes());
        // System.out.println(new String(cell.getValue()));
        System.out.println(new String(CellUtil.cloneValue(cell)));
        System.out.println(new String(CellUtil.cloneValue(cell2)));
        System.out.println(new String(CellUtil.cloneValue(cell3)));

    }

    /**
     * 统计二月份到三月份的通话记录
     * 
     * @throws Exception
     */
    @Test
    public void scan() throws Exception {
        String phoneNum = "18676604687";
        String startRow = phoneNum + "_" + (Long.MAX_VALUE - sdf.parse("20180301000000").getTime());
        String stopRow = phoneNum + "_" + (Long.MAX_VALUE - sdf.parse("20180201000000").getTime());
        //遍历取值
        Scan scan = new Scan();
        scan.setStartRow(startRow.getBytes());
        scan.setStopRow(stopRow.getBytes());
        ResultScanner rss = htable.getScanner(scan);
        for (Result rs : rss) {
            System.out
                    .print(new String(CellUtil.cloneValue(rs.getColumnLatestCell("cf".getBytes(), "dnum".getBytes()))));
            System.out.print("-"
                    + new String(CellUtil.cloneValue(rs.getColumnLatestCell("cf".getBytes(), "length".getBytes()))));
            System.out.print(
                    "-" + new String(CellUtil.cloneValue(rs.getColumnLatestCell("cf".getBytes(), "type".getBytes()))));
            System.out.println(
                    "-" + new String(CellUtil.cloneValue(rs.getColumnLatestCell("cf".getBytes(), "date".getBytes()))));
        }
    }

    /**
     * 查询某个手机号主叫为1 的所有记录
     * 
     * @throws Exception
     */
    @Test
    public void scan2() throws Exception {
        FilterList list = new FilterList(FilterList.Operator.MUST_PASS_ALL);
        //添加过滤条件
        //前缀条件
        PrefixFilter filter1 = new PrefixFilter("18676604687".getBytes());
        //单列值匹配过滤
        SingleColumnValueFilter filter2 = 
                new SingleColumnValueFilter("cf".getBytes(), 
                        "type".getBytes(),
                        CompareOp.EQUAL, 
                        "1".getBytes());
        list.addFilter(filter1);
        list.addFilter(filter2);
        
        Scan scan = new Scan();
        scan.setFilter(list);
        ResultScanner rss = htable.getScanner(scan);
        for (Result rs : rss) {
            System.out
                    .print(new String(CellUtil.cloneValue(rs.getColumnLatestCell("cf".getBytes(), "dnum".getBytes()))));
            System.out.print("-"
                    + new String(CellUtil.cloneValue(rs.getColumnLatestCell("cf".getBytes(), "length".getBytes()))));
            System.out.print(
                    "-" + new String(CellUtil.cloneValue(rs.getColumnLatestCell("cf".getBytes(), "type".getBytes()))));
            System.out.println(
                    "-" + new String(CellUtil.cloneValue(rs.getColumnLatestCell("cf".getBytes(), "date".getBytes()))));
        }
    }

    /**
     * 关闭数据库
     */
    @After
    public void destory() throws Exception {
        if (admin != null) {
            admin.close();
        }
    }
}

示例二

package hbase;

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

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.KeyValue;
import org.apache.hadoop.hbase.MasterNotRunningException;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.ZooKeeperConnectionException;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HConnection;
import org.apache.hadoop.hbase.client.HConnectionManager;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.HTableInterface;
import org.apache.hadoop.hbase.client.HTablePool;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.Scan;
import org.apache.hadoop.hbase.filter.BinaryComparator;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.PrefixFilter;
import org.apache.hadoop.hbase.filter.RowFilter;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import org.apache.hadoop.hbase.filter.SubstringComparator;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test;


public class HBaseDAOImp {

    HConnection hTablePool = null;
    static Configuration conf =null;
    public HBaseDAOImp()
    {
         conf = new Configuration();
        String zk_list = "node1,node2,node3";
        conf.set("hbase.zookeeper.quorum", zk_list);
        try {
            hTablePool = HConnectionManager.createConnection(conf) ;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void save(Put put, String tableName) {
        // TODO Auto-generated method stub
        HTableInterface table = null;
        try {
            table = hTablePool.getTable(tableName) ;
            table.put(put) ;
            
        } catch (Exception e) {
            e.printStackTrace() ;
        }finally{
            try {
                table.close() ;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 插入一个cell
     * @param tableName
     * @param rowKey
     * @param family
     * @param quailifer
     * @param value
     */
    public void insert(String tableName, String rowKey, String family,
            String quailifer, String value) {
        // TODO Auto-generated method stub
        HTableInterface table = null;
        try {
            table = hTablePool.getTable(tableName) ;
            Put put = new Put(rowKey.getBytes());
            put.add(family.getBytes(), quailifer.getBytes(), value.getBytes()) ;
            table.put(put);
        } catch (Exception e) {
            e.printStackTrace();
        }finally
        {
            try {
                table.close() ;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    /**
     * 在一个列族下插入多个单元格
     * @param tableName
     * @param rowKey
     * @param family
     * @param quailifer
     * @param value
     */
    public void insert(String tableName,String rowKey,String family,String quailifer[],String value[])
    {
        HTableInterface table = null;
        try {
            table = hTablePool.getTable(tableName) ;
            Put put = new Put(rowKey.getBytes());
            // 批量添加
            for (int i = 0; i < quailifer.length; i++) {
                String col = quailifer[i];
                String val = value[i];
                put.add(family.getBytes(), col.getBytes(), val.getBytes());
            }
            table.put(put);
        } catch (Exception e) {
            e.printStackTrace();
        }finally
        {
            try {
                table.close() ;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public void save(List<Put> Put, String tableName) {
        // TODO Auto-generated method stub
        HTableInterface table = null;
        try {
            table = hTablePool.getTable(tableName) ;
            table.put(Put) ;
        }
        catch (Exception e) {
            // TODO: handle exception
        }finally
        {
            try {
                table.close() ;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }


    public Result getOneRow(String tableName, String rowKey) {
        // TODO Auto-generated method stub
        HTableInterface table = null;
        Result rsResult = null;
        try {
            table = hTablePool.getTable(tableName) ;
            Get get = new Get(rowKey.getBytes()) ;
            rsResult = table.get(get) ;
        } catch (Exception e) {
            e.printStackTrace() ;
        }
        finally
        {
            try {
                table.close() ;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return rsResult;
    }
    
    /**
     * 最常用的方法,优化查询
     * 查询一行数据,
     * @param tableName
     * @param rowKey
     * @param cols
     * @return
     */
    public Result getOneRowAndMultiColumn(String tableName, String rowKey,String[] cols) {
        // TODO Auto-generated method stub
        HTableInterface table = null;
        Result rsResult = null;
        try {
            table = hTablePool.getTable(tableName) ;
            Get get = new Get(rowKey.getBytes()) ;
            for (int i = 0; i < cols.length; i++) {
                get.addColumn("cf".getBytes(), cols[i].getBytes()) ;
            }
            rsResult = table.get(get) ;
        } catch (Exception e) {
            e.printStackTrace() ;
        }
        finally
        {
            try {
                table.close() ;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return rsResult;
    }

    
    public List<Result> getRows(String tableName, String rowKeyLike) {
        // TODO Auto-generated method stub
        HTableInterface table = null;
        List<Result> list = null;
        try {
            FilterList fl = new FilterList(FilterList.Operator.MUST_PASS_ALL);
            table = hTablePool.getTable(tableName) ;
            PrefixFilter filter = new PrefixFilter(rowKeyLike.getBytes());
            SingleColumnValueFilter filter1 = new SingleColumnValueFilter(
                      "order".getBytes(),
                      "order_type".getBytes(),
                      CompareOp.EQUAL,
                      Bytes.toBytes("1")
                      );
            fl.addFilter(filter);
            fl.addFilter(filter1);
            Scan scan = new Scan();
            scan.setFilter(fl);
            ResultScanner scanner = table.getScanner(scan) ;
            list = new ArrayList<Result>() ;
            for (Result rs : scanner) {
                list.add(rs) ;
            }
        } catch (Exception e) {
            e.printStackTrace() ;
        }
        finally
        {
            try {
                table.close() ;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
    
    
    public List<Result> getRows(String tableName, String rowKeyLike ,String cols[]) {
        // TODO Auto-generated method stub
        HTableInterface table = null;
        List<Result> list = null;
        try {
            table = hTablePool.getTable(tableName) ;
            PrefixFilter filter = new PrefixFilter(rowKeyLike.getBytes());
            
            Scan scan = new Scan();
            for (int i = 0; i < cols.length; i++) {
                scan.addColumn("cf".getBytes(), cols[i].getBytes()) ;
            }
            scan.setFilter(filter);
            ResultScanner scanner = table.getScanner(scan) ;
            list = new ArrayList<Result>() ;
            for (Result rs : scanner) {
                list.add(rs) ;
            }
        } catch (Exception e) {
            e.printStackTrace() ;
        }
        finally
        {
            try {
                table.close() ;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
    
    public List<Result> getRowsByOneKey(String tableName, String rowKeyLike ,String cols[]) {
        // TODO Auto-generated method stub
        HTableInterface table = null;
        List<Result> list = null;
        try {
            table = hTablePool.getTable(tableName) ;
            PrefixFilter filter = new PrefixFilter(rowKeyLike.getBytes());
            
            Scan scan = new Scan();
            for (int i = 0; i < cols.length; i++) {
                scan.addColumn("cf".getBytes(), cols[i].getBytes()) ;
            }
            scan.setFilter(filter);
            ResultScanner scanner = table.getScanner(scan) ;
            list = new ArrayList<Result>() ;
            for (Result rs : scanner) {
                list.add(rs) ;
            }
        } catch (Exception e) {
            e.printStackTrace() ;
        }
        finally
        {
            try {
                table.close() ;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
    
    /**
     * 范围查询
     * @param tableName
     * @param startRow
     * @param stopRow
     * @return
     */
    public List<Result> getRows(String tableName,String startRow,String stopRow)
    {
        HTableInterface table = null;
        List<Result> list = null;
        try {
            table = hTablePool.getTable(tableName) ;
            Scan scan = new Scan() ;
            scan.setStartRow(startRow.getBytes()) ;
            scan.setStopRow(stopRow.getBytes()) ;
            ResultScanner scanner = table.getScanner(scan) ;
            list = new ArrayList<Result>() ;
            for (Result rsResult : scanner) {
                list.add(rsResult) ;
            }
            
        }catch (Exception e) {
            e.printStackTrace() ;
        }
        finally
        {
            try {
                table.close() ;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
    
    
    public void deleteRecords(String tableName, String rowKeyLike){
        HTableInterface table = null;
        try {
            table = hTablePool.getTable(tableName) ;
            PrefixFilter filter = new PrefixFilter(rowKeyLike.getBytes());
            Scan scan = new Scan();
            scan.setFilter(filter);
            ResultScanner scanner = table.getScanner(scan) ;
            List<Delete> list = new ArrayList<Delete>() ;
            for (Result rs : scanner) {
                Delete del = new Delete(rs.getRow());
                list.add(del) ;
            }
            table.delete(list);
        }
        catch (Exception e) {
            e.printStackTrace() ;
        }
        finally
        {
            try {
                table.close() ;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
    
    public void deleteCell(String tableName, String rowkey,String cf,String column){
        HTableInterface table = null;
        try {
            table = hTablePool.getTable(tableName) ;
            Delete del = new Delete(rowkey.getBytes());
            del.deleteColumn(cf.getBytes(), column.getBytes());
            table.delete(del);
        }
        catch (Exception e) {
            e.printStackTrace() ;
        }
        finally
        {
            try {
                table.close() ;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
    }
    
    public   void createTable(String tableName, String[] columnFamilys){
        try {
            // admin 对象
            HBaseAdmin admin = new HBaseAdmin(conf);
            if (admin.tableExists(tableName)) {
                System.err.println("此表,已存在!");
            } else {
                HTableDescriptor tableDesc = new HTableDescriptor(
                        TableName.valueOf(tableName));

                for (String columnFamily : columnFamilys) {
                    tableDesc.addFamily(new HColumnDescriptor(columnFamily));
                }

                admin.createTable(tableDesc);
                System.err.println("建表成功!");

            }
            admin.close();// 关闭释放资源
        } catch (MasterNotRunningException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ZooKeeperConnectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * 删除一个表
     * 
     * @param tableName
     *            删除的表名
     * */
    public   void deleteTable(String tableName)   {
        try {
            HBaseAdmin admin = new HBaseAdmin(conf);
            if (admin.tableExists(tableName)) {
                admin.disableTable(tableName);// 禁用表
                admin.deleteTable(tableName);// 删除表
                System.err.println("删除表成功!");
            } else {
                System.err.println("删除的表不存在!");
            }
            admin.close();
        } catch (MasterNotRunningException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ZooKeeperConnectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
    /**
     * 查询表中所有行
     * @param tablename
    */
    public void scaner(String tablename) {
    try {
            HTable table =new HTable(conf, tablename);
            Scan s =new Scan();
//            s.addColumn(family, qualifier)
//            s.addColumn(family, qualifier)
            ResultScanner rs = table.getScanner(s);
    for (Result r : rs) {
                
           for(Cell cell:r.rawCells()){   
                System.out.println("RowName:"+new String(CellUtil.cloneRow(cell))+" ");
                System.out.println("Timetamp:"+cell.getTimestamp()+" ");
                System.out.println("column Family:"+new String(CellUtil.cloneFamily(cell))+" ");
                System.out.println("row Name:"+new String(CellUtil.cloneQualifier(cell))+" ");
                System.out.println("value:"+new String(CellUtil.cloneValue(cell))+" ");
               }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void scanerByColumn(String tablename) {
        
        try {
            HTable table =new HTable(conf, tablename);
            Scan s =new Scan();
            s.addColumn("cf".getBytes(), "201504052237".getBytes());
            s.addColumn("cf".getBytes(), "201504052237".getBytes());
            ResultScanner rs = table.getScanner(s);
            for (Result r : rs) {
                
                for(Cell cell:r.rawCells()){   
                    System.out.println("RowName:"+new String(CellUtil.cloneRow(cell))+" ");
                    System.out.println("Timetamp:"+cell.getTimestamp()+" ");
                    System.out.println("column Family:"+new String(CellUtil.cloneFamily(cell))+" ");
                    System.out.println("row Name:"+new String(CellUtil.cloneQualifier(cell))+" ");
                    System.out.println("value:"+new String(CellUtil.cloneValue(cell))+" ");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        

        
        
//        创建表
//        String tableName="test";
//        String cfs[] = {"cf"};
//        dao.createTable(tableName,cfs);
        
//        存入一条数据
//        Put put = new Put("bjsxt".getBytes());
//        put.add("cf".getBytes(), "name".getBytes(), "cai10".getBytes()) ;
//        dao.save(put, "test") ;

//        插入多列数据
//        Put put = new Put("bjsxt".getBytes());
//        List<Put> list = new ArrayList<Put>();
//        put.add("cf".getBytes(), "addr".getBytes(), "shanghai1".getBytes()) ;
//        put.add("cf".getBytes(), "age".getBytes(), "30".getBytes()) ;
//        put.add("cf".getBytes(), "tel".getBytes(), "13889891818".getBytes()) ;
//        list.add(put) ;
//        dao.save(list, "test");
        
//        插入单行数据
//        dao.insert("test", "testrow", "cf", "age", "35") ;
//        dao.insert("test", "testrow", "cf", "cardid", "12312312335") ;
//        dao.insert("test", "testrow", "cf", "tel", "13512312345") ;
        
        
        
//        List<Result> list = dao.getRows("test", "testrow",new String[]{"age"}) ;
//        for(Result rs : list)
//        {
//            for(Cell cell:rs.rawCells()){   
//                System.out.println("RowName:"+new String(CellUtil.cloneRow(cell))+" ");
//                System.out.println("Timetamp:"+cell.getTimestamp()+" ");
//                System.out.println("column Family:"+new String(CellUtil.cloneFamily(cell))+" ");
//                System.out.println("row Name:"+new String(CellUtil.cloneQualifier(cell))+" ");
//                System.out.println("value:"+new String(CellUtil.cloneValue(cell))+" ");
//               }
//        }
        
//        Result rs = dao.getOneRow("test", "testrow");
//         System.out.println(new String(rs.getValue("cf".getBytes(), "age".getBytes())));
        
//        Result rs = dao.getOneRowAndMultiColumn("cell_monitor_table", "29448-513332015-04-05", new String[]{"201504052236","201504052237"});
//        for(Cell cell:rs.rawCells()){   
//            System.out.println("RowName:"+new String(CellUtil.cloneRow(cell))+" ");
//            System.out.println("Timetamp:"+cell.getTimestamp()+" ");
//            System.out.println("column Family:"+new String(CellUtil.cloneFamily(cell))+" ");
//            System.out.println("row Name:"+new String(CellUtil.cloneQualifier(cell))+" ");
//            System.out.println("value:"+new String(CellUtil.cloneValue(cell))+" ");
//           }
        
//        dao.deleteTable("cell_monitor_table");
//        创建表
        String tableName="cell_monitor_table";
        String cfs[] = {"cf"};
//        dao.createTable(tableName,cfs);
    }
    
    
      public static void testRowFilter(String tableName){
             try {
                  HTable table =new HTable(conf, tableName);
                Scan scan = new Scan();
                scan.addColumn(Bytes.toBytes("column1"),Bytes.toBytes("qqqq"));
                Filter filter1 = new RowFilter(CompareOp.LESS_OR_EQUAL,new BinaryComparator(Bytes.toBytes("laoxia157")));
                scan.setFilter(filter1);
                ResultScanner scanner1 = table.getScanner(scan);
                for (Result res : scanner1) {
                    System.out.println(res);
                }
                scanner1.close();

//             
//                Filter filter2 = new RowFilter(CompareFilter.CompareOp.EQUAL,new RegexStringComparator("laoxia4\\d{2}"));
//                scan.setFilter(filter2);
//                ResultScanner scanner2 = table.getScanner(scan);
//                for (Result res : scanner2) {
//                     System.out.println(res);
//                }
//                scanner2.close();

                Filter filter3 = new RowFilter( CompareOp.EQUAL,new SubstringComparator("laoxia407"));
                scan.setFilter(filter3);
                ResultScanner scanner3 = table.getScanner(scan);
                for (Result res : scanner3) {
                      System.out.println(res);
                }
                scanner3.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        
      @Test
      public void testTrasaction(){
          try{
              HTableInterface table = null;
              table = hTablePool.getTable("t_test".getBytes());
//              Put put1 =new Put("002".getBytes());
//              put1.add("cf1".getBytes(), "name".getBytes(), "王五".getBytes());
//              table.put(put1);
              Put newput =new Put("001".getBytes());
              newput.add("cf1".getBytes(), "like".getBytes(), "看书".getBytes());
              
              boolean f= table.checkAndPut("001".getBytes(), "cf1".getBytes(), "age".getBytes(), "24".getBytes(), newput);
              System.out.println(f);
              
          }catch (Exception e){
              e.printStackTrace();
          }
          
      }
}

官网 Hbase API:http://hbase.apache.org/2.1/apidocs/index.html
API参考:https://www.cnblogs.com/liuwei6/p/6842536.html

Protocol 参考:

https://www.ibm.com/developerworks/cn/linux/l-cn-gpb/index.html
https://segmentfault.com/a/1190000010098194

posted @ 2019-02-28 12:55  cac2020  阅读(442)  评论(0编辑  收藏  举报