001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.shaded.protobuf;
019
020import java.io.ByteArrayOutputStream;
021import java.io.IOException;
022import java.io.InputStream;
023import java.lang.reflect.Constructor;
024import java.lang.reflect.Method;
025import java.nio.ByteBuffer;
026import java.security.AccessController;
027import java.security.PrivilegedAction;
028import java.util.ArrayList;
029import java.util.Collections;
030import java.util.List;
031import java.util.Locale;
032import java.util.Map;
033import java.util.Map.Entry;
034import java.util.NavigableSet;
035import java.util.Optional;
036import java.util.concurrent.Callable;
037import java.util.concurrent.TimeUnit;
038import java.util.function.Function;
039import java.util.regex.Pattern;
040import java.util.stream.Collectors;
041
042import org.apache.commons.io.input.BoundedInputStream;
043import org.apache.hadoop.conf.Configuration;
044import org.apache.hadoop.fs.Path;
045import org.apache.hadoop.hbase.ByteBufferExtendedCell;
046import org.apache.hadoop.hbase.CacheEvictionStats;
047import org.apache.hadoop.hbase.CacheEvictionStatsBuilder;
048import org.apache.hadoop.hbase.Cell;
049import org.apache.hadoop.hbase.Cell.Type;
050import org.apache.hadoop.hbase.CellBuilderType;
051import org.apache.hadoop.hbase.CellScanner;
052import org.apache.hadoop.hbase.CellUtil;
053import org.apache.hadoop.hbase.DoNotRetryIOException;
054import org.apache.hadoop.hbase.ExtendedCellBuilder;
055import org.apache.hadoop.hbase.ExtendedCellBuilderFactory;
056import org.apache.hadoop.hbase.HBaseConfiguration;
057import org.apache.hadoop.hbase.HBaseIOException;
058import org.apache.hadoop.hbase.HConstants;
059import org.apache.hadoop.hbase.KeyValue;
060import org.apache.hadoop.hbase.NamespaceDescriptor;
061import org.apache.hadoop.hbase.ServerName;
062import org.apache.hadoop.hbase.TableName;
063import org.apache.hadoop.hbase.client.Append;
064import org.apache.hadoop.hbase.client.ClientUtil;
065import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
066import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
067import org.apache.hadoop.hbase.client.CompactionState;
068import org.apache.hadoop.hbase.client.Consistency;
069import org.apache.hadoop.hbase.client.Cursor;
070import org.apache.hadoop.hbase.client.Delete;
071import org.apache.hadoop.hbase.client.Durability;
072import org.apache.hadoop.hbase.client.Get;
073import org.apache.hadoop.hbase.client.Increment;
074import org.apache.hadoop.hbase.client.Mutation;
075import org.apache.hadoop.hbase.client.PackagePrivateFieldAccessor;
076import org.apache.hadoop.hbase.client.Put;
077import org.apache.hadoop.hbase.client.RegionInfoBuilder;
078import org.apache.hadoop.hbase.client.RegionLoadStats;
079import org.apache.hadoop.hbase.client.Result;
080import org.apache.hadoop.hbase.client.Scan;
081import org.apache.hadoop.hbase.client.SnapshotDescription;
082import org.apache.hadoop.hbase.client.SnapshotType;
083import org.apache.hadoop.hbase.client.TableDescriptor;
084import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
085import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
086import org.apache.hadoop.hbase.client.security.SecurityCapability;
087import org.apache.hadoop.hbase.exceptions.DeserializationException;
088import org.apache.hadoop.hbase.filter.ByteArrayComparable;
089import org.apache.hadoop.hbase.filter.Filter;
090import org.apache.hadoop.hbase.io.TimeRange;
091import org.apache.hadoop.hbase.protobuf.ProtobufMagic;
092import org.apache.hadoop.hbase.protobuf.ProtobufMessageConverter;
093import org.apache.hadoop.hbase.quotas.QuotaScope;
094import org.apache.hadoop.hbase.quotas.QuotaType;
095import org.apache.hadoop.hbase.quotas.SpaceViolationPolicy;
096import org.apache.hadoop.hbase.quotas.ThrottleType;
097import org.apache.hadoop.hbase.replication.ReplicationLoadSink;
098import org.apache.hadoop.hbase.replication.ReplicationLoadSource;
099import org.apache.hadoop.hbase.security.visibility.Authorizations;
100import org.apache.hadoop.hbase.security.visibility.CellVisibility;
101import org.apache.hadoop.hbase.util.Addressing;
102import org.apache.hadoop.hbase.util.Bytes;
103import org.apache.hadoop.hbase.util.DynamicClassLoader;
104import org.apache.hadoop.hbase.util.ExceptionUtil;
105import org.apache.hadoop.hbase.util.Methods;
106import org.apache.hadoop.hbase.util.VersionInfo;
107import org.apache.hadoop.ipc.RemoteException;
108import org.apache.yetus.audience.InterfaceAudience;
109
110import org.apache.hbase.thirdparty.com.google.common.annotations.VisibleForTesting;
111import org.apache.hbase.thirdparty.com.google.common.io.ByteStreams;
112import org.apache.hbase.thirdparty.com.google.gson.JsonArray;
113import org.apache.hbase.thirdparty.com.google.gson.JsonElement;
114import org.apache.hbase.thirdparty.com.google.protobuf.ByteString;
115import org.apache.hbase.thirdparty.com.google.protobuf.CodedInputStream;
116import org.apache.hbase.thirdparty.com.google.protobuf.InvalidProtocolBufferException;
117import org.apache.hbase.thirdparty.com.google.protobuf.Message;
118import org.apache.hbase.thirdparty.com.google.protobuf.RpcChannel;
119import org.apache.hbase.thirdparty.com.google.protobuf.RpcController;
120import org.apache.hbase.thirdparty.com.google.protobuf.Service;
121import org.apache.hbase.thirdparty.com.google.protobuf.ServiceException;
122import org.apache.hbase.thirdparty.com.google.protobuf.TextFormat;
123import org.apache.hbase.thirdparty.com.google.protobuf.UnsafeByteOperations;
124import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.AdminService;
125import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.CloseRegionRequest;
126import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetOnlineRegionRequest;
127import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetOnlineRegionResponse;
128import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionInfoRequest;
129import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionInfoResponse;
130import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetRegionLoadResponse;
131import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetServerInfoRequest;
132import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetServerInfoResponse;
133import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetStoreFileRequest;
134import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.GetStoreFileResponse;
135import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.OpenRegionRequest;
136import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.ServerInfo;
137import org.apache.hadoop.hbase.shaded.protobuf.generated.AdminProtos.WarmupRegionRequest;
138import org.apache.hadoop.hbase.shaded.protobuf.generated.CellProtos;
139import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos;
140import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.Column;
141import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.GetRequest;
142import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.MutationProto;
143import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.MutationProto.ColumnValue;
144import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.MutationProto.ColumnValue.QualifierValue;
145import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.MutationProto.DeleteType;
146import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.MutationProto.MutationType;
147import org.apache.hadoop.hbase.shaded.protobuf.generated.ClientProtos.ScanRequest;
148import org.apache.hadoop.hbase.shaded.protobuf.generated.ClusterStatusProtos;
149import org.apache.hadoop.hbase.shaded.protobuf.generated.ClusterStatusProtos.RegionLoad;
150import org.apache.hadoop.hbase.shaded.protobuf.generated.ComparatorProtos;
151import org.apache.hadoop.hbase.shaded.protobuf.generated.FilterProtos;
152import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos;
153import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.BytesBytesPair;
154import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.ColumnFamilySchema;
155import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.NameBytesPair;
156import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.NameStringPair;
157import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.ProcedureDescription;
158import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.RegionExceptionMessage;
159import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.RegionInfo;
160import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.RegionSpecifier;
161import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.RegionSpecifier.RegionSpecifierType;
162import org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.TableSchema;
163import org.apache.hadoop.hbase.shaded.protobuf.generated.LockServiceProtos;
164import org.apache.hadoop.hbase.shaded.protobuf.generated.MapReduceProtos;
165import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos;
166import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.CreateTableRequest;
167import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetCompletedSnapshotsResponse;
168import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.GetTableDescriptorsResponse;
169import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListNamespaceDescriptorsResponse;
170import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.ListTableDescriptorsByNamespaceResponse;
171import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MajorCompactionTimestampResponse;
172import org.apache.hadoop.hbase.shaded.protobuf.generated.ProcedureProtos;
173import org.apache.hadoop.hbase.shaded.protobuf.generated.QuotaProtos;
174import org.apache.hadoop.hbase.shaded.protobuf.generated.RegionServerStatusProtos.RegionServerReportRequest;
175import org.apache.hadoop.hbase.shaded.protobuf.generated.RegionServerStatusProtos.RegionServerStartupRequest;
176import org.apache.hadoop.hbase.shaded.protobuf.generated.SnapshotProtos;
177import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos;
178import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.BulkLoadDescriptor;
179import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.CompactionDescriptor;
180import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.FlushDescriptor;
181import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.FlushDescriptor.FlushAction;
182import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.RegionEventDescriptor;
183import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.RegionEventDescriptor.EventType;
184import org.apache.hadoop.hbase.shaded.protobuf.generated.WALProtos.StoreDescriptor;
185import org.apache.hadoop.hbase.shaded.protobuf.generated.ZooKeeperProtos;
186
187/**
188 * Protobufs utility.
189 * Be aware that a class named org.apache.hadoop.hbase.protobuf.ProtobufUtil (i.e. no 'shaded' in
190 * the package name) carries a COPY of a subset of this class for non-shaded
191 * users; e.g. Coprocessor Endpoints. If you make change in here, be sure to make change in
192 * the companion class too (not the end of the world, especially if you are adding new functionality
193 * but something to be aware of.
194 * @see ProtobufUtil
195 */
196// TODO: Generate the non-shaded protobufutil from this one.
197@InterfaceAudience.Private // TODO: some clients (Hive, etc) use this class
198public final class ProtobufUtil {
199  private ProtobufUtil() {
200  }
201
202  /**
203   * Many results are simple: no cell, exists true or false. To save on object creations,
204   *  we reuse them across calls.
205   */
206  private final static Cell[] EMPTY_CELL_ARRAY = new Cell[]{};
207  private final static Result EMPTY_RESULT = Result.create(EMPTY_CELL_ARRAY);
208  final static Result EMPTY_RESULT_EXISTS_TRUE = Result.create(null, true);
209  final static Result EMPTY_RESULT_EXISTS_FALSE = Result.create(null, false);
210  private final static Result EMPTY_RESULT_STALE = Result.create(EMPTY_CELL_ARRAY, null, true);
211  private final static Result EMPTY_RESULT_EXISTS_TRUE_STALE
212    = Result.create((Cell[])null, true, true);
213  private final static Result EMPTY_RESULT_EXISTS_FALSE_STALE
214    = Result.create((Cell[])null, false, true);
215
216  private final static ClientProtos.Result EMPTY_RESULT_PB;
217  private final static ClientProtos.Result EMPTY_RESULT_PB_EXISTS_TRUE;
218  private final static ClientProtos.Result EMPTY_RESULT_PB_EXISTS_FALSE;
219  private final static ClientProtos.Result EMPTY_RESULT_PB_STALE;
220  private final static ClientProtos.Result EMPTY_RESULT_PB_EXISTS_TRUE_STALE;
221  private final static ClientProtos.Result EMPTY_RESULT_PB_EXISTS_FALSE_STALE;
222
223
224  static {
225    ClientProtos.Result.Builder builder = ClientProtos.Result.newBuilder();
226
227    builder.setExists(true);
228    builder.setAssociatedCellCount(0);
229    EMPTY_RESULT_PB_EXISTS_TRUE =  builder.build();
230
231    builder.setStale(true);
232    EMPTY_RESULT_PB_EXISTS_TRUE_STALE = builder.build();
233    builder.clear();
234
235    builder.setExists(false);
236    builder.setAssociatedCellCount(0);
237    EMPTY_RESULT_PB_EXISTS_FALSE =  builder.build();
238    builder.setStale(true);
239    EMPTY_RESULT_PB_EXISTS_FALSE_STALE = builder.build();
240
241    builder.clear();
242    builder.setAssociatedCellCount(0);
243    EMPTY_RESULT_PB =  builder.build();
244    builder.setStale(true);
245    EMPTY_RESULT_PB_STALE = builder.build();
246  }
247
248  private static volatile boolean classLoaderLoaded = false;
249
250  /**
251   * Dynamic class loader to load filter/comparators
252   */
253  private final static class ClassLoaderHolder {
254    private final static ClassLoader CLASS_LOADER;
255
256    static {
257      ClassLoader parent = ProtobufUtil.class.getClassLoader();
258      Configuration conf = HBaseConfiguration.create();
259      CLASS_LOADER = AccessController.doPrivileged((PrivilegedAction<ClassLoader>)
260        () -> new DynamicClassLoader(conf, parent)
261      );
262      classLoaderLoaded = true;
263    }
264  }
265
266  @VisibleForTesting
267  public static boolean isClassLoaderLoaded() {
268    return classLoaderLoaded;
269  }
270
271  /**
272   * Prepend the passed bytes with four bytes of magic, {@link ProtobufMagic#PB_MAGIC},
273   * to flag what follows as a protobuf in hbase.  Prepend these bytes to all content written to
274   * znodes, etc.
275   * @param bytes Bytes to decorate
276   * @return The passed <code>bytes</code> with magic prepended (Creates a new
277   * byte array that is <code>bytes.length</code> plus {@link ProtobufMagic#PB_MAGIC}.length.
278   */
279  public static byte [] prependPBMagic(final byte [] bytes) {
280    return Bytes.add(ProtobufMagic.PB_MAGIC, bytes);
281  }
282
283  /**
284   * @param bytes Bytes to check.
285   * @return True if passed <code>bytes</code> has {@link ProtobufMagic#PB_MAGIC} for a prefix.
286   */
287  public static boolean isPBMagicPrefix(final byte [] bytes) {
288    return ProtobufMagic.isPBMagicPrefix(bytes);
289  }
290
291  /**
292   * @param bytes Bytes to check.
293   * @param offset offset to start at
294   * @param len length to use
295   * @return True if passed <code>bytes</code> has {@link ProtobufMagic#PB_MAGIC} for a prefix.
296   */
297  public static boolean isPBMagicPrefix(final byte [] bytes, int offset, int len) {
298    return ProtobufMagic.isPBMagicPrefix(bytes, offset, len);
299  }
300
301  /**
302   * @param bytes bytes to check
303   * @throws DeserializationException if we are missing the pb magic prefix
304   */
305  public static void expectPBMagicPrefix(final byte [] bytes) throws DeserializationException {
306    if (!isPBMagicPrefix(bytes)) {
307      throw new DeserializationException("Missing pb magic " +
308          Bytes.toString(ProtobufMagic.PB_MAGIC) + " prefix");
309    }
310  }
311
312  /**
313   * @return Length of {@link ProtobufMagic#lengthOfPBMagic()}
314   */
315  public static int lengthOfPBMagic() {
316    return ProtobufMagic.lengthOfPBMagic();
317  }
318
319  public static ComparatorProtos.ByteArrayComparable toByteArrayComparable(final byte [] value) {
320    ComparatorProtos.ByteArrayComparable.Builder builder =
321      ComparatorProtos.ByteArrayComparable.newBuilder();
322    if (value != null) builder.setValue(UnsafeByteOperations.unsafeWrap(value));
323    return builder.build();
324  }
325
326  /**
327   * Return the IOException thrown by the remote server wrapped in
328   * ServiceException as cause.
329   *
330   * @param se ServiceException that wraps IO exception thrown by the server
331   * @return Exception wrapped in ServiceException or
332   *   a new IOException that wraps the unexpected ServiceException.
333   */
334  public static IOException getRemoteException(ServiceException se) {
335    return makeIOExceptionOfException(se);
336  }
337
338  /**
339   * Like {@link #getRemoteException(ServiceException)} but more generic, able to handle more than
340   * just {@link ServiceException}. Prefer this method to
341   * {@link #getRemoteException(ServiceException)} because trying to
342   * contain direct protobuf references.
343   * @param e
344   */
345  public static IOException handleRemoteException(Exception e) {
346    return makeIOExceptionOfException(e);
347  }
348
349  private static IOException makeIOExceptionOfException(Exception e) {
350    Throwable t = e;
351    if (e instanceof ServiceException) {
352      t = e.getCause();
353    }
354    if (ExceptionUtil.isInterrupt(t)) {
355      return ExceptionUtil.asInterrupt(t);
356    }
357    if (t instanceof RemoteException) {
358      t = ((RemoteException)t).unwrapRemoteException();
359    }
360    return t instanceof IOException? (IOException)t: new HBaseIOException(t);
361  }
362
363  /**
364   * Convert a ServerName to a protocol buffer ServerName
365   *
366   * @param serverName the ServerName to convert
367   * @return the converted protocol buffer ServerName
368   * @see #toServerName(org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.ServerName)
369   */
370  public static HBaseProtos.ServerName toServerName(final ServerName serverName) {
371    if (serverName == null) return null;
372    HBaseProtos.ServerName.Builder builder =
373      HBaseProtos.ServerName.newBuilder();
374    builder.setHostName(serverName.getHostname());
375    if (serverName.getPort() >= 0) {
376      builder.setPort(serverName.getPort());
377    }
378    if (serverName.getStartcode() >= 0) {
379      builder.setStartCode(serverName.getStartcode());
380    }
381    return builder.build();
382  }
383
384  /**
385   * Convert a protocol buffer ServerName to a ServerName
386   *
387   * @param proto the protocol buffer ServerName to convert
388   * @return the converted ServerName
389   */
390  public static ServerName toServerName(final HBaseProtos.ServerName proto) {
391    if (proto == null) return null;
392    String hostName = proto.getHostName();
393    long startCode = -1;
394    int port = -1;
395    if (proto.hasPort()) {
396      port = proto.getPort();
397    }
398    if (proto.hasStartCode()) {
399      startCode = proto.getStartCode();
400    }
401    return ServerName.valueOf(hostName, port, startCode);
402  }
403
404  /**
405   * Convert a list of protocol buffer ServerName to a list of ServerName
406   * @param proto protocol buffer ServerNameList
407   * @return a list of ServerName
408   */
409  public static List<ServerName> toServerNameList(
410          List<HBaseProtos.ServerName> proto) {
411    return proto.stream().map(ProtobufUtil::toServerName)
412            .collect(Collectors.toList());
413  }
414
415  /**
416   * Get a list of NamespaceDescriptor from ListNamespaceDescriptorsResponse protobuf
417   * @param proto the ListNamespaceDescriptorsResponse
418   * @return a list of NamespaceDescriptor
419   */
420  public static List<NamespaceDescriptor> toNamespaceDescriptorList(
421      ListNamespaceDescriptorsResponse proto) {
422    return proto.getNamespaceDescriptorList().stream().map(ProtobufUtil::toNamespaceDescriptor)
423        .collect(Collectors.toList());
424  }
425
426  /**
427   * Get a list of TableDescriptor from GetTableDescriptorsResponse protobuf
428   * @param proto the GetTableDescriptorsResponse
429   * @return a list of TableDescriptor
430   */
431  public static List<TableDescriptor> toTableDescriptorList(GetTableDescriptorsResponse proto) {
432    if (proto == null) {
433      return new ArrayList<>();
434    }
435    return proto.getTableSchemaList().stream().map(ProtobufUtil::toTableDescriptor)
436        .collect(Collectors.toList());
437  }
438
439  /**
440   * Get a list of TableDescriptor from ListTableDescriptorsByNamespaceResponse protobuf
441   * @param proto the ListTableDescriptorsByNamespaceResponse
442   * @return a list of TableDescriptor
443   */
444  public static List<TableDescriptor>
445      toTableDescriptorList(ListTableDescriptorsByNamespaceResponse proto) {
446    if (proto == null) return new ArrayList<>();
447    return proto.getTableSchemaList().stream().map(ProtobufUtil::toTableDescriptor)
448        .collect(Collectors.toList());
449  }
450
451  /**
452   * get the split keys in form "byte [][]" from a CreateTableRequest proto
453   *
454   * @param proto the CreateTableRequest
455   * @return the split keys
456   */
457  public static byte [][] getSplitKeysArray(final CreateTableRequest proto) {
458    byte [][] splitKeys = new byte[proto.getSplitKeysCount()][];
459    for (int i = 0; i < proto.getSplitKeysCount(); ++i) {
460      splitKeys[i] = proto.getSplitKeys(i).toByteArray();
461    }
462    return splitKeys;
463  }
464
465  /**
466   * Convert a protobuf Durability into a client Durability
467   */
468  public static Durability toDurability(
469      final ClientProtos.MutationProto.Durability proto) {
470    switch(proto) {
471    case USE_DEFAULT:
472      return Durability.USE_DEFAULT;
473    case SKIP_WAL:
474      return Durability.SKIP_WAL;
475    case ASYNC_WAL:
476      return Durability.ASYNC_WAL;
477    case SYNC_WAL:
478      return Durability.SYNC_WAL;
479    case FSYNC_WAL:
480      return Durability.FSYNC_WAL;
481    default:
482      return Durability.USE_DEFAULT;
483    }
484  }
485
486  /**
487   * Convert a client Durability into a protbuf Durability
488   */
489  public static ClientProtos.MutationProto.Durability toDurability(
490      final Durability d) {
491    switch(d) {
492    case USE_DEFAULT:
493      return ClientProtos.MutationProto.Durability.USE_DEFAULT;
494    case SKIP_WAL:
495      return ClientProtos.MutationProto.Durability.SKIP_WAL;
496    case ASYNC_WAL:
497      return ClientProtos.MutationProto.Durability.ASYNC_WAL;
498    case SYNC_WAL:
499      return ClientProtos.MutationProto.Durability.SYNC_WAL;
500    case FSYNC_WAL:
501      return ClientProtos.MutationProto.Durability.FSYNC_WAL;
502    default:
503      return ClientProtos.MutationProto.Durability.USE_DEFAULT;
504    }
505  }
506
507  /**
508   * Convert a protocol buffer Get to a client Get
509   *
510   * @param proto the protocol buffer Get to convert
511   * @return the converted client Get
512   * @throws IOException
513   */
514  public static Get toGet(final ClientProtos.Get proto) throws IOException {
515    if (proto == null) return null;
516    byte[] row = proto.getRow().toByteArray();
517    Get get = new Get(row);
518    if (proto.hasCacheBlocks()) {
519      get.setCacheBlocks(proto.getCacheBlocks());
520    }
521    if (proto.hasMaxVersions()) {
522      get.setMaxVersions(proto.getMaxVersions());
523    }
524    if (proto.hasStoreLimit()) {
525      get.setMaxResultsPerColumnFamily(proto.getStoreLimit());
526    }
527    if (proto.hasStoreOffset()) {
528      get.setRowOffsetPerColumnFamily(proto.getStoreOffset());
529    }
530    if (proto.getCfTimeRangeCount() > 0) {
531      for (HBaseProtos.ColumnFamilyTimeRange cftr : proto.getCfTimeRangeList()) {
532        TimeRange timeRange = toTimeRange(cftr.getTimeRange());
533        get.setColumnFamilyTimeRange(cftr.getColumnFamily().toByteArray(),
534            timeRange.getMin(), timeRange.getMax());
535      }
536    }
537    if (proto.hasTimeRange()) {
538      TimeRange timeRange = toTimeRange(proto.getTimeRange());
539      get.setTimeRange(timeRange.getMin(), timeRange.getMax());
540    }
541    if (proto.hasFilter()) {
542      FilterProtos.Filter filter = proto.getFilter();
543      get.setFilter(ProtobufUtil.toFilter(filter));
544    }
545    for (NameBytesPair attribute: proto.getAttributeList()) {
546      get.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
547    }
548    if (proto.getColumnCount() > 0) {
549      for (Column column: proto.getColumnList()) {
550        byte[] family = column.getFamily().toByteArray();
551        if (column.getQualifierCount() > 0) {
552          for (ByteString qualifier: column.getQualifierList()) {
553            get.addColumn(family, qualifier.toByteArray());
554          }
555        } else {
556          get.addFamily(family);
557        }
558      }
559    }
560    if (proto.hasExistenceOnly() && proto.getExistenceOnly()){
561      get.setCheckExistenceOnly(true);
562    }
563    if (proto.hasConsistency()) {
564      get.setConsistency(toConsistency(proto.getConsistency()));
565    }
566    if (proto.hasLoadColumnFamiliesOnDemand()) {
567      get.setLoadColumnFamiliesOnDemand(proto.getLoadColumnFamiliesOnDemand());
568    }
569    return get;
570  }
571
572  public static Consistency toConsistency(ClientProtos.Consistency consistency) {
573    switch (consistency) {
574      case STRONG : return Consistency.STRONG;
575      case TIMELINE : return Consistency.TIMELINE;
576      default : return Consistency.STRONG;
577    }
578  }
579
580  public static ClientProtos.Consistency toConsistency(Consistency consistency) {
581    switch (consistency) {
582      case STRONG : return ClientProtos.Consistency.STRONG;
583      case TIMELINE : return ClientProtos.Consistency.TIMELINE;
584      default : return ClientProtos.Consistency.STRONG;
585    }
586  }
587
588  /**
589   * Convert a protocol buffer Mutate to a Put.
590   *
591   * @param proto The protocol buffer MutationProto to convert
592   * @return A client Put.
593   * @throws IOException
594   */
595  public static Put toPut(final MutationProto proto)
596  throws IOException {
597    return toPut(proto, null);
598  }
599
600  /**
601   * Convert a protocol buffer Mutate to a Put.
602   *
603   * @param proto The protocol buffer MutationProto to convert
604   * @param cellScanner If non-null, the Cell data that goes with this proto.
605   * @return A client Put.
606   * @throws IOException
607   */
608  public static Put toPut(final MutationProto proto, final CellScanner cellScanner)
609  throws IOException {
610    // TODO: Server-side at least why do we convert back to the Client types?  Why not just pb it?
611    MutationType type = proto.getMutateType();
612    assert type == MutationType.PUT: type.name();
613    long timestamp = proto.hasTimestamp()? proto.getTimestamp(): HConstants.LATEST_TIMESTAMP;
614    Put put = proto.hasRow() ? new Put(proto.getRow().toByteArray(), timestamp) : null;
615    int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
616    if (cellCount > 0) {
617      // The proto has metadata only and the data is separate to be found in the cellScanner.
618      if (cellScanner == null) {
619        throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
620            toShortString(proto));
621      }
622      for (int i = 0; i < cellCount; i++) {
623        if (!cellScanner.advance()) {
624          throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
625            " no cell returned: " + toShortString(proto));
626        }
627        Cell cell = cellScanner.current();
628        if (put == null) {
629          put = new Put(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), timestamp);
630        }
631        put.add(cell);
632      }
633    } else {
634      if (put == null) {
635        throw new IllegalArgumentException("row cannot be null");
636      }
637      // The proto has the metadata and the data itself
638      ExtendedCellBuilder cellBuilder = ExtendedCellBuilderFactory.create(CellBuilderType.SHALLOW_COPY);
639      for (ColumnValue column: proto.getColumnValueList()) {
640        byte[] family = column.getFamily().toByteArray();
641        for (QualifierValue qv: column.getQualifierValueList()) {
642          if (!qv.hasValue()) {
643            throw new DoNotRetryIOException(
644                "Missing required field: qualifier value");
645          }
646          long ts = timestamp;
647          if (qv.hasTimestamp()) {
648            ts = qv.getTimestamp();
649          }
650          byte[] allTagsBytes;
651          if (qv.hasTags()) {
652            allTagsBytes = qv.getTags().toByteArray();
653            if(qv.hasDeleteType()) {
654              put.add(cellBuilder.clear()
655                  .setRow(proto.getRow().toByteArray())
656                  .setFamily(family)
657                  .setQualifier(qv.hasQualifier() ? qv.getQualifier().toByteArray() : null)
658                  .setTimestamp(ts)
659                  .setType(fromDeleteType(qv.getDeleteType()).getCode())
660                  .setTags(allTagsBytes)
661                  .build());
662            } else {
663              put.add(cellBuilder.clear()
664                  .setRow(put.getRow())
665                  .setFamily(family)
666                  .setQualifier(qv.hasQualifier() ? qv.getQualifier().toByteArray() : null)
667                  .setTimestamp(ts)
668                  .setType(Cell.Type.Put)
669                  .setValue(qv.hasValue() ? qv.getValue().toByteArray() : null)
670                  .setTags(allTagsBytes)
671                  .build());
672            }
673          } else {
674            if(qv.hasDeleteType()) {
675              put.add(cellBuilder.clear()
676                  .setRow(put.getRow())
677                  .setFamily(family)
678                  .setQualifier(qv.hasQualifier() ? qv.getQualifier().toByteArray() : null)
679                  .setTimestamp(ts)
680                  .setType(fromDeleteType(qv.getDeleteType()).getCode())
681                  .build());
682            } else{
683              put.add(cellBuilder.clear()
684                  .setRow(put.getRow())
685                  .setFamily(family)
686                  .setQualifier(qv.hasQualifier() ? qv.getQualifier().toByteArray() : null)
687                  .setTimestamp(ts)
688                  .setType(Type.Put)
689                  .setValue(qv.hasValue() ? qv.getValue().toByteArray() : null)
690                  .build());
691            }
692          }
693        }
694      }
695    }
696    put.setDurability(toDurability(proto.getDurability()));
697    for (NameBytesPair attribute: proto.getAttributeList()) {
698      put.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
699    }
700    return put;
701  }
702
703  /**
704   * Convert a protocol buffer Mutate to a Delete
705   *
706   * @param proto the protocol buffer Mutate to convert
707   * @return the converted client Delete
708   * @throws IOException
709   */
710  public static Delete toDelete(final MutationProto proto)
711  throws IOException {
712    return toDelete(proto, null);
713  }
714
715  /**
716   * Convert a protocol buffer Mutate to a Delete
717   *
718   * @param proto the protocol buffer Mutate to convert
719   * @param cellScanner if non-null, the data that goes with this delete.
720   * @return the converted client Delete
721   * @throws IOException
722   */
723  public static Delete toDelete(final MutationProto proto, final CellScanner cellScanner)
724  throws IOException {
725    MutationType type = proto.getMutateType();
726    assert type == MutationType.DELETE : type.name();
727    long timestamp = proto.hasTimestamp() ? proto.getTimestamp() : HConstants.LATEST_TIMESTAMP;
728    Delete delete = proto.hasRow() ? new Delete(proto.getRow().toByteArray(), timestamp) : null;
729    int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
730    if (cellCount > 0) {
731      // The proto has metadata only and the data is separate to be found in the cellScanner.
732      if (cellScanner == null) {
733        // TextFormat should be fine for a Delete since it carries no data, just coordinates.
734        throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
735          TextFormat.shortDebugString(proto));
736      }
737      for (int i = 0; i < cellCount; i++) {
738        if (!cellScanner.advance()) {
739          // TextFormat should be fine for a Delete since it carries no data, just coordinates.
740          throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
741            " no cell returned: " + TextFormat.shortDebugString(proto));
742        }
743        Cell cell = cellScanner.current();
744        if (delete == null) {
745          delete =
746            new Delete(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), timestamp);
747        }
748        delete.add(cell);
749      }
750    } else {
751      if (delete == null) {
752        throw new IllegalArgumentException("row cannot be null");
753      }
754      for (ColumnValue column: proto.getColumnValueList()) {
755        byte[] family = column.getFamily().toByteArray();
756        for (QualifierValue qv: column.getQualifierValueList()) {
757          DeleteType deleteType = qv.getDeleteType();
758          byte[] qualifier = null;
759          if (qv.hasQualifier()) {
760            qualifier = qv.getQualifier().toByteArray();
761          }
762          long ts = HConstants.LATEST_TIMESTAMP;
763          if (qv.hasTimestamp()) {
764            ts = qv.getTimestamp();
765          }
766          if (deleteType == DeleteType.DELETE_ONE_VERSION) {
767            delete.addColumn(family, qualifier, ts);
768          } else if (deleteType == DeleteType.DELETE_MULTIPLE_VERSIONS) {
769            delete.addColumns(family, qualifier, ts);
770          } else if (deleteType == DeleteType.DELETE_FAMILY_VERSION) {
771            delete.addFamilyVersion(family, ts);
772          } else {
773            delete.addFamily(family, ts);
774          }
775        }
776      }
777    }
778    delete.setDurability(toDurability(proto.getDurability()));
779    for (NameBytesPair attribute: proto.getAttributeList()) {
780      delete.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
781    }
782    return delete;
783  }
784  @FunctionalInterface
785  private interface ConsumerWithException <T, U> {
786    void accept(T t, U u) throws IOException;
787  }
788
789  private static <T extends Mutation> T toDelta(Function<Bytes, T> supplier, ConsumerWithException<T, Cell> consumer,
790    final MutationProto proto, final CellScanner cellScanner) throws IOException {
791    byte[] row = proto.hasRow() ? proto.getRow().toByteArray() : null;
792    T mutation = row == null ? null : supplier.apply(new Bytes(row));
793    int cellCount = proto.hasAssociatedCellCount() ? proto.getAssociatedCellCount() : 0;
794    if (cellCount > 0) {
795      // The proto has metadata only and the data is separate to be found in the cellScanner.
796      if (cellScanner == null) {
797        throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
798                toShortString(proto));
799      }
800      for (int i = 0; i < cellCount; i++) {
801        if (!cellScanner.advance()) {
802          throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
803                  " no cell returned: " + toShortString(proto));
804        }
805        Cell cell = cellScanner.current();
806        if (mutation == null) {
807          mutation = supplier.apply(new Bytes(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()));
808        }
809        consumer.accept(mutation, cell);
810      }
811    } else {
812      if (mutation == null) {
813        throw new IllegalArgumentException("row cannot be null");
814      }
815      for (ColumnValue column : proto.getColumnValueList()) {
816        byte[] family = column.getFamily().toByteArray();
817        for (QualifierValue qv : column.getQualifierValueList()) {
818          byte[] qualifier = qv.getQualifier().toByteArray();
819          if (!qv.hasValue()) {
820            throw new DoNotRetryIOException(
821                    "Missing required field: qualifier value");
822          }
823          byte[] value = qv.getValue().toByteArray();
824          byte[] tags = null;
825          if (qv.hasTags()) {
826            tags = qv.getTags().toByteArray();
827          }
828          consumer.accept(mutation, ExtendedCellBuilderFactory.create(CellBuilderType.SHALLOW_COPY)
829                  .setRow(mutation.getRow())
830                  .setFamily(family)
831                  .setQualifier(qualifier)
832                  .setTimestamp(qv.getTimestamp())
833                  .setType(KeyValue.Type.Put.getCode())
834                  .setValue(value)
835                  .setTags(tags)
836                  .build());
837        }
838      }
839    }
840    mutation.setDurability(toDurability(proto.getDurability()));
841    for (NameBytesPair attribute : proto.getAttributeList()) {
842      mutation.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
843    }
844    return mutation;
845  }
846
847  /**
848   * Convert a protocol buffer Mutate to an Append
849   * @param cellScanner
850   * @param proto the protocol buffer Mutate to convert
851   * @return the converted client Append
852   * @throws IOException
853   */
854  public static Append toAppend(final MutationProto proto, final CellScanner cellScanner)
855          throws IOException {
856    MutationType type = proto.getMutateType();
857    assert type == MutationType.APPEND : type.name();
858    Append append = toDelta((Bytes row) -> new Append(row.get(), row.getOffset(), row.getLength()),
859            Append::add, proto, cellScanner);
860    if (proto.hasTimeRange()) {
861      TimeRange timeRange = toTimeRange(proto.getTimeRange());
862      append.setTimeRange(timeRange.getMin(), timeRange.getMax());
863    }
864    return append;
865  }
866
867  /**
868   * Convert a protocol buffer Mutate to an Increment
869   *
870   * @param proto the protocol buffer Mutate to convert
871   * @return the converted client Increment
872   * @throws IOException
873   */
874  public static Increment toIncrement(final MutationProto proto, final CellScanner cellScanner)
875          throws IOException {
876    MutationType type = proto.getMutateType();
877    assert type == MutationType.INCREMENT : type.name();
878    Increment increment = toDelta((Bytes row) -> new Increment(row.get(), row.getOffset(), row.getLength()),
879            Increment::add, proto, cellScanner);
880    if (proto.hasTimeRange()) {
881      TimeRange timeRange = toTimeRange(proto.getTimeRange());
882      increment.setTimeRange(timeRange.getMin(), timeRange.getMax());
883    }
884    return increment;
885  }
886
887  /**
888   * Convert a MutateRequest to Mutation
889   *
890   * @param proto the protocol buffer Mutate to convert
891   * @return the converted Mutation
892   * @throws IOException
893   */
894  public static Mutation toMutation(final MutationProto proto) throws IOException {
895    MutationType type = proto.getMutateType();
896    if (type == MutationType.APPEND) {
897      return toAppend(proto, null);
898    }
899    if (type == MutationType.DELETE) {
900      return toDelete(proto, null);
901    }
902    if (type == MutationType.PUT) {
903      return toPut(proto, null);
904    }
905    throw new IOException("Unknown mutation type " + type);
906  }
907
908  /**
909   * Convert a protocol buffer Mutate to a Get.
910   * @param proto the protocol buffer Mutate to convert.
911   * @param cellScanner
912   * @return the converted client get.
913   * @throws IOException
914   */
915  public static Get toGet(final MutationProto proto, final CellScanner cellScanner)
916      throws IOException {
917    MutationType type = proto.getMutateType();
918    assert type == MutationType.INCREMENT || type == MutationType.APPEND : type.name();
919    byte[] row = proto.hasRow() ? proto.getRow().toByteArray() : null;
920    Get get = null;
921    int cellCount = proto.hasAssociatedCellCount() ? proto.getAssociatedCellCount() : 0;
922    if (cellCount > 0) {
923      // The proto has metadata only and the data is separate to be found in the cellScanner.
924      if (cellScanner == null) {
925        throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: "
926            + TextFormat.shortDebugString(proto));
927      }
928      for (int i = 0; i < cellCount; i++) {
929        if (!cellScanner.advance()) {
930          throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i
931              + " no cell returned: " + TextFormat.shortDebugString(proto));
932        }
933        Cell cell = cellScanner.current();
934        if (get == null) {
935          get = new Get(CellUtil.cloneRow(cell));
936        }
937        get.addColumn(CellUtil.cloneFamily(cell), CellUtil.cloneQualifier(cell));
938      }
939    } else {
940      get = new Get(row);
941      for (ColumnValue column : proto.getColumnValueList()) {
942        byte[] family = column.getFamily().toByteArray();
943        for (QualifierValue qv : column.getQualifierValueList()) {
944          byte[] qualifier = qv.getQualifier().toByteArray();
945          if (!qv.hasValue()) {
946            throw new DoNotRetryIOException("Missing required field: qualifier value");
947          }
948          get.addColumn(family, qualifier);
949        }
950      }
951    }
952    if (proto.hasTimeRange()) {
953      TimeRange timeRange = toTimeRange(proto.getTimeRange());
954      get.setTimeRange(timeRange.getMin(), timeRange.getMax());
955    }
956    for (NameBytesPair attribute : proto.getAttributeList()) {
957      get.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
958    }
959    return get;
960  }
961
962  public static ClientProtos.Scan.ReadType toReadType(Scan.ReadType readType) {
963    switch (readType) {
964      case DEFAULT:
965        return ClientProtos.Scan.ReadType.DEFAULT;
966      case STREAM:
967        return ClientProtos.Scan.ReadType.STREAM;
968      case PREAD:
969        return ClientProtos.Scan.ReadType.PREAD;
970      default:
971        throw new IllegalArgumentException("Unknown ReadType: " + readType);
972    }
973  }
974
975  public static Scan.ReadType toReadType(ClientProtos.Scan.ReadType readType) {
976    switch (readType) {
977      case DEFAULT:
978        return Scan.ReadType.DEFAULT;
979      case STREAM:
980        return Scan.ReadType.STREAM;
981      case PREAD:
982        return Scan.ReadType.PREAD;
983      default:
984        throw new IllegalArgumentException("Unknown ReadType: " + readType);
985    }
986  }
987
988  /**
989   * Convert a client Scan to a protocol buffer Scan
990   *
991   * @param scan the client Scan to convert
992   * @return the converted protocol buffer Scan
993   * @throws IOException
994   */
995  public static ClientProtos.Scan toScan(
996      final Scan scan) throws IOException {
997    ClientProtos.Scan.Builder scanBuilder =
998      ClientProtos.Scan.newBuilder();
999    scanBuilder.setCacheBlocks(scan.getCacheBlocks());
1000    if (scan.getBatch() > 0) {
1001      scanBuilder.setBatchSize(scan.getBatch());
1002    }
1003    if (scan.getMaxResultSize() > 0) {
1004      scanBuilder.setMaxResultSize(scan.getMaxResultSize());
1005    }
1006    if (scan.isSmall()) {
1007      scanBuilder.setSmall(scan.isSmall());
1008    }
1009    if (scan.getAllowPartialResults()) {
1010      scanBuilder.setAllowPartialResults(scan.getAllowPartialResults());
1011    }
1012    Boolean loadColumnFamiliesOnDemand = scan.getLoadColumnFamiliesOnDemandValue();
1013    if (loadColumnFamiliesOnDemand != null) {
1014      scanBuilder.setLoadColumnFamiliesOnDemand(loadColumnFamiliesOnDemand);
1015    }
1016    scanBuilder.setMaxVersions(scan.getMaxVersions());
1017    scan.getColumnFamilyTimeRange().forEach((cf, timeRange) -> {
1018      scanBuilder.addCfTimeRange(HBaseProtos.ColumnFamilyTimeRange.newBuilder()
1019        .setColumnFamily(UnsafeByteOperations.unsafeWrap(cf))
1020        .setTimeRange(toTimeRange(timeRange))
1021        .build());
1022    });
1023    scanBuilder.setTimeRange(ProtobufUtil.toTimeRange(scan.getTimeRange()));
1024    Map<String, byte[]> attributes = scan.getAttributesMap();
1025    if (!attributes.isEmpty()) {
1026      NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
1027      for (Map.Entry<String, byte[]> attribute: attributes.entrySet()) {
1028        attributeBuilder.setName(attribute.getKey());
1029        attributeBuilder.setValue(UnsafeByteOperations.unsafeWrap(attribute.getValue()));
1030        scanBuilder.addAttribute(attributeBuilder.build());
1031      }
1032    }
1033    byte[] startRow = scan.getStartRow();
1034    if (startRow != null && startRow.length > 0) {
1035      scanBuilder.setStartRow(UnsafeByteOperations.unsafeWrap(startRow));
1036    }
1037    byte[] stopRow = scan.getStopRow();
1038    if (stopRow != null && stopRow.length > 0) {
1039      scanBuilder.setStopRow(UnsafeByteOperations.unsafeWrap(stopRow));
1040    }
1041    if (scan.hasFilter()) {
1042      scanBuilder.setFilter(ProtobufUtil.toFilter(scan.getFilter()));
1043    }
1044    if (scan.hasFamilies()) {
1045      Column.Builder columnBuilder = Column.newBuilder();
1046      for (Map.Entry<byte[],NavigableSet<byte []>>
1047          family: scan.getFamilyMap().entrySet()) {
1048        columnBuilder.setFamily(UnsafeByteOperations.unsafeWrap(family.getKey()));
1049        NavigableSet<byte []> qualifiers = family.getValue();
1050        columnBuilder.clearQualifier();
1051        if (qualifiers != null && qualifiers.size() > 0) {
1052          for (byte [] qualifier: qualifiers) {
1053            columnBuilder.addQualifier(UnsafeByteOperations.unsafeWrap(qualifier));
1054          }
1055        }
1056        scanBuilder.addColumn(columnBuilder.build());
1057      }
1058    }
1059    if (scan.getMaxResultsPerColumnFamily() >= 0) {
1060      scanBuilder.setStoreLimit(scan.getMaxResultsPerColumnFamily());
1061    }
1062    if (scan.getRowOffsetPerColumnFamily() > 0) {
1063      scanBuilder.setStoreOffset(scan.getRowOffsetPerColumnFamily());
1064    }
1065    if (scan.isReversed()) {
1066      scanBuilder.setReversed(scan.isReversed());
1067    }
1068    if (scan.getConsistency() == Consistency.TIMELINE) {
1069      scanBuilder.setConsistency(toConsistency(scan.getConsistency()));
1070    }
1071    if (scan.getCaching() > 0) {
1072      scanBuilder.setCaching(scan.getCaching());
1073    }
1074    long mvccReadPoint = PackagePrivateFieldAccessor.getMvccReadPoint(scan);
1075    if (mvccReadPoint > 0) {
1076      scanBuilder.setMvccReadPoint(mvccReadPoint);
1077    }
1078    if (!scan.includeStartRow()) {
1079      scanBuilder.setIncludeStartRow(false);
1080    }
1081    if (scan.includeStopRow()) {
1082      scanBuilder.setIncludeStopRow(true);
1083    }
1084    if (scan.getReadType() != Scan.ReadType.DEFAULT) {
1085      scanBuilder.setReadType(toReadType(scan.getReadType()));
1086    }
1087    if (scan.isNeedCursorResult()) {
1088      scanBuilder.setNeedCursorResult(true);
1089    }
1090    return scanBuilder.build();
1091  }
1092
1093  /**
1094   * Convert a protocol buffer Scan to a client Scan
1095   *
1096   * @param proto the protocol buffer Scan to convert
1097   * @return the converted client Scan
1098   * @throws IOException
1099   */
1100  public static Scan toScan(
1101      final ClientProtos.Scan proto) throws IOException {
1102    byte[] startRow = HConstants.EMPTY_START_ROW;
1103    byte[] stopRow = HConstants.EMPTY_END_ROW;
1104    boolean includeStartRow = true;
1105    boolean includeStopRow = false;
1106    if (proto.hasStartRow()) {
1107      startRow = proto.getStartRow().toByteArray();
1108    }
1109    if (proto.hasStopRow()) {
1110      stopRow = proto.getStopRow().toByteArray();
1111    }
1112    if (proto.hasIncludeStartRow()) {
1113      includeStartRow = proto.getIncludeStartRow();
1114    }
1115    if (proto.hasIncludeStopRow()) {
1116      includeStopRow = proto.getIncludeStopRow();
1117    } else {
1118      // old client without this flag, we should consider start=end as a get.
1119      if (ClientUtil.areScanStartRowAndStopRowEqual(startRow, stopRow)) {
1120        includeStopRow = true;
1121      }
1122    }
1123    Scan scan =
1124        new Scan().withStartRow(startRow, includeStartRow).withStopRow(stopRow, includeStopRow);
1125    if (proto.hasCacheBlocks()) {
1126      scan.setCacheBlocks(proto.getCacheBlocks());
1127    }
1128    if (proto.hasMaxVersions()) {
1129      scan.setMaxVersions(proto.getMaxVersions());
1130    }
1131    if (proto.hasStoreLimit()) {
1132      scan.setMaxResultsPerColumnFamily(proto.getStoreLimit());
1133    }
1134    if (proto.hasStoreOffset()) {
1135      scan.setRowOffsetPerColumnFamily(proto.getStoreOffset());
1136    }
1137    if (proto.hasLoadColumnFamiliesOnDemand()) {
1138      scan.setLoadColumnFamiliesOnDemand(proto.getLoadColumnFamiliesOnDemand());
1139    }
1140    if (proto.getCfTimeRangeCount() > 0) {
1141      for (HBaseProtos.ColumnFamilyTimeRange cftr : proto.getCfTimeRangeList()) {
1142        TimeRange timeRange = toTimeRange(cftr.getTimeRange());
1143        scan.setColumnFamilyTimeRange(cftr.getColumnFamily().toByteArray(),
1144            timeRange.getMin(), timeRange.getMax());
1145      }
1146    }
1147    if (proto.hasTimeRange()) {
1148      TimeRange timeRange = toTimeRange(proto.getTimeRange());
1149      scan.setTimeRange(timeRange.getMin(), timeRange.getMax());
1150    }
1151    if (proto.hasFilter()) {
1152      FilterProtos.Filter filter = proto.getFilter();
1153      scan.setFilter(ProtobufUtil.toFilter(filter));
1154    }
1155    if (proto.hasBatchSize()) {
1156      scan.setBatch(proto.getBatchSize());
1157    }
1158    if (proto.hasMaxResultSize()) {
1159      scan.setMaxResultSize(proto.getMaxResultSize());
1160    }
1161    if (proto.hasSmall()) {
1162      scan.setSmall(proto.getSmall());
1163    }
1164    if (proto.hasAllowPartialResults()) {
1165      scan.setAllowPartialResults(proto.getAllowPartialResults());
1166    }
1167    for (NameBytesPair attribute: proto.getAttributeList()) {
1168      scan.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
1169    }
1170    if (proto.getColumnCount() > 0) {
1171      for (Column column: proto.getColumnList()) {
1172        byte[] family = column.getFamily().toByteArray();
1173        if (column.getQualifierCount() > 0) {
1174          for (ByteString qualifier: column.getQualifierList()) {
1175            scan.addColumn(family, qualifier.toByteArray());
1176          }
1177        } else {
1178          scan.addFamily(family);
1179        }
1180      }
1181    }
1182    if (proto.hasReversed()) {
1183      scan.setReversed(proto.getReversed());
1184    }
1185    if (proto.hasConsistency()) {
1186      scan.setConsistency(toConsistency(proto.getConsistency()));
1187    }
1188    if (proto.hasCaching()) {
1189      scan.setCaching(proto.getCaching());
1190    }
1191    if (proto.hasMvccReadPoint()) {
1192      PackagePrivateFieldAccessor.setMvccReadPoint(scan, proto.getMvccReadPoint());
1193    }
1194    if (scan.isSmall()) {
1195      scan.setReadType(Scan.ReadType.PREAD);
1196    } else if (proto.hasReadType()) {
1197      scan.setReadType(toReadType(proto.getReadType()));
1198    }
1199    if (proto.getNeedCursorResult()) {
1200      scan.setNeedCursorResult(true);
1201    }
1202    return scan;
1203  }
1204
1205  public static ClientProtos.Cursor toCursor(Cursor cursor) {
1206    ClientProtos.Cursor.Builder builder = ClientProtos.Cursor.newBuilder();
1207    ClientProtos.Cursor.newBuilder().setRow(ByteString.copyFrom(cursor.getRow()));
1208    return builder.build();
1209  }
1210
1211  public static ClientProtos.Cursor toCursor(Cell cell) {
1212    return ClientProtos.Cursor.newBuilder()
1213        .setRow(ByteString.copyFrom(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()))
1214        .build();
1215  }
1216
1217  public static Cursor toCursor(ClientProtos.Cursor cursor) {
1218    return ClientUtil.createCursor(cursor.getRow().toByteArray());
1219  }
1220
1221  /**
1222   * Create a protocol buffer Get based on a client Get.
1223   *
1224   * @param get the client Get
1225   * @return a protocol buffer Get
1226   * @throws IOException
1227   */
1228  public static ClientProtos.Get toGet(
1229      final Get get) throws IOException {
1230    ClientProtos.Get.Builder builder =
1231      ClientProtos.Get.newBuilder();
1232    builder.setRow(UnsafeByteOperations.unsafeWrap(get.getRow()));
1233    builder.setCacheBlocks(get.getCacheBlocks());
1234    builder.setMaxVersions(get.getMaxVersions());
1235    if (get.getFilter() != null) {
1236      builder.setFilter(ProtobufUtil.toFilter(get.getFilter()));
1237    }
1238    get.getColumnFamilyTimeRange().forEach((cf, timeRange) -> {
1239      builder.addCfTimeRange(HBaseProtos.ColumnFamilyTimeRange.newBuilder()
1240        .setColumnFamily(UnsafeByteOperations.unsafeWrap(cf))
1241        .setTimeRange(toTimeRange(timeRange))
1242        .build());
1243    });
1244    builder.setTimeRange(ProtobufUtil.toTimeRange(get.getTimeRange()));
1245    Map<String, byte[]> attributes = get.getAttributesMap();
1246    if (!attributes.isEmpty()) {
1247      NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
1248      for (Map.Entry<String, byte[]> attribute: attributes.entrySet()) {
1249        attributeBuilder.setName(attribute.getKey());
1250        attributeBuilder.setValue(UnsafeByteOperations.unsafeWrap(attribute.getValue()));
1251        builder.addAttribute(attributeBuilder.build());
1252      }
1253    }
1254    if (get.hasFamilies()) {
1255      Column.Builder columnBuilder = Column.newBuilder();
1256      Map<byte[], NavigableSet<byte[]>> families = get.getFamilyMap();
1257      for (Map.Entry<byte[], NavigableSet<byte[]>> family: families.entrySet()) {
1258        NavigableSet<byte[]> qualifiers = family.getValue();
1259        columnBuilder.setFamily(UnsafeByteOperations.unsafeWrap(family.getKey()));
1260        columnBuilder.clearQualifier();
1261        if (qualifiers != null && qualifiers.size() > 0) {
1262          for (byte[] qualifier: qualifiers) {
1263            columnBuilder.addQualifier(UnsafeByteOperations.unsafeWrap(qualifier));
1264          }
1265        }
1266        builder.addColumn(columnBuilder.build());
1267      }
1268    }
1269    if (get.getMaxResultsPerColumnFamily() >= 0) {
1270      builder.setStoreLimit(get.getMaxResultsPerColumnFamily());
1271    }
1272    if (get.getRowOffsetPerColumnFamily() > 0) {
1273      builder.setStoreOffset(get.getRowOffsetPerColumnFamily());
1274    }
1275    if (get.isCheckExistenceOnly()){
1276      builder.setExistenceOnly(true);
1277    }
1278    if (get.getConsistency() != null && get.getConsistency() != Consistency.STRONG) {
1279      builder.setConsistency(toConsistency(get.getConsistency()));
1280    }
1281
1282    Boolean loadColumnFamiliesOnDemand = get.getLoadColumnFamiliesOnDemandValue();
1283    if (loadColumnFamiliesOnDemand != null) {
1284      builder.setLoadColumnFamiliesOnDemand(loadColumnFamiliesOnDemand);
1285    }
1286    return builder.build();
1287  }
1288
1289  public static MutationProto toMutation(final MutationType type, final Mutation mutation)
1290    throws IOException {
1291    return toMutation(type, mutation, HConstants.NO_NONCE);
1292  }
1293
1294  /**
1295   * Create a protocol buffer Mutate based on a client Mutation
1296   *
1297   * @param type
1298   * @param mutation
1299   * @return a protobuf'd Mutation
1300   * @throws IOException
1301   */
1302  public static MutationProto toMutation(final MutationType type, final Mutation mutation,
1303    final long nonce) throws IOException {
1304    return toMutation(type, mutation, MutationProto.newBuilder(), nonce);
1305  }
1306
1307  public static MutationProto toMutation(final MutationType type, final Mutation mutation,
1308      MutationProto.Builder builder) throws IOException {
1309    return toMutation(type, mutation, builder, HConstants.NO_NONCE);
1310  }
1311
1312  public static MutationProto toMutation(final MutationType type, final Mutation mutation,
1313      MutationProto.Builder builder, long nonce)
1314  throws IOException {
1315    builder = getMutationBuilderAndSetCommonFields(type, mutation, builder);
1316    if (nonce != HConstants.NO_NONCE) {
1317      builder.setNonce(nonce);
1318    }
1319    if (type == MutationType.INCREMENT) {
1320      builder.setTimeRange(ProtobufUtil.toTimeRange(((Increment) mutation).getTimeRange()));
1321    }
1322    if (type == MutationType.APPEND) {
1323      builder.setTimeRange(ProtobufUtil.toTimeRange(((Append) mutation).getTimeRange()));
1324    }
1325    ColumnValue.Builder columnBuilder = ColumnValue.newBuilder();
1326    QualifierValue.Builder valueBuilder = QualifierValue.newBuilder();
1327    for (Map.Entry<byte[],List<Cell>> family: mutation.getFamilyCellMap().entrySet()) {
1328      columnBuilder.clear();
1329      columnBuilder.setFamily(UnsafeByteOperations.unsafeWrap(family.getKey()));
1330      for (Cell cell: family.getValue()) {
1331        valueBuilder.clear();
1332        valueBuilder.setQualifier(UnsafeByteOperations.unsafeWrap(
1333            cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()));
1334        valueBuilder.setValue(UnsafeByteOperations.unsafeWrap(
1335            cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
1336        valueBuilder.setTimestamp(cell.getTimestamp());
1337        if (type == MutationType.DELETE || (type == MutationType.PUT && CellUtil.isDelete(cell))) {
1338          KeyValue.Type keyValueType = KeyValue.Type.codeToType(cell.getTypeByte());
1339          valueBuilder.setDeleteType(toDeleteType(keyValueType));
1340        }
1341        columnBuilder.addQualifierValue(valueBuilder.build());
1342      }
1343      builder.addColumnValue(columnBuilder.build());
1344    }
1345    return builder.build();
1346  }
1347
1348  /**
1349   * Create a protocol buffer MutationProto based on a client Mutation. Does NOT include data.
1350   * Understanding is that the Cell will be transported other than via protobuf.
1351   * @param type
1352   * @param mutation
1353   * @param builder
1354   * @return a protobuf'd Mutation
1355   * @throws IOException
1356   */
1357  public static MutationProto toMutationNoData(final MutationType type, final Mutation mutation,
1358      final MutationProto.Builder builder)  throws IOException {
1359    return toMutationNoData(type, mutation, builder, HConstants.NO_NONCE);
1360  }
1361
1362  /**
1363   * Create a protocol buffer MutationProto based on a client Mutation.  Does NOT include data.
1364   * Understanding is that the Cell will be transported other than via protobuf.
1365   * @param type
1366   * @param mutation
1367   * @return a protobuf'd Mutation
1368   * @throws IOException
1369   */
1370  public static MutationProto toMutationNoData(final MutationType type, final Mutation mutation)
1371  throws IOException {
1372    MutationProto.Builder builder =  MutationProto.newBuilder();
1373    return toMutationNoData(type, mutation, builder);
1374  }
1375
1376  public static MutationProto toMutationNoData(final MutationType type, final Mutation mutation,
1377      final MutationProto.Builder builder, long nonce) throws IOException {
1378    getMutationBuilderAndSetCommonFields(type, mutation, builder);
1379    builder.setAssociatedCellCount(mutation.size());
1380    if (mutation instanceof Increment) {
1381      builder.setTimeRange(ProtobufUtil.toTimeRange(((Increment) mutation).getTimeRange()));
1382    }
1383    if (mutation instanceof Append) {
1384      builder.setTimeRange(ProtobufUtil.toTimeRange(((Append) mutation).getTimeRange()));
1385    }
1386    if (nonce != HConstants.NO_NONCE) {
1387      builder.setNonce(nonce);
1388    }
1389    return builder.build();
1390  }
1391
1392  /**
1393   * Code shared by {@link #toMutation(MutationType, Mutation)} and
1394   * {@link #toMutationNoData(MutationType, Mutation)}
1395   * @param type
1396   * @param mutation
1397   * @return A partly-filled out protobuf'd Mutation.
1398   */
1399  private static MutationProto.Builder getMutationBuilderAndSetCommonFields(final MutationType type,
1400      final Mutation mutation, MutationProto.Builder builder) {
1401    builder.setRow(UnsafeByteOperations.unsafeWrap(mutation.getRow()));
1402    builder.setMutateType(type);
1403    builder.setDurability(toDurability(mutation.getDurability()));
1404    builder.setTimestamp(mutation.getTimestamp());
1405    Map<String, byte[]> attributes = mutation.getAttributesMap();
1406    if (!attributes.isEmpty()) {
1407      NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
1408      for (Map.Entry<String, byte[]> attribute: attributes.entrySet()) {
1409        attributeBuilder.setName(attribute.getKey());
1410        attributeBuilder.setValue(UnsafeByteOperations.unsafeWrap(attribute.getValue()));
1411        builder.addAttribute(attributeBuilder.build());
1412      }
1413    }
1414    return builder;
1415  }
1416
1417  /**
1418   * Convert a client Result to a protocol buffer Result
1419   *
1420   * @param result the client Result to convert
1421   * @return the converted protocol buffer Result
1422   */
1423  public static ClientProtos.Result toResult(final Result result) {
1424    if (result.getExists() != null) {
1425      return toResult(result.getExists(), result.isStale());
1426    }
1427
1428    Cell[] cells = result.rawCells();
1429    if (cells == null || cells.length == 0) {
1430      return result.isStale() ? EMPTY_RESULT_PB_STALE : EMPTY_RESULT_PB;
1431    }
1432
1433    ClientProtos.Result.Builder builder = ClientProtos.Result.newBuilder();
1434    for (Cell c : cells) {
1435      builder.addCell(toCell(c));
1436    }
1437
1438    builder.setStale(result.isStale());
1439    builder.setPartial(result.mayHaveMoreCellsInRow());
1440
1441    return builder.build();
1442  }
1443
1444  /**
1445   * Convert a client Result to a protocol buffer Result
1446   *
1447   * @param existence the client existence to send
1448   * @return the converted protocol buffer Result
1449   */
1450  public static ClientProtos.Result toResult(final boolean existence, boolean stale) {
1451    if (stale){
1452      return existence ? EMPTY_RESULT_PB_EXISTS_TRUE_STALE : EMPTY_RESULT_PB_EXISTS_FALSE_STALE;
1453    } else {
1454      return existence ? EMPTY_RESULT_PB_EXISTS_TRUE : EMPTY_RESULT_PB_EXISTS_FALSE;
1455    }
1456  }
1457
1458  /**
1459   * Convert a client Result to a protocol buffer Result.
1460   * The pb Result does not include the Cell data.  That is for transport otherwise.
1461   *
1462   * @param result the client Result to convert
1463   * @return the converted protocol buffer Result
1464   */
1465  public static ClientProtos.Result toResultNoData(final Result result) {
1466    if (result.getExists() != null) return toResult(result.getExists(), result.isStale());
1467    int size = result.size();
1468    if (size == 0) return result.isStale() ? EMPTY_RESULT_PB_STALE : EMPTY_RESULT_PB;
1469    ClientProtos.Result.Builder builder = ClientProtos.Result.newBuilder();
1470    builder.setAssociatedCellCount(size);
1471    builder.setStale(result.isStale());
1472    return builder.build();
1473  }
1474
1475  /**
1476   * Convert a protocol buffer Result to a client Result
1477   *
1478   * @param proto the protocol buffer Result to convert
1479   * @return the converted client Result
1480   */
1481  public static Result toResult(final ClientProtos.Result proto) {
1482    if (proto.hasExists()) {
1483      if (proto.getStale()) {
1484        return proto.getExists() ? EMPTY_RESULT_EXISTS_TRUE_STALE :EMPTY_RESULT_EXISTS_FALSE_STALE;
1485      }
1486      return proto.getExists() ? EMPTY_RESULT_EXISTS_TRUE : EMPTY_RESULT_EXISTS_FALSE;
1487    }
1488
1489    List<CellProtos.Cell> values = proto.getCellList();
1490    if (values.isEmpty()){
1491      return proto.getStale() ? EMPTY_RESULT_STALE : EMPTY_RESULT;
1492    }
1493
1494    List<Cell> cells = new ArrayList<>(values.size());
1495    ExtendedCellBuilder builder = ExtendedCellBuilderFactory.create(CellBuilderType.SHALLOW_COPY);
1496    for (CellProtos.Cell c : values) {
1497      cells.add(toCell(builder, c));
1498    }
1499    return Result.create(cells, null, proto.getStale(), proto.getPartial());
1500  }
1501
1502  /**
1503   * Convert a protocol buffer Result to a client Result
1504   *
1505   * @param proto the protocol buffer Result to convert
1506   * @param scanner Optional cell scanner.
1507   * @return the converted client Result
1508   * @throws IOException
1509   */
1510  public static Result toResult(final ClientProtos.Result proto, final CellScanner scanner)
1511  throws IOException {
1512    List<CellProtos.Cell> values = proto.getCellList();
1513
1514    if (proto.hasExists()) {
1515      if ((values != null && !values.isEmpty()) ||
1516          (proto.hasAssociatedCellCount() && proto.getAssociatedCellCount() > 0)) {
1517        throw new IllegalArgumentException("bad proto: exists with cells is no allowed " + proto);
1518      }
1519      if (proto.getStale()) {
1520        return proto.getExists() ? EMPTY_RESULT_EXISTS_TRUE_STALE :EMPTY_RESULT_EXISTS_FALSE_STALE;
1521      }
1522      return proto.getExists() ? EMPTY_RESULT_EXISTS_TRUE : EMPTY_RESULT_EXISTS_FALSE;
1523    }
1524
1525    // TODO: Unit test that has some Cells in scanner and some in the proto.
1526    List<Cell> cells = null;
1527    if (proto.hasAssociatedCellCount()) {
1528      int count = proto.getAssociatedCellCount();
1529      cells = new ArrayList<>(count + values.size());
1530      for (int i = 0; i < count; i++) {
1531        if (!scanner.advance()) throw new IOException("Failed get " + i + " of " + count);
1532        cells.add(scanner.current());
1533      }
1534    }
1535
1536    if (!values.isEmpty()){
1537      if (cells == null) cells = new ArrayList<>(values.size());
1538      ExtendedCellBuilder builder = ExtendedCellBuilderFactory.create(CellBuilderType.SHALLOW_COPY);
1539      for (CellProtos.Cell c: values) {
1540        cells.add(toCell(builder, c));
1541      }
1542    }
1543
1544    return (cells == null || cells.isEmpty())
1545        ? (proto.getStale() ? EMPTY_RESULT_STALE : EMPTY_RESULT)
1546        : Result.create(cells, null, proto.getStale());
1547  }
1548
1549
1550  /**
1551   * Convert a ByteArrayComparable to a protocol buffer Comparator
1552   *
1553   * @param comparator the ByteArrayComparable to convert
1554   * @return the converted protocol buffer Comparator
1555   */
1556  public static ComparatorProtos.Comparator toComparator(ByteArrayComparable comparator) {
1557    ComparatorProtos.Comparator.Builder builder = ComparatorProtos.Comparator.newBuilder();
1558    builder.setName(comparator.getClass().getName());
1559    builder.setSerializedComparator(UnsafeByteOperations.unsafeWrap(comparator.toByteArray()));
1560    return builder.build();
1561  }
1562
1563  /**
1564   * Convert a protocol buffer Comparator to a ByteArrayComparable
1565   *
1566   * @param proto the protocol buffer Comparator to convert
1567   * @return the converted ByteArrayComparable
1568   */
1569  @SuppressWarnings("unchecked")
1570  public static ByteArrayComparable toComparator(ComparatorProtos.Comparator proto)
1571  throws IOException {
1572    String type = proto.getName();
1573    String funcName = "parseFrom";
1574    byte [] value = proto.getSerializedComparator().toByteArray();
1575    try {
1576      Class<?> c = Class.forName(type, true, ClassLoaderHolder.CLASS_LOADER);
1577      Method parseFrom = c.getMethod(funcName, byte[].class);
1578      if (parseFrom == null) {
1579        throw new IOException("Unable to locate function: " + funcName + " in type: " + type);
1580      }
1581      return (ByteArrayComparable)parseFrom.invoke(null, value);
1582    } catch (Exception e) {
1583      throw new IOException(e);
1584    }
1585  }
1586
1587  /**
1588   * Convert a protocol buffer Filter to a client Filter
1589   *
1590   * @param proto the protocol buffer Filter to convert
1591   * @return the converted Filter
1592   */
1593  @SuppressWarnings("unchecked")
1594  public static Filter toFilter(FilterProtos.Filter proto) throws IOException {
1595    String type = proto.getName();
1596    final byte [] value = proto.getSerializedFilter().toByteArray();
1597    String funcName = "parseFrom";
1598    try {
1599      Class<?> c = Class.forName(type, true, ClassLoaderHolder.CLASS_LOADER);
1600      Method parseFrom = c.getMethod(funcName, byte[].class);
1601      if (parseFrom == null) {
1602        throw new IOException("Unable to locate function: " + funcName + " in type: " + type);
1603      }
1604      return (Filter)parseFrom.invoke(c, value);
1605    } catch (Exception e) {
1606      // Either we couldn't instantiate the method object, or "parseFrom" failed.
1607      // In either case, let's not retry.
1608      throw new DoNotRetryIOException(e);
1609    }
1610  }
1611
1612  /**
1613   * Convert a client Filter to a protocol buffer Filter
1614   *
1615   * @param filter the Filter to convert
1616   * @return the converted protocol buffer Filter
1617   */
1618  public static FilterProtos.Filter toFilter(Filter filter) throws IOException {
1619    FilterProtos.Filter.Builder builder = FilterProtos.Filter.newBuilder();
1620    builder.setName(filter.getClass().getName());
1621    builder.setSerializedFilter(UnsafeByteOperations.unsafeWrap(filter.toByteArray()));
1622    return builder.build();
1623  }
1624
1625  /**
1626   * Convert a delete KeyValue type to protocol buffer DeleteType.
1627   *
1628   * @param type
1629   * @return protocol buffer DeleteType
1630   * @throws IOException
1631   */
1632  public static DeleteType toDeleteType(
1633      KeyValue.Type type) throws IOException {
1634    switch (type) {
1635    case Delete:
1636      return DeleteType.DELETE_ONE_VERSION;
1637    case DeleteColumn:
1638      return DeleteType.DELETE_MULTIPLE_VERSIONS;
1639    case DeleteFamily:
1640      return DeleteType.DELETE_FAMILY;
1641    case DeleteFamilyVersion:
1642      return DeleteType.DELETE_FAMILY_VERSION;
1643    default:
1644        throw new IOException("Unknown delete type: " + type);
1645    }
1646  }
1647
1648  /**
1649   * Convert a protocol buffer DeleteType to delete KeyValue type.
1650   *
1651   * @param type The DeleteType
1652   * @return The type.
1653   * @throws IOException
1654   */
1655  public static KeyValue.Type fromDeleteType(
1656      DeleteType type) throws IOException {
1657    switch (type) {
1658    case DELETE_ONE_VERSION:
1659      return KeyValue.Type.Delete;
1660    case DELETE_MULTIPLE_VERSIONS:
1661      return KeyValue.Type.DeleteColumn;
1662    case DELETE_FAMILY:
1663      return KeyValue.Type.DeleteFamily;
1664    case DELETE_FAMILY_VERSION:
1665      return KeyValue.Type.DeleteFamilyVersion;
1666    default:
1667      throw new IOException("Unknown delete type: " + type);
1668    }
1669  }
1670
1671  /**
1672   * Convert a stringified protocol buffer exception Parameter to a Java Exception
1673   *
1674   * @param parameter the protocol buffer Parameter to convert
1675   * @return the converted Exception
1676   * @throws IOException if failed to deserialize the parameter
1677   */
1678  @SuppressWarnings("unchecked")
1679  public static Throwable toException(final NameBytesPair parameter) throws IOException {
1680    if (parameter == null || !parameter.hasValue()) return null;
1681    String desc = parameter.getValue().toStringUtf8();
1682    String type = parameter.getName();
1683    try {
1684      Class<? extends Throwable> c =
1685        (Class<? extends Throwable>)Class.forName(type, true, ClassLoaderHolder.CLASS_LOADER);
1686      Constructor<? extends Throwable> cn = null;
1687      try {
1688        cn = c.getDeclaredConstructor(String.class);
1689        return cn.newInstance(desc);
1690      } catch (NoSuchMethodException e) {
1691        // Could be a raw RemoteException. See HBASE-8987.
1692        cn = c.getDeclaredConstructor(String.class, String.class);
1693        return cn.newInstance(type, desc);
1694      }
1695    } catch (Exception e) {
1696      throw new IOException(e);
1697    }
1698  }
1699
1700// Start helpers for Client
1701
1702  @SuppressWarnings("unchecked")
1703  public static <T extends Service> T newServiceStub(Class<T> service, RpcChannel channel)
1704      throws Exception {
1705    return (T)Methods.call(service, null, "newStub",
1706        new Class[]{ RpcChannel.class }, new Object[]{ channel });
1707  }
1708
1709// End helpers for Client
1710// Start helpers for Admin
1711
1712  /**
1713   * A helper to retrieve region info given a region name
1714   * using admin protocol.
1715   *
1716   * @param admin
1717   * @param regionName
1718   * @return the retrieved region info
1719   * @throws IOException
1720   */
1721  public static org.apache.hadoop.hbase.client.RegionInfo getRegionInfo(final RpcController controller,
1722      final AdminService.BlockingInterface admin, final byte[] regionName) throws IOException {
1723    try {
1724      GetRegionInfoRequest request =
1725        RequestConverter.buildGetRegionInfoRequest(regionName);
1726      GetRegionInfoResponse response =
1727        admin.getRegionInfo(controller, request);
1728      return toRegionInfo(response.getRegionInfo());
1729    } catch (ServiceException se) {
1730      throw getRemoteException(se);
1731    }
1732  }
1733
1734  public static List<org.apache.hadoop.hbase.RegionLoad> getRegionLoadInfo(
1735      GetRegionLoadResponse regionLoadResponse) {
1736    List<org.apache.hadoop.hbase.RegionLoad> regionLoadList =
1737        new ArrayList<>(regionLoadResponse.getRegionLoadsCount());
1738    for (RegionLoad regionLoad : regionLoadResponse.getRegionLoadsList()) {
1739      regionLoadList.add(new org.apache.hadoop.hbase.RegionLoad(regionLoad));
1740    }
1741    return regionLoadList;
1742  }
1743
1744  /**
1745   * A helper to close a region given a region name
1746   * using admin protocol.
1747   *
1748   * @param admin
1749   * @param regionName
1750   * @throws IOException
1751   */
1752  public static void closeRegion(final RpcController controller,
1753      final AdminService.BlockingInterface admin, final ServerName server, final byte[] regionName)
1754          throws IOException {
1755    CloseRegionRequest closeRegionRequest =
1756      ProtobufUtil.buildCloseRegionRequest(server, regionName);
1757    try {
1758      admin.closeRegion(controller, closeRegionRequest);
1759    } catch (ServiceException se) {
1760      throw getRemoteException(se);
1761    }
1762  }
1763
1764  /**
1765   * A helper to warmup a region given a region name
1766   * using admin protocol
1767   *
1768   * @param admin
1769   * @param regionInfo
1770   *
1771   */
1772  public static void warmupRegion(final RpcController controller,
1773      final AdminService.BlockingInterface admin, final org.apache.hadoop.hbase.client.RegionInfo regionInfo) throws IOException {
1774
1775    try {
1776      WarmupRegionRequest warmupRegionRequest =
1777           RequestConverter.buildWarmupRegionRequest(regionInfo);
1778
1779      admin.warmupRegion(controller, warmupRegionRequest);
1780    } catch (ServiceException e) {
1781      throw getRemoteException(e);
1782    }
1783  }
1784
1785  /**
1786   * A helper to open a region using admin protocol.
1787   * @param admin
1788   * @param region
1789   * @throws IOException
1790   */
1791  public static void openRegion(final RpcController controller,
1792      final AdminService.BlockingInterface admin, ServerName server, final org.apache.hadoop.hbase.client.RegionInfo region)
1793          throws IOException {
1794    OpenRegionRequest request =
1795      RequestConverter.buildOpenRegionRequest(server, region, null);
1796    try {
1797      admin.openRegion(controller, request);
1798    } catch (ServiceException se) {
1799      throw ProtobufUtil.getRemoteException(se);
1800    }
1801  }
1802
1803  /**
1804   * A helper to get the all the online regions on a region
1805   * server using admin protocol.
1806   *
1807   * @param admin
1808   * @return a list of online region info
1809   * @throws IOException
1810   */
1811  public static List<org.apache.hadoop.hbase.client.RegionInfo> getOnlineRegions(final AdminService.BlockingInterface admin)
1812      throws IOException {
1813    return getOnlineRegions(null, admin);
1814  }
1815
1816  /**
1817   * A helper to get the all the online regions on a region
1818   * server using admin protocol.
1819   * @return a list of online region info
1820   */
1821  public static List<org.apache.hadoop.hbase.client.RegionInfo> getOnlineRegions(final RpcController controller,
1822      final AdminService.BlockingInterface admin)
1823  throws IOException {
1824    GetOnlineRegionRequest request = RequestConverter.buildGetOnlineRegionRequest();
1825    GetOnlineRegionResponse response = null;
1826    try {
1827      response = admin.getOnlineRegion(controller, request);
1828    } catch (ServiceException se) {
1829      throw getRemoteException(se);
1830    }
1831    return getRegionInfos(response);
1832  }
1833
1834  /**
1835   * Get the list of region info from a GetOnlineRegionResponse
1836   *
1837   * @param proto the GetOnlineRegionResponse
1838   * @return the list of region info or empty if <code>proto</code> is null
1839   */
1840  public static List<org.apache.hadoop.hbase.client.RegionInfo> getRegionInfos(final GetOnlineRegionResponse proto) {
1841    if (proto == null) return Collections.EMPTY_LIST;
1842    List<org.apache.hadoop.hbase.client.RegionInfo> regionInfos = new ArrayList<>(proto.getRegionInfoList().size());
1843    for (RegionInfo regionInfo: proto.getRegionInfoList()) {
1844      regionInfos.add(toRegionInfo(regionInfo));
1845    }
1846    return regionInfos;
1847  }
1848
1849  /**
1850   * A helper to get the info of a region server using admin protocol.
1851   * @return the server name
1852   */
1853  public static ServerInfo getServerInfo(final RpcController controller,
1854      final AdminService.BlockingInterface admin)
1855  throws IOException {
1856    GetServerInfoRequest request = RequestConverter.buildGetServerInfoRequest();
1857    try {
1858      GetServerInfoResponse response = admin.getServerInfo(controller, request);
1859      return response.getServerInfo();
1860    } catch (ServiceException se) {
1861      throw getRemoteException(se);
1862    }
1863  }
1864
1865  /**
1866   * A helper to get the list of files of a column family
1867   * on a given region using admin protocol.
1868   *
1869   * @return the list of store files
1870   */
1871  public static List<String> getStoreFiles(final AdminService.BlockingInterface admin,
1872      final byte[] regionName, final byte[] family)
1873  throws IOException {
1874    return getStoreFiles(null, admin, regionName, family);
1875  }
1876
1877  /**
1878   * A helper to get the list of files of a column family
1879   * on a given region using admin protocol.
1880   *
1881   * @return the list of store files
1882   */
1883  public static List<String> getStoreFiles(final RpcController controller,
1884      final AdminService.BlockingInterface admin, final byte[] regionName, final byte[] family)
1885  throws IOException {
1886    GetStoreFileRequest request =
1887      ProtobufUtil.buildGetStoreFileRequest(regionName, family);
1888    try {
1889      GetStoreFileResponse response = admin.getStoreFile(controller, request);
1890      return response.getStoreFileList();
1891    } catch (ServiceException se) {
1892      throw ProtobufUtil.getRemoteException(se);
1893    }
1894  }
1895
1896// End helpers for Admin
1897
1898  /*
1899   * Get the total (read + write) requests from a RegionLoad pb
1900   * @param rl - RegionLoad pb
1901   * @return total (read + write) requests
1902   */
1903  public static long getTotalRequestsCount(RegionLoad rl) {
1904    if (rl == null) {
1905      return 0;
1906    }
1907
1908    return rl.getReadRequestsCount() + rl.getWriteRequestsCount();
1909  }
1910
1911
1912  /**
1913   * @param m Message to get delimited pb serialization of (with pb magic prefix)
1914   */
1915  public static byte [] toDelimitedByteArray(final Message m) throws IOException {
1916    // Allocate arbitrary big size so we avoid resizing.
1917    ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
1918    baos.write(ProtobufMagic.PB_MAGIC);
1919    m.writeDelimitedTo(baos);
1920    return baos.toByteArray();
1921  }
1922
1923  /**
1924   * Find the HRegion encoded name based on a region specifier
1925   *
1926   * @param regionSpecifier the region specifier
1927   * @return the corresponding region's encoded name
1928   * @throws DoNotRetryIOException if the specifier type is unsupported
1929   */
1930  public static String getRegionEncodedName(
1931      final RegionSpecifier regionSpecifier) throws DoNotRetryIOException {
1932    ByteString value = regionSpecifier.getValue();
1933    RegionSpecifierType type = regionSpecifier.getType();
1934    switch (type) {
1935      case REGION_NAME:
1936        return org.apache.hadoop.hbase.client.RegionInfo.encodeRegionName(value.toByteArray());
1937      case ENCODED_REGION_NAME:
1938        return value.toStringUtf8();
1939      default:
1940        throw new DoNotRetryIOException(
1941          "Unsupported region specifier type: " + type);
1942    }
1943  }
1944
1945  public static ScanMetrics toScanMetrics(final byte[] bytes) {
1946    MapReduceProtos.ScanMetrics pScanMetrics = null;
1947    try {
1948      pScanMetrics = MapReduceProtos.ScanMetrics.parseFrom(bytes);
1949    } catch (InvalidProtocolBufferException e) {
1950      // Ignored there are just no key values to add.
1951    }
1952    ScanMetrics scanMetrics = new ScanMetrics();
1953    if (pScanMetrics != null) {
1954      for (HBaseProtos.NameInt64Pair pair : pScanMetrics.getMetricsList()) {
1955        if (pair.hasName() && pair.hasValue()) {
1956          scanMetrics.setCounter(pair.getName(), pair.getValue());
1957        }
1958      }
1959    }
1960    return scanMetrics;
1961  }
1962
1963  public static MapReduceProtos.ScanMetrics toScanMetrics(ScanMetrics scanMetrics, boolean reset) {
1964    MapReduceProtos.ScanMetrics.Builder builder = MapReduceProtos.ScanMetrics.newBuilder();
1965    Map<String, Long> metrics = scanMetrics.getMetricsMap(reset);
1966    for (Entry<String, Long> e : metrics.entrySet()) {
1967      HBaseProtos.NameInt64Pair nameInt64Pair =
1968          HBaseProtos.NameInt64Pair.newBuilder().setName(e.getKey()).setValue(e.getValue()).build();
1969      builder.addMetrics(nameInt64Pair);
1970    }
1971    return builder.build();
1972  }
1973
1974  /**
1975   * Unwraps an exception from a protobuf service into the underlying (expected) IOException.
1976   * This method will <strong>always</strong> throw an exception.
1977   * @param se the {@code ServiceException} instance to convert into an {@code IOException}
1978   */
1979  public static void toIOException(ServiceException se) throws IOException {
1980    if (se == null) {
1981      throw new NullPointerException("Null service exception passed!");
1982    }
1983
1984    Throwable cause = se.getCause();
1985    if (cause != null && cause instanceof IOException) {
1986      throw (IOException)cause;
1987    }
1988    throw new IOException(se);
1989  }
1990
1991  public static CellProtos.Cell toCell(final Cell kv) {
1992    // Doing this is going to kill us if we do it for all data passed.
1993    // St.Ack 20121205
1994    CellProtos.Cell.Builder kvbuilder = CellProtos.Cell.newBuilder();
1995    if (kv instanceof ByteBufferExtendedCell) {
1996      kvbuilder.setRow(wrap(((ByteBufferExtendedCell) kv).getRowByteBuffer(),
1997        ((ByteBufferExtendedCell) kv).getRowPosition(), kv.getRowLength()));
1998      kvbuilder.setFamily(wrap(((ByteBufferExtendedCell) kv).getFamilyByteBuffer(),
1999        ((ByteBufferExtendedCell) kv).getFamilyPosition(), kv.getFamilyLength()));
2000      kvbuilder.setQualifier(wrap(((ByteBufferExtendedCell) kv).getQualifierByteBuffer(),
2001        ((ByteBufferExtendedCell) kv).getQualifierPosition(), kv.getQualifierLength()));
2002      kvbuilder.setCellType(CellProtos.CellType.valueOf(kv.getTypeByte()));
2003      kvbuilder.setTimestamp(kv.getTimestamp());
2004      kvbuilder.setValue(wrap(((ByteBufferExtendedCell) kv).getValueByteBuffer(),
2005        ((ByteBufferExtendedCell) kv).getValuePosition(), kv.getValueLength()));
2006      // TODO : Once tags become first class then we may have to set tags to kvbuilder.
2007    } else {
2008      kvbuilder.setRow(
2009        UnsafeByteOperations.unsafeWrap(kv.getRowArray(), kv.getRowOffset(), kv.getRowLength()));
2010      kvbuilder.setFamily(UnsafeByteOperations.unsafeWrap(kv.getFamilyArray(), kv.getFamilyOffset(),
2011        kv.getFamilyLength()));
2012      kvbuilder.setQualifier(UnsafeByteOperations.unsafeWrap(kv.getQualifierArray(),
2013        kv.getQualifierOffset(), kv.getQualifierLength()));
2014      kvbuilder.setCellType(CellProtos.CellType.valueOf(kv.getTypeByte()));
2015      kvbuilder.setTimestamp(kv.getTimestamp());
2016      kvbuilder.setValue(UnsafeByteOperations.unsafeWrap(kv.getValueArray(), kv.getValueOffset(),
2017        kv.getValueLength()));
2018    }
2019    return kvbuilder.build();
2020  }
2021
2022  private static ByteString wrap(ByteBuffer b, int offset, int length) {
2023    ByteBuffer dup = b.duplicate();
2024    dup.position(offset);
2025    dup.limit(offset + length);
2026    return UnsafeByteOperations.unsafeWrap(dup);
2027  }
2028
2029  public static Cell toCell(ExtendedCellBuilder cellBuilder, final CellProtos.Cell cell) {
2030    return cellBuilder.clear()
2031            .setRow(cell.getRow().toByteArray())
2032            .setFamily(cell.getFamily().toByteArray())
2033            .setQualifier(cell.getQualifier().toByteArray())
2034            .setTimestamp(cell.getTimestamp())
2035            .setType((byte) cell.getCellType().getNumber())
2036            .setValue(cell.getValue().toByteArray())
2037            .build();
2038  }
2039
2040  public static HBaseProtos.NamespaceDescriptor toProtoNamespaceDescriptor(NamespaceDescriptor ns) {
2041    HBaseProtos.NamespaceDescriptor.Builder b =
2042        HBaseProtos.NamespaceDescriptor.newBuilder()
2043            .setName(ByteString.copyFromUtf8(ns.getName()));
2044    for(Map.Entry<String, String> entry: ns.getConfiguration().entrySet()) {
2045      b.addConfiguration(HBaseProtos.NameStringPair.newBuilder()
2046          .setName(entry.getKey())
2047          .setValue(entry.getValue()));
2048    }
2049    return b.build();
2050  }
2051
2052  public static NamespaceDescriptor toNamespaceDescriptor(HBaseProtos.NamespaceDescriptor desc) {
2053    NamespaceDescriptor.Builder b = NamespaceDescriptor.create(desc.getName().toStringUtf8());
2054    for (HBaseProtos.NameStringPair prop : desc.getConfigurationList()) {
2055      b.addConfiguration(prop.getName(), prop.getValue());
2056    }
2057    return b.build();
2058  }
2059
2060  public static CompactionDescriptor toCompactionDescriptor(
2061      org.apache.hadoop.hbase.client.RegionInfo info, byte[] family,
2062      List<Path> inputPaths, List<Path> outputPaths, Path storeDir) {
2063    return toCompactionDescriptor(info, null, family, inputPaths, outputPaths, storeDir);
2064  }
2065
2066  public static CompactionDescriptor toCompactionDescriptor(
2067      org.apache.hadoop.hbase.client.RegionInfo info, byte[] regionName,
2068      byte[] family, List<Path> inputPaths, List<Path> outputPaths, Path storeDir) {
2069    // compaction descriptor contains relative paths.
2070    // input / output paths are relative to the store dir
2071    // store dir is relative to region dir
2072    CompactionDescriptor.Builder builder = CompactionDescriptor.newBuilder()
2073        .setTableName(UnsafeByteOperations.unsafeWrap(info.getTable().toBytes()))
2074        .setEncodedRegionName(UnsafeByteOperations.unsafeWrap(
2075          regionName == null ? info.getEncodedNameAsBytes() : regionName))
2076        .setFamilyName(UnsafeByteOperations.unsafeWrap(family))
2077        .setStoreHomeDir(storeDir.getName()); //make relative
2078    for (Path inputPath : inputPaths) {
2079      builder.addCompactionInput(inputPath.getName()); //relative path
2080    }
2081    for (Path outputPath : outputPaths) {
2082      builder.addCompactionOutput(outputPath.getName());
2083    }
2084    builder.setRegionName(UnsafeByteOperations.unsafeWrap(info.getRegionName()));
2085    return builder.build();
2086  }
2087
2088  public static FlushDescriptor toFlushDescriptor(FlushAction action, org.apache.hadoop.hbase.client.RegionInfo hri,
2089      long flushSeqId, Map<byte[], List<Path>> committedFiles) {
2090    FlushDescriptor.Builder desc = FlushDescriptor.newBuilder()
2091        .setAction(action)
2092        .setEncodedRegionName(UnsafeByteOperations.unsafeWrap(hri.getEncodedNameAsBytes()))
2093        .setRegionName(UnsafeByteOperations.unsafeWrap(hri.getRegionName()))
2094        .setFlushSequenceNumber(flushSeqId)
2095        .setTableName(UnsafeByteOperations.unsafeWrap(hri.getTable().getName()));
2096
2097    for (Map.Entry<byte[], List<Path>> entry : committedFiles.entrySet()) {
2098      WALProtos.FlushDescriptor.StoreFlushDescriptor.Builder builder =
2099          WALProtos.FlushDescriptor.StoreFlushDescriptor.newBuilder()
2100          .setFamilyName(UnsafeByteOperations.unsafeWrap(entry.getKey()))
2101          .setStoreHomeDir(Bytes.toString(entry.getKey())); //relative to region
2102      if (entry.getValue() != null) {
2103        for (Path path : entry.getValue()) {
2104          builder.addFlushOutput(path.getName());
2105        }
2106      }
2107      desc.addStoreFlushes(builder);
2108    }
2109    return desc.build();
2110  }
2111
2112  public static RegionEventDescriptor toRegionEventDescriptor(
2113      EventType eventType, org.apache.hadoop.hbase.client.RegionInfo hri, long seqId, ServerName server,
2114      Map<byte[], List<Path>> storeFiles) {
2115    final byte[] tableNameAsBytes = hri.getTable().getName();
2116    final byte[] encodedNameAsBytes = hri.getEncodedNameAsBytes();
2117    final byte[] regionNameAsBytes = hri.getRegionName();
2118    return toRegionEventDescriptor(eventType,
2119        tableNameAsBytes,
2120        encodedNameAsBytes,
2121        regionNameAsBytes,
2122        seqId,
2123
2124        server,
2125        storeFiles);
2126  }
2127
2128  public static RegionEventDescriptor toRegionEventDescriptor(EventType eventType,
2129                                                              byte[] tableNameAsBytes,
2130                                                              byte[] encodedNameAsBytes,
2131                                                              byte[] regionNameAsBytes,
2132                                                               long seqId,
2133
2134                                                              ServerName server,
2135                                                              Map<byte[], List<Path>> storeFiles) {
2136    RegionEventDescriptor.Builder desc = RegionEventDescriptor.newBuilder()
2137        .setEventType(eventType)
2138        .setTableName(UnsafeByteOperations.unsafeWrap(tableNameAsBytes))
2139        .setEncodedRegionName(UnsafeByteOperations.unsafeWrap(encodedNameAsBytes))
2140        .setRegionName(UnsafeByteOperations.unsafeWrap(regionNameAsBytes))
2141        .setLogSequenceNumber(seqId)
2142        .setServer(toServerName(server));
2143
2144    for (Entry<byte[], List<Path>> entry : storeFiles.entrySet()) {
2145      StoreDescriptor.Builder builder = StoreDescriptor.newBuilder()
2146          .setFamilyName(UnsafeByteOperations.unsafeWrap(entry.getKey()))
2147          .setStoreHomeDir(Bytes.toString(entry.getKey()));
2148      for (Path path : entry.getValue()) {
2149        builder.addStoreFile(path.getName());
2150      }
2151
2152      desc.addStores(builder);
2153    }
2154    return desc.build();
2155  }
2156
2157  /**
2158   * Return short version of Message toString'd, shorter than TextFormat#shortDebugString.
2159   * Tries to NOT print out data both because it can be big but also so we do not have data in our
2160   * logs. Use judiciously.
2161   * @param m
2162   * @return toString of passed <code>m</code>
2163   */
2164  public static String getShortTextFormat(Message m) {
2165    if (m == null) return "null";
2166    if (m instanceof ScanRequest) {
2167      // This should be small and safe to output.  No data.
2168      return TextFormat.shortDebugString(m);
2169    } else if (m instanceof RegionServerReportRequest) {
2170      // Print a short message only, just the servername and the requests, not the full load.
2171      RegionServerReportRequest r = (RegionServerReportRequest)m;
2172      return "server " + TextFormat.shortDebugString(r.getServer()) +
2173        " load { numberOfRequests: " + r.getLoad().getNumberOfRequests() + " }";
2174    } else if (m instanceof RegionServerStartupRequest) {
2175      // Should be small enough.
2176      return TextFormat.shortDebugString(m);
2177    } else if (m instanceof MutationProto) {
2178      return toShortString((MutationProto)m);
2179    } else if (m instanceof GetRequest) {
2180      GetRequest r = (GetRequest) m;
2181      return "region= " + getStringForByteString(r.getRegion().getValue()) +
2182          ", row=" + getStringForByteString(r.getGet().getRow());
2183    } else if (m instanceof ClientProtos.MultiRequest) {
2184      ClientProtos.MultiRequest r = (ClientProtos.MultiRequest) m;
2185      // Get first set of Actions.
2186      ClientProtos.RegionAction actions = r.getRegionActionList().get(0);
2187      String row = actions.getActionCount() <= 0? "":
2188        getStringForByteString(actions.getAction(0).hasGet()?
2189          actions.getAction(0).getGet().getRow():
2190          actions.getAction(0).getMutation().getRow());
2191      return "region= " + getStringForByteString(actions.getRegion().getValue()) +
2192          ", for " + r.getRegionActionCount() +
2193          " actions and 1st row key=" + row;
2194    } else if (m instanceof ClientProtos.MutateRequest) {
2195      ClientProtos.MutateRequest r = (ClientProtos.MutateRequest) m;
2196      return "region= " + getStringForByteString(r.getRegion().getValue()) +
2197          ", row=" + getStringForByteString(r.getMutation().getRow());
2198    } else if (m instanceof ClientProtos.CoprocessorServiceRequest) {
2199      ClientProtos.CoprocessorServiceRequest r = (ClientProtos.CoprocessorServiceRequest) m;
2200      return "coprocessorService= " + r.getCall().getServiceName() + ":" + r.getCall().getMethodName();
2201    }
2202    return "TODO: " + m.getClass().toString();
2203  }
2204
2205  private static String getStringForByteString(ByteString bs) {
2206    return Bytes.toStringBinary(bs.toByteArray());
2207  }
2208
2209  /**
2210   * Print out some subset of a MutationProto rather than all of it and its data
2211   * @param proto Protobuf to print out
2212   * @return Short String of mutation proto
2213   */
2214  static String toShortString(final MutationProto proto) {
2215    return "row=" + Bytes.toString(proto.getRow().toByteArray()) +
2216        ", type=" + proto.getMutateType().toString();
2217  }
2218
2219  public static TableName toTableName(HBaseProtos.TableName tableNamePB) {
2220    return TableName.valueOf(tableNamePB.getNamespace().asReadOnlyByteBuffer(),
2221        tableNamePB.getQualifier().asReadOnlyByteBuffer());
2222  }
2223
2224  public static HBaseProtos.TableName toProtoTableName(TableName tableName) {
2225    return HBaseProtos.TableName.newBuilder()
2226        .setNamespace(UnsafeByteOperations.unsafeWrap(tableName.getNamespace()))
2227        .setQualifier(UnsafeByteOperations.unsafeWrap(tableName.getQualifier())).build();
2228  }
2229
2230  public static List<TableName> toTableNameList(List<HBaseProtos.TableName> tableNamesList) {
2231    if (tableNamesList == null) {
2232      return new ArrayList<>();
2233    }
2234    return tableNamesList.stream().map(ProtobufUtil::toTableName).collect(Collectors.toList());
2235  }
2236
2237  public static TableName[] getTableNameArray(List<HBaseProtos.TableName> tableNamesList) {
2238    if (tableNamesList == null) {
2239      return new TableName[0];
2240    }
2241    TableName[] tableNames = new TableName[tableNamesList.size()];
2242    for (int i = 0; i < tableNamesList.size(); i++) {
2243      tableNames[i] = toTableName(tableNamesList.get(i));
2244    }
2245    return tableNames;
2246  }
2247
2248  /**
2249   * Convert a protocol buffer CellVisibility to a client CellVisibility
2250   *
2251   * @param proto
2252   * @return the converted client CellVisibility
2253   */
2254  public static CellVisibility toCellVisibility(ClientProtos.CellVisibility proto) {
2255    if (proto == null) return null;
2256    return new CellVisibility(proto.getExpression());
2257  }
2258
2259  /**
2260   * Convert a protocol buffer CellVisibility bytes to a client CellVisibility
2261   *
2262   * @param protoBytes
2263   * @return the converted client CellVisibility
2264   * @throws DeserializationException
2265   */
2266  public static CellVisibility toCellVisibility(byte[] protoBytes) throws DeserializationException {
2267    if (protoBytes == null) return null;
2268    ClientProtos.CellVisibility.Builder builder = ClientProtos.CellVisibility.newBuilder();
2269    ClientProtos.CellVisibility proto = null;
2270    try {
2271      ProtobufUtil.mergeFrom(builder, protoBytes);
2272      proto = builder.build();
2273    } catch (IOException e) {
2274      throw new DeserializationException(e);
2275    }
2276    return toCellVisibility(proto);
2277  }
2278
2279  /**
2280   * Create a protocol buffer CellVisibility based on a client CellVisibility.
2281   *
2282   * @param cellVisibility
2283   * @return a protocol buffer CellVisibility
2284   */
2285  public static ClientProtos.CellVisibility toCellVisibility(CellVisibility cellVisibility) {
2286    ClientProtos.CellVisibility.Builder builder = ClientProtos.CellVisibility.newBuilder();
2287    builder.setExpression(cellVisibility.getExpression());
2288    return builder.build();
2289  }
2290
2291  /**
2292   * Convert a protocol buffer Authorizations to a client Authorizations
2293   *
2294   * @param proto
2295   * @return the converted client Authorizations
2296   */
2297  public static Authorizations toAuthorizations(ClientProtos.Authorizations proto) {
2298    if (proto == null) return null;
2299    return new Authorizations(proto.getLabelList());
2300  }
2301
2302  /**
2303   * Convert a protocol buffer Authorizations bytes to a client Authorizations
2304   *
2305   * @param protoBytes
2306   * @return the converted client Authorizations
2307   * @throws DeserializationException
2308   */
2309  public static Authorizations toAuthorizations(byte[] protoBytes) throws DeserializationException {
2310    if (protoBytes == null) return null;
2311    ClientProtos.Authorizations.Builder builder = ClientProtos.Authorizations.newBuilder();
2312    ClientProtos.Authorizations proto = null;
2313    try {
2314      ProtobufUtil.mergeFrom(builder, protoBytes);
2315      proto = builder.build();
2316    } catch (IOException e) {
2317      throw new DeserializationException(e);
2318    }
2319    return toAuthorizations(proto);
2320  }
2321
2322  /**
2323   * Create a protocol buffer Authorizations based on a client Authorizations.
2324   *
2325   * @param authorizations
2326   * @return a protocol buffer Authorizations
2327   */
2328  public static ClientProtos.Authorizations toAuthorizations(Authorizations authorizations) {
2329    ClientProtos.Authorizations.Builder builder = ClientProtos.Authorizations.newBuilder();
2330    for (String label : authorizations.getLabels()) {
2331      builder.addLabel(label);
2332    }
2333    return builder.build();
2334  }
2335
2336  /**
2337   * Convert a protocol buffer TimeUnit to a client TimeUnit
2338   *
2339   * @param proto
2340   * @return the converted client TimeUnit
2341   */
2342  public static TimeUnit toTimeUnit(final HBaseProtos.TimeUnit proto) {
2343    switch (proto) {
2344      case NANOSECONDS:  return TimeUnit.NANOSECONDS;
2345      case MICROSECONDS: return TimeUnit.MICROSECONDS;
2346      case MILLISECONDS: return TimeUnit.MILLISECONDS;
2347      case SECONDS:      return TimeUnit.SECONDS;
2348      case MINUTES:      return TimeUnit.MINUTES;
2349      case HOURS:        return TimeUnit.HOURS;
2350      case DAYS:         return TimeUnit.DAYS;
2351    }
2352    throw new RuntimeException("Invalid TimeUnit " + proto);
2353  }
2354
2355  /**
2356   * Convert a client TimeUnit to a protocol buffer TimeUnit
2357   *
2358   * @param timeUnit
2359   * @return the converted protocol buffer TimeUnit
2360   */
2361  public static HBaseProtos.TimeUnit toProtoTimeUnit(final TimeUnit timeUnit) {
2362    switch (timeUnit) {
2363      case NANOSECONDS:  return HBaseProtos.TimeUnit.NANOSECONDS;
2364      case MICROSECONDS: return HBaseProtos.TimeUnit.MICROSECONDS;
2365      case MILLISECONDS: return HBaseProtos.TimeUnit.MILLISECONDS;
2366      case SECONDS:      return HBaseProtos.TimeUnit.SECONDS;
2367      case MINUTES:      return HBaseProtos.TimeUnit.MINUTES;
2368      case HOURS:        return HBaseProtos.TimeUnit.HOURS;
2369      case DAYS:         return HBaseProtos.TimeUnit.DAYS;
2370    }
2371    throw new RuntimeException("Invalid TimeUnit " + timeUnit);
2372  }
2373
2374  /**
2375   * Convert a protocol buffer ThrottleType to a client ThrottleType
2376   *
2377   * @param proto
2378   * @return the converted client ThrottleType
2379   */
2380  public static ThrottleType toThrottleType(final QuotaProtos.ThrottleType proto) {
2381    switch (proto) {
2382      case REQUEST_NUMBER: return ThrottleType.REQUEST_NUMBER;
2383      case REQUEST_SIZE:   return ThrottleType.REQUEST_SIZE;
2384      case WRITE_NUMBER:   return ThrottleType.WRITE_NUMBER;
2385      case WRITE_SIZE:     return ThrottleType.WRITE_SIZE;
2386      case READ_NUMBER:    return ThrottleType.READ_NUMBER;
2387      case READ_SIZE:      return ThrottleType.READ_SIZE;
2388    }
2389    throw new RuntimeException("Invalid ThrottleType " + proto);
2390  }
2391
2392  /**
2393   * Convert a client ThrottleType to a protocol buffer ThrottleType
2394   *
2395   * @param type
2396   * @return the converted protocol buffer ThrottleType
2397   */
2398  public static QuotaProtos.ThrottleType toProtoThrottleType(final ThrottleType type) {
2399    switch (type) {
2400      case REQUEST_NUMBER: return QuotaProtos.ThrottleType.REQUEST_NUMBER;
2401      case REQUEST_SIZE:   return QuotaProtos.ThrottleType.REQUEST_SIZE;
2402      case WRITE_NUMBER:   return QuotaProtos.ThrottleType.WRITE_NUMBER;
2403      case WRITE_SIZE:     return QuotaProtos.ThrottleType.WRITE_SIZE;
2404      case READ_NUMBER:    return QuotaProtos.ThrottleType.READ_NUMBER;
2405      case READ_SIZE:      return QuotaProtos.ThrottleType.READ_SIZE;
2406    }
2407    throw new RuntimeException("Invalid ThrottleType " + type);
2408  }
2409
2410  /**
2411   * Convert a protocol buffer QuotaScope to a client QuotaScope
2412   *
2413   * @param proto
2414   * @return the converted client QuotaScope
2415   */
2416  public static QuotaScope toQuotaScope(final QuotaProtos.QuotaScope proto) {
2417    switch (proto) {
2418      case CLUSTER: return QuotaScope.CLUSTER;
2419      case MACHINE: return QuotaScope.MACHINE;
2420    }
2421    throw new RuntimeException("Invalid QuotaScope " + proto);
2422  }
2423
2424  /**
2425   * Convert a client QuotaScope to a protocol buffer QuotaScope
2426   *
2427   * @param scope
2428   * @return the converted protocol buffer QuotaScope
2429   */
2430  public static QuotaProtos.QuotaScope toProtoQuotaScope(final QuotaScope scope) {
2431    switch (scope) {
2432      case CLUSTER: return QuotaProtos.QuotaScope.CLUSTER;
2433      case MACHINE: return QuotaProtos.QuotaScope.MACHINE;
2434    }
2435    throw new RuntimeException("Invalid QuotaScope " + scope);
2436  }
2437
2438  /**
2439   * Convert a protocol buffer QuotaType to a client QuotaType
2440   *
2441   * @param proto
2442   * @return the converted client QuotaType
2443   */
2444  public static QuotaType toQuotaScope(final QuotaProtos.QuotaType proto) {
2445    switch (proto) {
2446      case THROTTLE: return QuotaType.THROTTLE;
2447      case SPACE: return QuotaType.SPACE;
2448    }
2449    throw new RuntimeException("Invalid QuotaType " + proto);
2450  }
2451
2452  /**
2453   * Convert a client QuotaType to a protocol buffer QuotaType
2454   *
2455   * @param type
2456   * @return the converted protocol buffer QuotaType
2457   */
2458  public static QuotaProtos.QuotaType toProtoQuotaScope(final QuotaType type) {
2459    switch (type) {
2460      case THROTTLE: return QuotaProtos.QuotaType.THROTTLE;
2461      case SPACE: return QuotaProtos.QuotaType.SPACE;
2462      default: throw new RuntimeException("Invalid QuotaType " + type);
2463    }
2464  }
2465
2466  /**
2467   * Converts a protocol buffer SpaceViolationPolicy to a client SpaceViolationPolicy.
2468   *
2469   * @param proto The protocol buffer space violation policy.
2470   * @return The corresponding client SpaceViolationPolicy.
2471   */
2472  public static SpaceViolationPolicy toViolationPolicy(
2473      final QuotaProtos.SpaceViolationPolicy proto) {
2474    switch (proto) {
2475      case DISABLE: return SpaceViolationPolicy.DISABLE;
2476      case NO_WRITES_COMPACTIONS: return SpaceViolationPolicy.NO_WRITES_COMPACTIONS;
2477      case NO_WRITES: return SpaceViolationPolicy.NO_WRITES;
2478      case NO_INSERTS: return SpaceViolationPolicy.NO_INSERTS;
2479    }
2480    throw new RuntimeException("Invalid SpaceViolationPolicy " + proto);
2481  }
2482
2483  /**
2484   * Converts a client SpaceViolationPolicy to a protocol buffer SpaceViolationPolicy.
2485   *
2486   * @param policy The client SpaceViolationPolicy object.
2487   * @return The corresponding protocol buffer SpaceViolationPolicy.
2488   */
2489  public static QuotaProtos.SpaceViolationPolicy toProtoViolationPolicy(
2490      final SpaceViolationPolicy policy) {
2491    switch (policy) {
2492      case DISABLE: return QuotaProtos.SpaceViolationPolicy.DISABLE;
2493      case NO_WRITES_COMPACTIONS: return QuotaProtos.SpaceViolationPolicy.NO_WRITES_COMPACTIONS;
2494      case NO_WRITES: return QuotaProtos.SpaceViolationPolicy.NO_WRITES;
2495      case NO_INSERTS: return QuotaProtos.SpaceViolationPolicy.NO_INSERTS;
2496    }
2497    throw new RuntimeException("Invalid SpaceViolationPolicy " + policy);
2498  }
2499
2500  /**
2501   * Build a protocol buffer TimedQuota
2502   *
2503   * @param limit the allowed number of request/data per timeUnit
2504   * @param timeUnit the limit time unit
2505   * @param scope the quota scope
2506   * @return the protocol buffer TimedQuota
2507   */
2508  public static QuotaProtos.TimedQuota toTimedQuota(final long limit, final TimeUnit timeUnit,
2509      final QuotaScope scope) {
2510    return QuotaProtos.TimedQuota.newBuilder()
2511            .setSoftLimit(limit)
2512            .setTimeUnit(toProtoTimeUnit(timeUnit))
2513            .setScope(toProtoQuotaScope(scope))
2514            .build();
2515  }
2516
2517  /**
2518   * Builds a protocol buffer SpaceQuota.
2519   *
2520   * @param limit The maximum space usage for the quota in bytes.
2521   * @param violationPolicy The policy to apply when the quota is violated.
2522   * @return The protocol buffer SpaceQuota.
2523   */
2524  public static QuotaProtos.SpaceQuota toProtoSpaceQuota(
2525      final long limit, final SpaceViolationPolicy violationPolicy) {
2526    return QuotaProtos.SpaceQuota.newBuilder()
2527        .setSoftLimit(limit)
2528        .setViolationPolicy(toProtoViolationPolicy(violationPolicy))
2529        .build();
2530  }
2531
2532  /**
2533   * Generates a marker for the WAL so that we propagate the notion of a bulk region load
2534   * throughout the WAL.
2535   *
2536   * @param tableName         The tableName into which the bulk load is being imported into.
2537   * @param encodedRegionName Encoded region name of the region which is being bulk loaded.
2538   * @param storeFiles        A set of store files of a column family are bulk loaded.
2539   * @param storeFilesSize  Map of store files and their lengths
2540   * @param bulkloadSeqId     sequence ID (by a force flush) used to create bulk load hfile
2541   *                          name
2542   * @return The WAL log marker for bulk loads.
2543   */
2544  public static WALProtos.BulkLoadDescriptor toBulkLoadDescriptor(TableName tableName,
2545      ByteString encodedRegionName, Map<byte[], List<Path>> storeFiles,
2546      Map<String, Long> storeFilesSize, long bulkloadSeqId) {
2547    BulkLoadDescriptor.Builder desc =
2548        BulkLoadDescriptor.newBuilder()
2549        .setTableName(ProtobufUtil.toProtoTableName(tableName))
2550        .setEncodedRegionName(encodedRegionName).setBulkloadSeqNum(bulkloadSeqId);
2551
2552    for (Map.Entry<byte[], List<Path>> entry : storeFiles.entrySet()) {
2553      WALProtos.StoreDescriptor.Builder builder = StoreDescriptor.newBuilder()
2554          .setFamilyName(UnsafeByteOperations.unsafeWrap(entry.getKey()))
2555          .setStoreHomeDir(Bytes.toString(entry.getKey())); // relative to region
2556      for (Path path : entry.getValue()) {
2557        String name = path.getName();
2558        builder.addStoreFile(name);
2559        Long size = storeFilesSize.get(name) == null ? (Long) 0L : storeFilesSize.get(name);
2560        builder.setStoreFileSizeBytes(size);
2561      }
2562      desc.addStores(builder);
2563    }
2564
2565    return desc.build();
2566  }
2567
2568  /**
2569   * This version of protobuf's mergeDelimitedFrom avoid the hard-coded 64MB limit for decoding
2570   * buffers
2571   * @param builder current message builder
2572   * @param in Inputsream with delimited protobuf data
2573   * @throws IOException
2574   */
2575  public static void mergeDelimitedFrom(Message.Builder builder, InputStream in)
2576    throws IOException {
2577    // This used to be builder.mergeDelimitedFrom(in);
2578    // but is replaced to allow us to bump the protobuf size limit.
2579    final int firstByte = in.read();
2580    if (firstByte != -1) {
2581      final int size = CodedInputStream.readRawVarint32(firstByte, in);
2582      final InputStream limitedInput = ByteStreams.limit(in, size);
2583      final CodedInputStream codedInput = CodedInputStream.newInstance(limitedInput);
2584      codedInput.setSizeLimit(size);
2585      builder.mergeFrom(codedInput);
2586      codedInput.checkLastTagWas(0);
2587    }
2588  }
2589
2590  /**
2591   * This version of protobuf's mergeFrom avoids the hard-coded 64MB limit for decoding
2592   * buffers where the message size is known
2593   * @param builder current message builder
2594   * @param in InputStream containing protobuf data
2595   * @param size known size of protobuf data
2596   * @throws IOException
2597   */
2598  public static void mergeFrom(Message.Builder builder, InputStream in, int size)
2599      throws IOException {
2600    final CodedInputStream codedInput = CodedInputStream.newInstance(in);
2601    codedInput.setSizeLimit(size);
2602    builder.mergeFrom(codedInput);
2603    codedInput.checkLastTagWas(0);
2604  }
2605
2606  /**
2607   * This version of protobuf's mergeFrom avoids the hard-coded 64MB limit for decoding
2608   * buffers where the message size is not known
2609   * @param builder current message builder
2610   * @param in InputStream containing protobuf data
2611   * @throws IOException
2612   */
2613  public static void mergeFrom(Message.Builder builder, InputStream in)
2614      throws IOException {
2615    final CodedInputStream codedInput = CodedInputStream.newInstance(in);
2616    codedInput.setSizeLimit(Integer.MAX_VALUE);
2617    builder.mergeFrom(codedInput);
2618    codedInput.checkLastTagWas(0);
2619  }
2620
2621  /**
2622   * This version of protobuf's mergeFrom avoids the hard-coded 64MB limit for decoding
2623   * buffers when working with ByteStrings
2624   * @param builder current message builder
2625   * @param bs ByteString containing the
2626   * @throws IOException
2627   */
2628  public static void mergeFrom(Message.Builder builder, ByteString bs) throws IOException {
2629    final CodedInputStream codedInput = bs.newCodedInput();
2630    codedInput.setSizeLimit(bs.size());
2631    builder.mergeFrom(codedInput);
2632    codedInput.checkLastTagWas(0);
2633  }
2634
2635  /**
2636   * This version of protobuf's mergeFrom avoids the hard-coded 64MB limit for decoding
2637   * buffers when working with byte arrays
2638   * @param builder current message builder
2639   * @param b byte array
2640   * @throws IOException
2641   */
2642  public static void mergeFrom(Message.Builder builder, byte[] b) throws IOException {
2643    final CodedInputStream codedInput = CodedInputStream.newInstance(b);
2644    codedInput.setSizeLimit(b.length);
2645    builder.mergeFrom(codedInput);
2646    codedInput.checkLastTagWas(0);
2647  }
2648
2649  /**
2650   * This version of protobuf's mergeFrom avoids the hard-coded 64MB limit for decoding
2651   * buffers when working with byte arrays
2652   * @param builder current message builder
2653   * @param b byte array
2654   * @param offset
2655   * @param length
2656   * @throws IOException
2657   */
2658  public static void mergeFrom(Message.Builder builder, byte[] b, int offset, int length)
2659      throws IOException {
2660    final CodedInputStream codedInput = CodedInputStream.newInstance(b, offset, length);
2661    codedInput.setSizeLimit(length);
2662    builder.mergeFrom(codedInput);
2663    codedInput.checkLastTagWas(0);
2664  }
2665
2666  public static void mergeFrom(Message.Builder builder, CodedInputStream codedInput, int length)
2667      throws IOException {
2668    codedInput.resetSizeCounter();
2669    int prevLimit = codedInput.setSizeLimit(length);
2670
2671    int limit = codedInput.pushLimit(length);
2672    builder.mergeFrom(codedInput);
2673    codedInput.popLimit(limit);
2674
2675    codedInput.checkLastTagWas(0);
2676    codedInput.setSizeLimit(prevLimit);
2677  }
2678
2679  public static ReplicationLoadSink toReplicationLoadSink(
2680      ClusterStatusProtos.ReplicationLoadSink rls) {
2681    return new ReplicationLoadSink(rls.getAgeOfLastAppliedOp(), rls.getTimeStampsOfLastAppliedOp());
2682  }
2683
2684  public static ReplicationLoadSource toReplicationLoadSource(
2685      ClusterStatusProtos.ReplicationLoadSource rls) {
2686    return new ReplicationLoadSource(rls.getPeerID(), rls.getAgeOfLastShippedOp(),
2687      rls.getSizeOfLogQueue(), rls.getTimeStampOfLastShippedOp(), rls.getReplicationLag());
2688  }
2689
2690  /**
2691   * Get a protocol buffer VersionInfo
2692   *
2693   * @return the converted protocol buffer VersionInfo
2694   */
2695  public static HBaseProtos.VersionInfo getVersionInfo() {
2696    HBaseProtos.VersionInfo.Builder builder = HBaseProtos.VersionInfo.newBuilder();
2697    String version = VersionInfo.getVersion();
2698    builder.setVersion(version);
2699    String[] components = version.split("\\.");
2700    if (components != null && components.length > 2) {
2701      builder.setVersionMajor(Integer.parseInt(components[0]));
2702      builder.setVersionMinor(Integer.parseInt(components[1]));
2703    }
2704    builder.setUrl(VersionInfo.getUrl());
2705    builder.setRevision(VersionInfo.getRevision());
2706    builder.setUser(VersionInfo.getUser());
2707    builder.setDate(VersionInfo.getDate());
2708    builder.setSrcChecksum(VersionInfo.getSrcChecksum());
2709    return builder.build();
2710  }
2711
2712  /**
2713   * Convert SecurityCapabilitiesResponse.Capability to SecurityCapability
2714   * @param capabilities capabilities returned in the SecurityCapabilitiesResponse message
2715   * @return the converted list of SecurityCapability elements
2716   */
2717  public static List<SecurityCapability> toSecurityCapabilityList(
2718      List<MasterProtos.SecurityCapabilitiesResponse.Capability> capabilities) {
2719    List<SecurityCapability> scList = new ArrayList<>(capabilities.size());
2720    for (MasterProtos.SecurityCapabilitiesResponse.Capability c: capabilities) {
2721      try {
2722        scList.add(SecurityCapability.valueOf(c.getNumber()));
2723      } catch (IllegalArgumentException e) {
2724        // Unknown capability, just ignore it. We don't understand the new capability
2725        // but don't care since by definition we cannot take advantage of it.
2726      }
2727    }
2728    return scList;
2729  }
2730
2731  public static TimeRange toTimeRange(HBaseProtos.TimeRange timeRange) {
2732    return timeRange == null ?
2733      TimeRange.allTime() :
2734      new TimeRange(timeRange.hasFrom() ? timeRange.getFrom() : 0,
2735        timeRange.hasTo() ? timeRange.getTo() : Long.MAX_VALUE);
2736  }
2737
2738  /**
2739   * Converts an ColumnFamilyDescriptor to ColumnFamilySchema
2740   * @param hcd the ColumnFamilySchema
2741   * @return Convert this instance to a the pb column family type
2742   */
2743  public static ColumnFamilySchema toColumnFamilySchema(ColumnFamilyDescriptor hcd) {
2744    ColumnFamilySchema.Builder builder = ColumnFamilySchema.newBuilder();
2745    builder.setName(UnsafeByteOperations.unsafeWrap(hcd.getName()));
2746    for (Map.Entry<Bytes, Bytes> e : hcd.getValues().entrySet()) {
2747      BytesBytesPair.Builder aBuilder = BytesBytesPair.newBuilder();
2748      aBuilder.setFirst(UnsafeByteOperations.unsafeWrap(e.getKey().get()));
2749      aBuilder.setSecond(UnsafeByteOperations.unsafeWrap(e.getValue().get()));
2750      builder.addAttributes(aBuilder.build());
2751    }
2752    for (Map.Entry<String, String> e : hcd.getConfiguration().entrySet()) {
2753      NameStringPair.Builder aBuilder = NameStringPair.newBuilder();
2754      aBuilder.setName(e.getKey());
2755      aBuilder.setValue(e.getValue());
2756      builder.addConfiguration(aBuilder.build());
2757    }
2758    return builder.build();
2759  }
2760
2761  /**
2762   * Converts a ColumnFamilySchema to ColumnFamilyDescriptor
2763   * @param cfs the ColumnFamilySchema
2764   * @return An {@link ColumnFamilyDescriptor} made from the passed in <code>cfs</code>
2765   */
2766  public static ColumnFamilyDescriptor toColumnFamilyDescriptor(final ColumnFamilySchema cfs) {
2767    // Use the empty constructor so we preserve the initial values set on construction for things
2768    // like maxVersion.  Otherwise, we pick up wrong values on deserialization which makes for
2769    // unrelated-looking test failures that are hard to trace back to here.
2770    ColumnFamilyDescriptorBuilder builder
2771      = ColumnFamilyDescriptorBuilder.newBuilder(cfs.getName().toByteArray());
2772    cfs.getAttributesList().forEach(a -> builder.setValue(a.getFirst().toByteArray(), a.getSecond().toByteArray()));
2773    cfs.getConfigurationList().forEach(a -> builder.setConfiguration(a.getName(), a.getValue()));
2774    return builder.build();
2775  }
2776
2777  /**
2778   * Converts an TableDescriptor to TableSchema
2779   * @param htd the TableDescriptor
2780   * @return Convert the current {@link TableDescriptor} into a pb TableSchema instance.
2781   */
2782  public static TableSchema toTableSchema(TableDescriptor htd) {
2783    TableSchema.Builder builder = TableSchema.newBuilder();
2784    builder.setTableName(toProtoTableName(htd.getTableName()));
2785    for (Map.Entry<Bytes, Bytes> e : htd.getValues().entrySet()) {
2786      BytesBytesPair.Builder aBuilder = BytesBytesPair.newBuilder();
2787      aBuilder.setFirst(UnsafeByteOperations.unsafeWrap(e.getKey().get()));
2788      aBuilder.setSecond(UnsafeByteOperations.unsafeWrap(e.getValue().get()));
2789      builder.addAttributes(aBuilder.build());
2790    }
2791    for (ColumnFamilyDescriptor hcd : htd.getColumnFamilies()) {
2792      builder.addColumnFamilies(toColumnFamilySchema(hcd));
2793    }
2794    return builder.build();
2795  }
2796
2797  /**
2798   * Converts a TableSchema to TableDescriptor
2799   * @param ts A pb TableSchema instance.
2800   * @return An {@link TableDescriptor} made from the passed in pb <code>ts</code>.
2801   */
2802  public static TableDescriptor toTableDescriptor(final TableSchema ts) {
2803    TableDescriptorBuilder builder
2804      = TableDescriptorBuilder.newBuilder(ProtobufUtil.toTableName(ts.getTableName()));
2805    ts.getColumnFamiliesList()
2806      .stream()
2807      .map(ProtobufUtil::toColumnFamilyDescriptor)
2808      .forEach(builder::setColumnFamily);
2809    ts.getAttributesList()
2810      .forEach(a -> builder.setValue(a.getFirst().toByteArray(), a.getSecond().toByteArray()));
2811    ts.getConfigurationList()
2812      .forEach(a -> builder.setValue(a.getName(), a.getValue()));
2813    return builder.build();
2814  }
2815
2816  /**
2817   * Creates {@link CompactionState} from
2818   * {@link org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse.CompactionState}
2819   * state
2820   * @param state the protobuf CompactionState
2821   * @return CompactionState
2822   */
2823  public static CompactionState createCompactionState(GetRegionInfoResponse.CompactionState state) {
2824    return CompactionState.valueOf(state.toString());
2825  }
2826
2827  public static GetRegionInfoResponse.CompactionState createCompactionState(CompactionState state) {
2828    return GetRegionInfoResponse.CompactionState.valueOf(state.toString());
2829  }
2830
2831  public static Optional<Long> toOptionalTimestamp(MajorCompactionTimestampResponse resp) {
2832    long timestamp = resp.getCompactionTimestamp();
2833    return timestamp == 0 ? Optional.empty() : Optional.of(timestamp);
2834  }
2835
2836  /**
2837   * Creates {@link org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription.Type}
2838   * from {@link SnapshotType}
2839   * @param type the SnapshotDescription type
2840   * @return the protobuf SnapshotDescription type
2841   */
2842  public static SnapshotProtos.SnapshotDescription.Type
2843      createProtosSnapShotDescType(SnapshotType type) {
2844    return SnapshotProtos.SnapshotDescription.Type.valueOf(type.name());
2845  }
2846
2847  /**
2848   * Creates {@link org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription.Type}
2849   * from the type of SnapshotDescription string
2850   * @param snapshotDesc string representing the snapshot description type
2851   * @return the protobuf SnapshotDescription type
2852   */
2853  public static SnapshotProtos.SnapshotDescription.Type
2854      createProtosSnapShotDescType(String snapshotDesc) {
2855    return SnapshotProtos.SnapshotDescription.Type.valueOf(snapshotDesc.toUpperCase(Locale.ROOT));
2856  }
2857
2858  /**
2859   * Creates {@link SnapshotType} from the type of
2860   * {@link org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription}
2861   * @param type the snapshot description type
2862   * @return the protobuf SnapshotDescription type
2863   */
2864  public static SnapshotType createSnapshotType(SnapshotProtos.SnapshotDescription.Type type) {
2865    return SnapshotType.valueOf(type.toString());
2866  }
2867
2868  /**
2869   * Convert from {@link SnapshotDescription} to
2870   * {@link org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription}
2871   * @param snapshotDesc the POJO SnapshotDescription
2872   * @return the protobuf SnapshotDescription
2873   */
2874  public static SnapshotProtos.SnapshotDescription
2875      createHBaseProtosSnapshotDesc(SnapshotDescription snapshotDesc) {
2876    SnapshotProtos.SnapshotDescription.Builder builder = SnapshotProtos.SnapshotDescription.newBuilder();
2877    if (snapshotDesc.getTableName() != null) {
2878      builder.setTable(snapshotDesc.getTableNameAsString());
2879    }
2880    if (snapshotDesc.getName() != null) {
2881      builder.setName(snapshotDesc.getName());
2882    }
2883    if (snapshotDesc.getOwner() != null) {
2884      builder.setOwner(snapshotDesc.getOwner());
2885    }
2886    if (snapshotDesc.getCreationTime() != -1L) {
2887      builder.setCreationTime(snapshotDesc.getCreationTime());
2888    }
2889    if (snapshotDesc.getVersion() != -1) {
2890      builder.setVersion(snapshotDesc.getVersion());
2891    }
2892    builder.setType(ProtobufUtil.createProtosSnapShotDescType(snapshotDesc.getType()));
2893    SnapshotProtos.SnapshotDescription snapshot = builder.build();
2894    return snapshot;
2895  }
2896
2897  /**
2898   * Convert from
2899   * {@link org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription} to
2900   * {@link SnapshotDescription}
2901   * @param snapshotDesc the protobuf SnapshotDescription
2902   * @return the POJO SnapshotDescription
2903   */
2904  public static SnapshotDescription
2905      createSnapshotDesc(SnapshotProtos.SnapshotDescription snapshotDesc) {
2906    return new SnapshotDescription(snapshotDesc.getName(),
2907        snapshotDesc.hasTable() ? TableName.valueOf(snapshotDesc.getTable()) : null,
2908        createSnapshotType(snapshotDesc.getType()), snapshotDesc.getOwner(),
2909        snapshotDesc.getCreationTime(), snapshotDesc.getVersion());
2910  }
2911
2912  public static RegionLoadStats createRegionLoadStats(ClientProtos.RegionLoadStats stats) {
2913    return new RegionLoadStats(stats.getMemStoreLoad(), stats.getHeapOccupancy(),
2914        stats.getCompactionPressure());
2915  }
2916
2917  /**
2918   * @param msg
2919   * @return A String version of the passed in <code>msg</code>
2920   */
2921  public static String toText(Message msg) {
2922    return TextFormat.shortDebugString(msg);
2923  }
2924
2925  public static byte [] toBytes(ByteString bs) {
2926    return bs.toByteArray();
2927  }
2928
2929  /**
2930   * Contain ServiceException inside here. Take a callable that is doing our pb rpc and run it.
2931   * @throws IOException
2932   */
2933  public static <T> T call(Callable<T> callable) throws IOException {
2934    try {
2935      return callable.call();
2936    } catch (Exception e) {
2937      throw ProtobufUtil.handleRemoteException(e);
2938    }
2939  }
2940
2941  /**
2942    * Create a protocol buffer GetStoreFileRequest for a given region name
2943    *
2944    * @param regionName the name of the region to get info
2945    * @param family the family to get store file list
2946    * @return a protocol buffer GetStoreFileRequest
2947    */
2948   public static GetStoreFileRequest
2949       buildGetStoreFileRequest(final byte[] regionName, final byte[] family) {
2950     GetStoreFileRequest.Builder builder = GetStoreFileRequest.newBuilder();
2951     RegionSpecifier region = RequestConverter.buildRegionSpecifier(
2952       RegionSpecifierType.REGION_NAME, regionName);
2953     builder.setRegion(region);
2954     builder.addFamily(UnsafeByteOperations.unsafeWrap(family));
2955     return builder.build();
2956   }
2957
2958  /**
2959    * Create a CloseRegionRequest for a given region name
2960    *
2961    * @param regionName the name of the region to close
2962    * @return a CloseRegionRequest
2963    */
2964   public static CloseRegionRequest buildCloseRegionRequest(ServerName server,
2965       final byte[] regionName) {
2966     return ProtobufUtil.buildCloseRegionRequest(server, regionName, null);
2967   }
2968
2969  public static CloseRegionRequest buildCloseRegionRequest(ServerName server,
2970    final byte[] regionName, ServerName destinationServer) {
2971    CloseRegionRequest.Builder builder = CloseRegionRequest.newBuilder();
2972    RegionSpecifier region = RequestConverter.buildRegionSpecifier(
2973      RegionSpecifierType.REGION_NAME, regionName);
2974    builder.setRegion(region);
2975    if (destinationServer != null){
2976      builder.setDestinationServer(toServerName(destinationServer));
2977    }
2978    if (server != null) {
2979      builder.setServerStartCode(server.getStartcode());
2980    }
2981    return builder.build();
2982  }
2983
2984  public static ProcedureDescription buildProcedureDescription(String signature, String instance,
2985      Map<String, String> props) {
2986    ProcedureDescription.Builder builder =
2987        ProcedureDescription.newBuilder().setSignature(signature).setInstance(instance);
2988    if (props != null && !props.isEmpty()) {
2989      props.entrySet().forEach(entry -> builder.addConfiguration(
2990        NameStringPair.newBuilder().setName(entry.getKey()).setValue(entry.getValue()).build()));
2991    }
2992    return builder.build();
2993  }
2994
2995  /**
2996   * Get a ServerName from the passed in data bytes.
2997   * @param data Data with a serialize server name in it; can handle the old style
2998   * servername where servername was host and port.  Works too with data that
2999   * begins w/ the pb 'PBUF' magic and that is then followed by a protobuf that
3000   * has a serialized {@link ServerName} in it.
3001   * @return Returns null if <code>data</code> is null else converts passed data
3002   * to a ServerName instance.
3003   * @throws DeserializationException
3004   */
3005  public static ServerName parseServerNameFrom(final byte [] data) throws DeserializationException {
3006    if (data == null || data.length <= 0) return null;
3007    if (ProtobufMagic.isPBMagicPrefix(data)) {
3008      int prefixLen = ProtobufMagic.lengthOfPBMagic();
3009      try {
3010        ZooKeeperProtos.Master rss =
3011          ZooKeeperProtos.Master.PARSER.parseFrom(data, prefixLen, data.length - prefixLen);
3012        org.apache.hadoop.hbase.shaded.protobuf.generated.HBaseProtos.ServerName sn =
3013            rss.getMaster();
3014        return ServerName.valueOf(sn.getHostName(), sn.getPort(), sn.getStartCode());
3015      } catch (/*InvalidProtocolBufferException*/IOException e) {
3016        // A failed parse of the znode is pretty catastrophic. Rather than loop
3017        // retrying hoping the bad bytes will changes, and rather than change
3018        // the signature on this method to add an IOE which will send ripples all
3019        // over the code base, throw a RuntimeException.  This should "never" happen.
3020        // Fail fast if it does.
3021        throw new DeserializationException(e);
3022      }
3023    }
3024    // The str returned could be old style -- pre hbase-1502 -- which was
3025    // hostname and port seperated by a colon rather than hostname, port and
3026    // startcode delimited by a ','.
3027    String str = Bytes.toString(data);
3028    int index = str.indexOf(ServerName.SERVERNAME_SEPARATOR);
3029    if (index != -1) {
3030      // Presume its ServerName serialized with versioned bytes.
3031      return ServerName.parseVersionedServerName(data);
3032    }
3033    // Presume it a hostname:port format.
3034    String hostname = Addressing.parseHostname(str);
3035    int port = Addressing.parsePort(str);
3036    return ServerName.valueOf(hostname, port, -1L);
3037  }
3038
3039  /**
3040   * Helper to convert the protobuf Procedure to JSON String
3041   * @return Convert the current Protocol Buffers Procedure to JSON String
3042   */
3043  public static String toProcedureJson(List<ProcedureProtos.Procedure> procProtos) {
3044    JsonArray procJsons = new JsonArray(procProtos.size());
3045    for (ProcedureProtos.Procedure procProto : procProtos) {
3046      try {
3047        JsonElement procJson = ProtobufMessageConverter.toJsonElement(procProto);
3048        procJsons.add(procJson);
3049      } catch (InvalidProtocolBufferException e) {
3050        procJsons.add(e.toString());
3051      }
3052    }
3053    return procJsons.toString();
3054  }
3055
3056  public static String toLockJson(List<LockServiceProtos.LockedResource> lockedResourceProtos) {
3057    JsonArray lockedResourceJsons = new JsonArray(lockedResourceProtos.size());
3058    for (LockServiceProtos.LockedResource lockedResourceProto : lockedResourceProtos) {
3059      try {
3060        JsonElement lockedResourceJson = ProtobufMessageConverter.toJsonElement(lockedResourceProto);
3061        lockedResourceJsons.add(lockedResourceJson);
3062      } catch (InvalidProtocolBufferException e) {
3063        lockedResourceJsons.add(e.toString());
3064      }
3065    }
3066    return lockedResourceJsons.toString();
3067  }
3068
3069  /**
3070   * Convert a RegionInfo to a Proto RegionInfo
3071   *
3072   * @param info the RegionInfo to convert
3073   * @return the converted Proto RegionInfo
3074   */
3075  public static HBaseProtos.RegionInfo toRegionInfo(final org.apache.hadoop.hbase.client.RegionInfo info) {
3076    if (info == null) return null;
3077    HBaseProtos.RegionInfo.Builder builder = HBaseProtos.RegionInfo.newBuilder();
3078    builder.setTableName(ProtobufUtil.toProtoTableName(info.getTable()));
3079    builder.setRegionId(info.getRegionId());
3080    if (info.getStartKey() != null) {
3081      builder.setStartKey(UnsafeByteOperations.unsafeWrap(info.getStartKey()));
3082    }
3083    if (info.getEndKey() != null) {
3084      builder.setEndKey(UnsafeByteOperations.unsafeWrap(info.getEndKey()));
3085    }
3086    builder.setOffline(info.isOffline());
3087    builder.setSplit(info.isSplit());
3088    builder.setReplicaId(info.getReplicaId());
3089    return builder.build();
3090  }
3091
3092  /**
3093   * Convert HBaseProto.RegionInfo to a RegionInfo
3094   *
3095   * @param proto the RegionInfo to convert
3096   * @return the converted RegionInfo
3097   */
3098  public static org.apache.hadoop.hbase.client.RegionInfo toRegionInfo(final HBaseProtos.RegionInfo proto) {
3099    if (proto == null) return null;
3100    TableName tableName = ProtobufUtil.toTableName(proto.getTableName());
3101    long regionId = proto.getRegionId();
3102    int defaultReplicaId = org.apache.hadoop.hbase.client.RegionInfo.DEFAULT_REPLICA_ID;
3103    int replicaId = proto.hasReplicaId()? proto.getReplicaId(): defaultReplicaId;
3104    if (tableName.equals(TableName.META_TABLE_NAME) && replicaId == defaultReplicaId) {
3105      return RegionInfoBuilder.FIRST_META_REGIONINFO;
3106    }
3107    byte[] startKey = null;
3108    byte[] endKey = null;
3109    if (proto.hasStartKey()) {
3110      startKey = proto.getStartKey().toByteArray();
3111    }
3112    if (proto.hasEndKey()) {
3113      endKey = proto.getEndKey().toByteArray();
3114    }
3115    boolean split = false;
3116    if (proto.hasSplit()) {
3117      split = proto.getSplit();
3118    }
3119    RegionInfoBuilder rib = RegionInfoBuilder.newBuilder(tableName)
3120    .setStartKey(startKey)
3121    .setEndKey(endKey)
3122    .setRegionId(regionId)
3123    .setReplicaId(replicaId)
3124    .setSplit(split);
3125    if (proto.hasOffline()) {
3126      rib.setOffline(proto.getOffline());
3127    }
3128    return rib.build();
3129  }
3130
3131  public static List<SnapshotDescription> toSnapshotDescriptionList(
3132      GetCompletedSnapshotsResponse response, Pattern pattern) {
3133    return response.getSnapshotsList().stream().map(ProtobufUtil::createSnapshotDesc)
3134        .filter(snap -> pattern != null ? pattern.matcher(snap.getName()).matches() : true)
3135        .collect(Collectors.toList());
3136  }
3137
3138  public static CacheEvictionStats toCacheEvictionStats(
3139      HBaseProtos.CacheEvictionStats stats) throws IOException{
3140    CacheEvictionStatsBuilder builder = CacheEvictionStats.builder();
3141    builder.withEvictedBlocks(stats.getEvictedBlocks())
3142        .withMaxCacheSize(stats.getMaxCacheSize());
3143    if (stats.getExceptionCount() > 0) {
3144      for (HBaseProtos.RegionExceptionMessage exception : stats.getExceptionList()) {
3145        HBaseProtos.RegionSpecifier rs = exception.getRegion();
3146        byte[] regionName = rs.getValue().toByteArray();
3147        builder.addException(regionName, ProtobufUtil.toException(exception.getException()));
3148      }
3149    }
3150    return builder.build();
3151  }
3152
3153  public static HBaseProtos.CacheEvictionStats toCacheEvictionStats(
3154      CacheEvictionStats cacheEvictionStats) {
3155    HBaseProtos.CacheEvictionStats.Builder builder
3156        = HBaseProtos.CacheEvictionStats.newBuilder();
3157    for (Map.Entry<byte[], Throwable> entry : cacheEvictionStats.getExceptions().entrySet()) {
3158      builder.addException(
3159          RegionExceptionMessage.newBuilder()
3160          .setRegion(RequestConverter.buildRegionSpecifier(
3161                  RegionSpecifierType.REGION_NAME, entry.getKey()))
3162          .setException(ResponseConverter.buildException(entry.getValue()))
3163          .build()
3164      );
3165    }
3166    return builder
3167        .setEvictedBlocks(cacheEvictionStats.getEvictedBlocks())
3168        .setMaxCacheSize(cacheEvictionStats.getMaxCacheSize())
3169        .build();
3170  }
3171
3172  public static ClusterStatusProtos.ReplicationLoadSource toReplicationLoadSource(
3173      ReplicationLoadSource rls) {
3174    return ClusterStatusProtos.ReplicationLoadSource.newBuilder()
3175        .setPeerID(rls.getPeerID())
3176        .setAgeOfLastShippedOp(rls.getAgeOfLastShippedOp())
3177        .setSizeOfLogQueue((int) rls.getSizeOfLogQueue())
3178        .setTimeStampOfLastShippedOp(rls.getTimestampOfLastShippedOp())
3179        .setReplicationLag(rls.getReplicationLag())
3180        .build();
3181  }
3182
3183  public static ClusterStatusProtos.ReplicationLoadSink toReplicationLoadSink(
3184      ReplicationLoadSink rls) {
3185    return ClusterStatusProtos.ReplicationLoadSink.newBuilder()
3186        .setAgeOfLastAppliedOp(rls.getAgeOfLastAppliedOp())
3187        .setTimeStampsOfLastAppliedOp(rls.getTimestampsOfLastAppliedOp())
3188        .build();
3189  }
3190
3191  public static HBaseProtos.TimeRange toTimeRange(TimeRange timeRange) {
3192    if (timeRange == null) {
3193      timeRange = TimeRange.allTime();
3194    }
3195    return HBaseProtos.TimeRange.newBuilder().setFrom(timeRange.getMin())
3196      .setTo(timeRange.getMax())
3197      .build();
3198  }
3199}