View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.protobuf;
19  
20  
21  import static org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier.RegionSpecifierType.REGION_NAME;
22  
23  import java.io.ByteArrayOutputStream;
24  import java.io.IOException;
25  import java.io.InputStream;
26  import java.io.InterruptedIOException;
27  import java.lang.reflect.Constructor;
28  import java.lang.reflect.InvocationTargetException;
29  import java.lang.reflect.Method;
30  import java.lang.reflect.ParameterizedType;
31  import java.lang.reflect.Type;
32  import java.nio.ByteBuffer;
33  import java.security.PrivilegedExceptionAction;
34  import java.util.ArrayList;
35  import java.util.Collection;
36  import java.util.HashMap;
37  import java.util.List;
38  import java.util.Map;
39  import java.util.Map.Entry;
40  import java.util.NavigableSet;
41  import java.util.concurrent.TimeUnit;
42  
43  import org.apache.hadoop.conf.Configuration;
44  import org.apache.hadoop.fs.Path;
45  import org.apache.hadoop.hbase.Cell;
46  import org.apache.hadoop.hbase.CellScanner;
47  import org.apache.hadoop.hbase.CellUtil;
48  import org.apache.hadoop.hbase.DoNotRetryIOException;
49  import org.apache.hadoop.hbase.HBaseConfiguration;
50  import org.apache.hadoop.hbase.HConstants;
51  import org.apache.hadoop.hbase.HRegionInfo;
52  import org.apache.hadoop.hbase.HTableDescriptor;
53  import org.apache.hadoop.hbase.KeyValue;
54  import org.apache.hadoop.hbase.NamespaceDescriptor;
55  import org.apache.hadoop.hbase.ServerName;
56  import org.apache.hadoop.hbase.TableName;
57  import org.apache.hadoop.hbase.Tag;
58  import org.apache.hadoop.hbase.classification.InterfaceAudience;
59  import org.apache.hadoop.hbase.client.Append;
60  import org.apache.hadoop.hbase.client.Consistency;
61  import org.apache.hadoop.hbase.client.Delete;
62  import org.apache.hadoop.hbase.client.Durability;
63  import org.apache.hadoop.hbase.client.Get;
64  import org.apache.hadoop.hbase.client.Increment;
65  import org.apache.hadoop.hbase.client.Mutation;
66  import org.apache.hadoop.hbase.client.Put;
67  import org.apache.hadoop.hbase.client.Result;
68  import org.apache.hadoop.hbase.client.Scan;
69  import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
70  import org.apache.hadoop.hbase.client.security.SecurityCapability;
71  import org.apache.hadoop.hbase.exceptions.DeserializationException;
72  import org.apache.hadoop.hbase.filter.ByteArrayComparable;
73  import org.apache.hadoop.hbase.filter.Filter;
74  import org.apache.hadoop.hbase.io.LimitInputStream;
75  import org.apache.hadoop.hbase.io.TimeRange;
76  import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos;
77  import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.AccessControlService;
78  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.AdminService;
79  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionRequest;
80  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionResponse;
81  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetOnlineRegionRequest;
82  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetOnlineRegionResponse;
83  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoRequest;
84  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse;
85  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetServerInfoRequest;
86  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetServerInfoResponse;
87  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetStoreFileRequest;
88  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetStoreFileResponse;
89  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.MergeRegionsRequest;
90  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.OpenRegionRequest;
91  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.ServerInfo;
92  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.SplitRegionRequest;
93  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.WarmupRegionRequest;
94  import org.apache.hadoop.hbase.protobuf.generated.AuthenticationProtos;
95  import org.apache.hadoop.hbase.protobuf.generated.CellProtos;
96  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
97  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.BulkLoadHFileRequest;
98  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.BulkLoadHFileResponse;
99  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ClientService;
100 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.Column;
101 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceCall;
102 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceRequest;
103 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceResponse;
104 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetRequest;
105 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetResponse;
106 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto;
107 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.ColumnValue;
108 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.ColumnValue.QualifierValue;
109 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.DeleteType;
110 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.MutationType;
111 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.ScanRequest;
112 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos;
113 import org.apache.hadoop.hbase.protobuf.generated.ClusterStatusProtos.RegionLoad;
114 import org.apache.hadoop.hbase.protobuf.generated.ComparatorProtos;
115 import org.apache.hadoop.hbase.protobuf.generated.FilterProtos;
116 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
117 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.NameBytesPair;
118 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionInfo;
119 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier;
120 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier.RegionSpecifierType;
121 import org.apache.hadoop.hbase.protobuf.generated.MapReduceProtos;
122 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos;
123 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.CreateTableRequest;
124 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.GetTableDescriptorsResponse;
125 import org.apache.hadoop.hbase.protobuf.generated.MasterProtos.MasterService;
126 import org.apache.hadoop.hbase.protobuf.generated.QuotaProtos;
127 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionServerReportRequest;
128 import org.apache.hadoop.hbase.protobuf.generated.RegionServerStatusProtos.RegionServerStartupRequest;
129 import org.apache.hadoop.hbase.protobuf.generated.WALProtos;
130 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.CompactionDescriptor;
131 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.FlushDescriptor;
132 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.FlushDescriptor.FlushAction;
133 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.RegionEventDescriptor;
134 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.RegionEventDescriptor.EventType;
135 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.BulkLoadDescriptor;
136 import org.apache.hadoop.hbase.protobuf.generated.WALProtos.StoreDescriptor;
137 import org.apache.hadoop.hbase.quotas.QuotaScope;
138 import org.apache.hadoop.hbase.quotas.QuotaType;
139 import org.apache.hadoop.hbase.quotas.ThrottleType;
140 import org.apache.hadoop.hbase.replication.ReplicationLoadSink;
141 import org.apache.hadoop.hbase.replication.ReplicationLoadSource;
142 import org.apache.hadoop.hbase.security.User;
143 import org.apache.hadoop.hbase.security.access.Permission;
144 import org.apache.hadoop.hbase.security.access.TablePermission;
145 import org.apache.hadoop.hbase.security.access.UserPermission;
146 import org.apache.hadoop.hbase.security.token.AuthenticationTokenIdentifier;
147 import org.apache.hadoop.hbase.security.visibility.Authorizations;
148 import org.apache.hadoop.hbase.security.visibility.CellVisibility;
149 import org.apache.hadoop.hbase.util.ByteStringer;
150 import org.apache.hadoop.hbase.util.Bytes;
151 import org.apache.hadoop.hbase.util.DynamicClassLoader;
152 import org.apache.hadoop.hbase.util.ExceptionUtil;
153 import org.apache.hadoop.hbase.util.Methods;
154 import org.apache.hadoop.hbase.util.Pair;
155 import org.apache.hadoop.hbase.util.VersionInfo;
156 import org.apache.hadoop.io.Text;
157 import org.apache.hadoop.ipc.RemoteException;
158 import org.apache.hadoop.security.token.Token;
159 
160 import com.google.common.collect.ArrayListMultimap;
161 import com.google.common.collect.ListMultimap;
162 import com.google.common.collect.Lists;
163 import com.google.protobuf.ByteString;
164 import com.google.protobuf.CodedInputStream;
165 import com.google.protobuf.InvalidProtocolBufferException;
166 import com.google.protobuf.Message;
167 import com.google.protobuf.Parser;
168 import com.google.protobuf.RpcChannel;
169 import com.google.protobuf.RpcController;
170 import com.google.protobuf.Service;
171 import com.google.protobuf.ServiceException;
172 import com.google.protobuf.TextFormat;
173 
174 /**
175  * Protobufs utility.
176  */
177 @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="DP_CREATE_CLASSLOADER_INSIDE_DO_PRIVILEGED",
178   justification="None. Address sometime.")
179 @InterfaceAudience.Private // TODO: some clients (Hive, etc) use this class
180 public final class ProtobufUtil {
181 
182   private ProtobufUtil() {
183   }
184 
185   /**
186    * Primitive type to class mapping.
187    */
188   private final static Map<String, Class<?>>
189     PRIMITIVES = new HashMap<String, Class<?>>();
190 
191 
192   /**
193    * Many results are simple: no cell, exists true or false. To save on object creations,
194    *  we reuse them across calls.
195    */
196   private final static Cell[] EMPTY_CELL_ARRAY = new Cell[]{};
197   private final static Result EMPTY_RESULT = Result.create(EMPTY_CELL_ARRAY);
198   final static Result EMPTY_RESULT_EXISTS_TRUE = Result.create(null, true);
199   final static Result EMPTY_RESULT_EXISTS_FALSE = Result.create(null, false);
200   private final static Result EMPTY_RESULT_STALE = Result.create(EMPTY_CELL_ARRAY, null, true);
201   private final static Result EMPTY_RESULT_EXISTS_TRUE_STALE
202     = Result.create((Cell[])null, true, true);
203   private final static Result EMPTY_RESULT_EXISTS_FALSE_STALE
204     = Result.create((Cell[])null, false, true);
205 
206   private final static ClientProtos.Result EMPTY_RESULT_PB;
207   private final static ClientProtos.Result EMPTY_RESULT_PB_EXISTS_TRUE;
208   private final static ClientProtos.Result EMPTY_RESULT_PB_EXISTS_FALSE;
209   private final static ClientProtos.Result EMPTY_RESULT_PB_STALE;
210   private final static ClientProtos.Result EMPTY_RESULT_PB_EXISTS_TRUE_STALE;
211   private final static ClientProtos.Result EMPTY_RESULT_PB_EXISTS_FALSE_STALE;
212 
213 
214   static {
215     ClientProtos.Result.Builder builder = ClientProtos.Result.newBuilder();
216 
217     builder.setExists(true);
218     builder.setAssociatedCellCount(0);
219     EMPTY_RESULT_PB_EXISTS_TRUE =  builder.build();
220 
221     builder.setStale(true);
222     EMPTY_RESULT_PB_EXISTS_TRUE_STALE = builder.build();
223     builder.clear();
224 
225     builder.setExists(false);
226     builder.setAssociatedCellCount(0);
227     EMPTY_RESULT_PB_EXISTS_FALSE =  builder.build();
228     builder.setStale(true);
229     EMPTY_RESULT_PB_EXISTS_FALSE_STALE = builder.build();
230 
231     builder.clear();
232     builder.setAssociatedCellCount(0);
233     EMPTY_RESULT_PB =  builder.build();
234     builder.setStale(true);
235     EMPTY_RESULT_PB_STALE = builder.build();
236   }
237 
238   /**
239    * Dynamic class loader to load filter/comparators
240    */
241   private final static ClassLoader CLASS_LOADER;
242 
243   static {
244     ClassLoader parent = ProtobufUtil.class.getClassLoader();
245     Configuration conf = HBaseConfiguration.create();
246     CLASS_LOADER = new DynamicClassLoader(conf, parent);
247 
248     PRIMITIVES.put(Boolean.TYPE.getName(), Boolean.TYPE);
249     PRIMITIVES.put(Byte.TYPE.getName(), Byte.TYPE);
250     PRIMITIVES.put(Character.TYPE.getName(), Character.TYPE);
251     PRIMITIVES.put(Short.TYPE.getName(), Short.TYPE);
252     PRIMITIVES.put(Integer.TYPE.getName(), Integer.TYPE);
253     PRIMITIVES.put(Long.TYPE.getName(), Long.TYPE);
254     PRIMITIVES.put(Float.TYPE.getName(), Float.TYPE);
255     PRIMITIVES.put(Double.TYPE.getName(), Double.TYPE);
256     PRIMITIVES.put(Void.TYPE.getName(), Void.TYPE);
257   }
258 
259   /**
260    * Magic we put ahead of a serialized protobuf message.
261    * For example, all znode content is protobuf messages with the below magic
262    * for preamble.
263    */
264   public static final byte [] PB_MAGIC = new byte [] {'P', 'B', 'U', 'F'};
265   private static final String PB_MAGIC_STR = Bytes.toString(PB_MAGIC);
266 
267   /**
268    * Prepend the passed bytes with four bytes of magic, {@link #PB_MAGIC}, to flag what
269    * follows as a protobuf in hbase.  Prepend these bytes to all content written to znodes, etc.
270    * @param bytes Bytes to decorate
271    * @return The passed <code>bytes</code> with magic prepended (Creates a new
272    * byte array that is <code>bytes.length</code> plus {@link #PB_MAGIC}.length.
273    */
274   public static byte [] prependPBMagic(final byte [] bytes) {
275     return Bytes.add(PB_MAGIC, bytes);
276   }
277 
278   /**
279    * @param bytes Bytes to check.
280    * @return True if passed <code>bytes</code> has {@link #PB_MAGIC} for a prefix.
281    */
282   public static boolean isPBMagicPrefix(final byte [] bytes) {
283     if (bytes == null) return false;
284     return isPBMagicPrefix(bytes, 0, bytes.length);
285   }
286 
287   /**
288    * @param bytes Bytes to check.
289    * @param offset offset to start at
290    * @param len length to use
291    * @return True if passed <code>bytes</code> has {@link #PB_MAGIC} for a prefix.
292    */
293   public static boolean isPBMagicPrefix(final byte [] bytes, int offset, int len) {
294     if (bytes == null || len < PB_MAGIC.length) return false;
295     return Bytes.compareTo(PB_MAGIC, 0, PB_MAGIC.length, bytes, offset, PB_MAGIC.length) == 0;
296   }
297 
298   /**
299    * @param bytes bytes to check
300    * @throws DeserializationException if we are missing the pb magic prefix
301    */
302   public static void expectPBMagicPrefix(final byte [] bytes) throws DeserializationException {
303     if (!isPBMagicPrefix(bytes)) {
304       throw new DeserializationException("Missing pb magic " + PB_MAGIC_STR + " prefix");
305     }
306   }
307 
308   /**
309    * @return Length of {@link #PB_MAGIC}
310    */
311   public static int lengthOfPBMagic() {
312     return PB_MAGIC.length;
313   }
314 
315   /**
316    * Return the IOException thrown by the remote server wrapped in
317    * ServiceException as cause.
318    *
319    * @param se ServiceException that wraps IO exception thrown by the server
320    * @return Exception wrapped in ServiceException or
321    *   a new IOException that wraps the unexpected ServiceException.
322    */
323   public static IOException getRemoteException(ServiceException se) {
324     Throwable e = se.getCause();
325     if (e == null) {
326       return new IOException(se);
327     }
328     if (ExceptionUtil.isInterrupt(e)) {
329       return ExceptionUtil.asInterrupt(e);
330     }
331     if (e instanceof RemoteException) {
332       e = ((RemoteException) e).unwrapRemoteException();
333     }
334     return e instanceof IOException ? (IOException) e : new IOException(se);
335   }
336 
337   /**
338    * Convert a ServerName to a protocol buffer ServerName
339    *
340    * @param serverName the ServerName to convert
341    * @return the converted protocol buffer ServerName
342    * @see #toServerName(org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.ServerName)
343    */
344   public static HBaseProtos.ServerName
345       toServerName(final ServerName serverName) {
346     if (serverName == null) return null;
347     HBaseProtos.ServerName.Builder builder =
348       HBaseProtos.ServerName.newBuilder();
349     builder.setHostName(serverName.getHostname());
350     if (serverName.getPort() >= 0) {
351       builder.setPort(serverName.getPort());
352     }
353     if (serverName.getStartcode() >= 0) {
354       builder.setStartCode(serverName.getStartcode());
355     }
356     return builder.build();
357   }
358 
359   /**
360    * Convert a protocol buffer ServerName to a ServerName
361    *
362    * @param proto the protocol buffer ServerName to convert
363    * @return the converted ServerName
364    */
365   public static ServerName toServerName(final HBaseProtos.ServerName proto) {
366     if (proto == null) return null;
367     String hostName = proto.getHostName();
368     long startCode = -1;
369     int port = -1;
370     if (proto.hasPort()) {
371       port = proto.getPort();
372     }
373     if (proto.hasStartCode()) {
374       startCode = proto.getStartCode();
375     }
376     return ServerName.valueOf(hostName, port, startCode);
377   }
378 
379   /**
380    * Get HTableDescriptor[] from GetTableDescriptorsResponse protobuf
381    *
382    * @param proto the GetTableDescriptorsResponse
383    * @return HTableDescriptor[]
384    */
385   public static HTableDescriptor[] getHTableDescriptorArray(GetTableDescriptorsResponse proto) {
386     if (proto == null) return null;
387 
388     HTableDescriptor[] ret = new HTableDescriptor[proto.getTableSchemaCount()];
389     for (int i = 0; i < proto.getTableSchemaCount(); ++i) {
390       ret[i] = HTableDescriptor.convert(proto.getTableSchema(i));
391     }
392     return ret;
393   }
394 
395   /**
396    * get the split keys in form "byte [][]" from a CreateTableRequest proto
397    *
398    * @param proto the CreateTableRequest
399    * @return the split keys
400    */
401   public static byte [][] getSplitKeysArray(final CreateTableRequest proto) {
402     byte [][] splitKeys = new byte[proto.getSplitKeysCount()][];
403     for (int i = 0; i < proto.getSplitKeysCount(); ++i) {
404       splitKeys[i] = proto.getSplitKeys(i).toByteArray();
405     }
406     return splitKeys;
407   }
408 
409   /**
410    * Convert a protobuf Durability into a client Durability
411    */
412   public static Durability toDurability(
413       final ClientProtos.MutationProto.Durability proto) {
414     switch(proto) {
415     case USE_DEFAULT:
416       return Durability.USE_DEFAULT;
417     case SKIP_WAL:
418       return Durability.SKIP_WAL;
419     case ASYNC_WAL:
420       return Durability.ASYNC_WAL;
421     case SYNC_WAL:
422       return Durability.SYNC_WAL;
423     case FSYNC_WAL:
424       return Durability.FSYNC_WAL;
425     default:
426       return Durability.USE_DEFAULT;
427     }
428   }
429 
430   /**
431    * Convert a client Durability into a protbuf Durability
432    */
433   public static ClientProtos.MutationProto.Durability toDurability(
434       final Durability d) {
435     switch(d) {
436     case USE_DEFAULT:
437       return ClientProtos.MutationProto.Durability.USE_DEFAULT;
438     case SKIP_WAL:
439       return ClientProtos.MutationProto.Durability.SKIP_WAL;
440     case ASYNC_WAL:
441       return ClientProtos.MutationProto.Durability.ASYNC_WAL;
442     case SYNC_WAL:
443       return ClientProtos.MutationProto.Durability.SYNC_WAL;
444     case FSYNC_WAL:
445       return ClientProtos.MutationProto.Durability.FSYNC_WAL;
446     default:
447       return ClientProtos.MutationProto.Durability.USE_DEFAULT;
448     }
449   }
450 
451   /**
452    * Convert a protocol buffer Get to a client Get
453    *
454    * @param proto the protocol buffer Get to convert
455    * @return the converted client Get
456    * @throws IOException
457    */
458   public static Get toGet(
459       final ClientProtos.Get proto) throws IOException {
460     if (proto == null) return null;
461     byte[] row = proto.getRow().toByteArray();
462     Get get = new Get(row);
463     if (proto.hasCacheBlocks()) {
464       get.setCacheBlocks(proto.getCacheBlocks());
465     }
466     if (proto.hasMaxVersions()) {
467       get.setMaxVersions(proto.getMaxVersions());
468     }
469     if (proto.hasStoreLimit()) {
470       get.setMaxResultsPerColumnFamily(proto.getStoreLimit());
471     }
472     if (proto.hasStoreOffset()) {
473       get.setRowOffsetPerColumnFamily(proto.getStoreOffset());
474     }
475     if (proto.getCfTimeRangeCount() > 0) {
476       for (HBaseProtos.ColumnFamilyTimeRange cftr : proto.getCfTimeRangeList()) {
477         TimeRange timeRange = protoToTimeRange(cftr.getTimeRange());
478         get.setColumnFamilyTimeRange(cftr.getColumnFamily().toByteArray(),
479             timeRange.getMin(), timeRange.getMax());
480       }
481     }
482     if (proto.hasTimeRange()) {
483       TimeRange timeRange = protoToTimeRange(proto.getTimeRange());
484       get.setTimeRange(timeRange.getMin(), timeRange.getMax());
485     }
486     if (proto.hasFilter()) {
487       FilterProtos.Filter filter = proto.getFilter();
488       get.setFilter(ProtobufUtil.toFilter(filter));
489     }
490     for (NameBytesPair attribute: proto.getAttributeList()) {
491       get.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
492     }
493     if (proto.getColumnCount() > 0) {
494       for (Column column: proto.getColumnList()) {
495         byte[] family = column.getFamily().toByteArray();
496         if (column.getQualifierCount() > 0) {
497           for (ByteString qualifier: column.getQualifierList()) {
498             get.addColumn(family, qualifier.toByteArray());
499           }
500         } else {
501           get.addFamily(family);
502         }
503       }
504     }
505     if (proto.hasExistenceOnly() && proto.getExistenceOnly()){
506       get.setCheckExistenceOnly(true);
507     }
508     if (proto.hasClosestRowBefore() && proto.getClosestRowBefore()){
509       get.setClosestRowBefore(true);
510     }
511     if (proto.hasConsistency()) {
512       get.setConsistency(toConsistency(proto.getConsistency()));
513     }
514     return get;
515   }
516 
517   public static Consistency toConsistency(ClientProtos.Consistency consistency) {
518     switch (consistency) {
519       case STRONG : return Consistency.STRONG;
520       case TIMELINE : return Consistency.TIMELINE;
521       default : return Consistency.STRONG;
522     }
523   }
524 
525   public static ClientProtos.Consistency toConsistency(Consistency consistency) {
526     switch (consistency) {
527       case STRONG : return ClientProtos.Consistency.STRONG;
528       case TIMELINE : return ClientProtos.Consistency.TIMELINE;
529       default : return ClientProtos.Consistency.STRONG;
530     }
531   }
532 
533   /**
534    * Convert a protocol buffer Mutate to a Put.
535    *
536    * @param proto The protocol buffer MutationProto to convert
537    * @return A client Put.
538    * @throws IOException
539    */
540   public static Put toPut(final MutationProto proto)
541   throws IOException {
542     return toPut(proto, null);
543   }
544 
545   /**
546    * Convert a protocol buffer Mutate to a Put.
547    *
548    * @param proto The protocol buffer MutationProto to convert
549    * @param cellScanner If non-null, the Cell data that goes with this proto.
550    * @return A client Put.
551    * @throws IOException
552    */
553   public static Put toPut(final MutationProto proto, final CellScanner cellScanner)
554   throws IOException {
555     // TODO: Server-side at least why do we convert back to the Client types?  Why not just pb it?
556     MutationType type = proto.getMutateType();
557     assert type == MutationType.PUT: type.name();
558     long timestamp = proto.hasTimestamp()? proto.getTimestamp(): HConstants.LATEST_TIMESTAMP;
559     Put put = proto.hasRow() ? new Put(proto.getRow().toByteArray(), timestamp) : null;
560     int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
561     if (cellCount > 0) {
562       // The proto has metadata only and the data is separate to be found in the cellScanner.
563       if (cellScanner == null) {
564         throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
565             toShortString(proto));
566       }
567       for (int i = 0; i < cellCount; i++) {
568         if (!cellScanner.advance()) {
569           throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
570             " no cell returned: " + toShortString(proto));
571         }
572         Cell cell = cellScanner.current();
573         if (put == null) {
574           put = new Put(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), timestamp);
575         }
576         put.add(cell);
577       }
578     } else {
579       if (put == null) {
580         throw new IllegalArgumentException("row cannot be null");
581       }
582       // The proto has the metadata and the data itself
583       for (ColumnValue column: proto.getColumnValueList()) {
584         byte[] family = column.getFamily().toByteArray();
585         for (QualifierValue qv: column.getQualifierValueList()) {
586           if (!qv.hasValue()) {
587             throw new DoNotRetryIOException(
588                 "Missing required field: qualifier value");
589           }
590           ByteBuffer qualifier =
591               qv.hasQualifier() ? qv.getQualifier().asReadOnlyByteBuffer() : null;
592           ByteBuffer value =
593               qv.hasValue() ? qv.getValue().asReadOnlyByteBuffer() : null;
594           long ts = timestamp;
595           if (qv.hasTimestamp()) {
596             ts = qv.getTimestamp();
597           }
598           byte[] tags;
599           if (qv.hasTags()) {
600             tags = qv.getTags().toByteArray();
601             Object[] array = Tag.asList(tags, 0, (short)tags.length).toArray();
602             Tag[] tagArray = new Tag[array.length];
603             for(int i = 0; i< array.length; i++) {
604               tagArray[i] = (Tag)array[i];
605             }
606             if(qv.hasDeleteType()) {
607               byte[] qual = qv.hasQualifier() ? qv.getQualifier().toByteArray() : null;
608               put.add(new KeyValue(proto.getRow().toByteArray(), family, qual, ts,
609                   fromDeleteType(qv.getDeleteType()), null, tags));
610             } else {
611               put.addImmutable(family, qualifier, ts, value, tagArray);
612             }
613           } else {
614             if(qv.hasDeleteType()) {
615               byte[] qual = qv.hasQualifier() ? qv.getQualifier().toByteArray() : null;
616               put.add(new KeyValue(proto.getRow().toByteArray(), family, qual, ts,
617                   fromDeleteType(qv.getDeleteType())));
618             } else{
619               put.addImmutable(family, qualifier, ts, value);
620             }
621           }
622         }
623       }
624     }
625     put.setDurability(toDurability(proto.getDurability()));
626     for (NameBytesPair attribute: proto.getAttributeList()) {
627       put.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
628     }
629     return put;
630   }
631 
632   /**
633    * Convert a protocol buffer Mutate to a Delete
634    *
635    * @param proto the protocol buffer Mutate to convert
636    * @return the converted client Delete
637    * @throws IOException
638    */
639   public static Delete toDelete(final MutationProto proto)
640   throws IOException {
641     return toDelete(proto, null);
642   }
643 
644   /**
645    * Convert a protocol buffer Mutate to a Delete
646    *
647    * @param proto the protocol buffer Mutate to convert
648    * @param cellScanner if non-null, the data that goes with this delete.
649    * @return the converted client Delete
650    * @throws IOException
651    */
652   public static Delete toDelete(final MutationProto proto, final CellScanner cellScanner)
653   throws IOException {
654     MutationType type = proto.getMutateType();
655     assert type == MutationType.DELETE : type.name();
656     long timestamp = proto.hasTimestamp() ? proto.getTimestamp() : HConstants.LATEST_TIMESTAMP;
657     Delete delete = proto.hasRow() ? new Delete(proto.getRow().toByteArray(), timestamp) : null;
658     int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
659     if (cellCount > 0) {
660       // The proto has metadata only and the data is separate to be found in the cellScanner.
661       if (cellScanner == null) {
662         // TextFormat should be fine for a Delete since it carries no data, just coordinates.
663         throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
664           TextFormat.shortDebugString(proto));
665       }
666       for (int i = 0; i < cellCount; i++) {
667         if (!cellScanner.advance()) {
668           // TextFormat should be fine for a Delete since it carries no data, just coordinates.
669           throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
670             " no cell returned: " + TextFormat.shortDebugString(proto));
671         }
672         Cell cell = cellScanner.current();
673         if (delete == null) {
674           delete =
675             new Delete(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), timestamp);
676         }
677         delete.addDeleteMarker(cell);
678       }
679     } else {
680       if (delete == null) {
681         throw new IllegalArgumentException("row cannot be null");
682       }
683       for (ColumnValue column: proto.getColumnValueList()) {
684         byte[] family = column.getFamily().toByteArray();
685         for (QualifierValue qv: column.getQualifierValueList()) {
686           DeleteType deleteType = qv.getDeleteType();
687           byte[] qualifier = null;
688           if (qv.hasQualifier()) {
689             qualifier = qv.getQualifier().toByteArray();
690           }
691           long ts = HConstants.LATEST_TIMESTAMP;
692           if (qv.hasTimestamp()) {
693             ts = qv.getTimestamp();
694           }
695           if (deleteType == DeleteType.DELETE_ONE_VERSION) {
696             delete.deleteColumn(family, qualifier, ts);
697           } else if (deleteType == DeleteType.DELETE_MULTIPLE_VERSIONS) {
698             delete.deleteColumns(family, qualifier, ts);
699           } else if (deleteType == DeleteType.DELETE_FAMILY_VERSION) {
700             delete.deleteFamilyVersion(family, ts);
701           } else {
702             delete.deleteFamily(family, ts);
703           }
704         }
705       }
706     }
707     delete.setDurability(toDurability(proto.getDurability()));
708     for (NameBytesPair attribute: proto.getAttributeList()) {
709       delete.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
710     }
711     return delete;
712   }
713 
714   /**
715    * Convert a protocol buffer Mutate to an Append
716    * @param cellScanner
717    * @param proto the protocol buffer Mutate to convert
718    * @return the converted client Append
719    * @throws IOException
720    */
721   public static Append toAppend(final MutationProto proto, final CellScanner cellScanner)
722   throws IOException {
723     MutationType type = proto.getMutateType();
724     assert type == MutationType.APPEND : type.name();
725     byte [] row = proto.hasRow()? proto.getRow().toByteArray(): null;
726     Append append = null;
727     int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
728     if (cellCount > 0) {
729       // The proto has metadata only and the data is separate to be found in the cellScanner.
730       if (cellScanner == null) {
731         throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
732           toShortString(proto));
733       }
734       for (int i = 0; i < cellCount; i++) {
735         if (!cellScanner.advance()) {
736           throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
737             " no cell returned: " + toShortString(proto));
738         }
739         Cell cell = cellScanner.current();
740         if (append == null) {
741           append = new Append(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
742         }
743         append.add(cell);
744       }
745     } else {
746       append = new Append(row);
747       for (ColumnValue column: proto.getColumnValueList()) {
748         byte[] family = column.getFamily().toByteArray();
749         for (QualifierValue qv: column.getQualifierValueList()) {
750           byte[] qualifier = qv.getQualifier().toByteArray();
751           if (!qv.hasValue()) {
752             throw new DoNotRetryIOException(
753               "Missing required field: qualifier value");
754           }
755           byte[] value = qv.getValue().toByteArray();
756           byte[] tags = null;
757           if (qv.hasTags()) {
758             tags = qv.getTags().toByteArray();
759           }
760           append.add(CellUtil.createCell(row, family, qualifier, qv.getTimestamp(),
761               KeyValue.Type.Put, value, tags));
762         }
763       }
764     }
765     append.setDurability(toDurability(proto.getDurability()));
766     for (NameBytesPair attribute: proto.getAttributeList()) {
767       append.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
768     }
769     return append;
770   }
771 
772   /**
773    * Convert a MutateRequest to Mutation
774    *
775    * @param proto the protocol buffer Mutate to convert
776    * @return the converted Mutation
777    * @throws IOException
778    */
779   public static Mutation toMutation(final MutationProto proto) throws IOException {
780     MutationType type = proto.getMutateType();
781     if (type == MutationType.APPEND) {
782       return toAppend(proto, null);
783     }
784     if (type == MutationType.DELETE) {
785       return toDelete(proto, null);
786     }
787     if (type == MutationType.PUT) {
788       return toPut(proto, null);
789     }
790     throw new IOException("Unknown mutation type " + type);
791   }
792 
793   /**
794    * Convert a protocol buffer Mutate to an Increment
795    *
796    * @param proto the protocol buffer Mutate to convert
797    * @return the converted client Increment
798    * @throws IOException
799    */
800   public static Increment toIncrement(final MutationProto proto, final CellScanner cellScanner)
801   throws IOException {
802     MutationType type = proto.getMutateType();
803     assert type == MutationType.INCREMENT : type.name();
804     byte [] row = proto.hasRow()? proto.getRow().toByteArray(): null;
805     Increment increment = null;
806     int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
807     if (cellCount > 0) {
808       // The proto has metadata only and the data is separate to be found in the cellScanner.
809       if (cellScanner == null) {
810         throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
811           TextFormat.shortDebugString(proto));
812       }
813       for (int i = 0; i < cellCount; i++) {
814         if (!cellScanner.advance()) {
815           throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
816             " no cell returned: " + TextFormat.shortDebugString(proto));
817         }
818         Cell cell = cellScanner.current();
819         if (increment == null) {
820           increment = new Increment(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
821         }
822         increment.add(cell);
823       }
824     } else {
825       increment = new Increment(row);
826       for (ColumnValue column: proto.getColumnValueList()) {
827         byte[] family = column.getFamily().toByteArray();
828         for (QualifierValue qv: column.getQualifierValueList()) {
829           byte[] qualifier = qv.getQualifier().toByteArray();
830           if (!qv.hasValue()) {
831             throw new DoNotRetryIOException("Missing required field: qualifier value");
832           }
833           byte[] value = qv.getValue().toByteArray();
834           byte[] tags = null;
835           if (qv.hasTags()) {
836             tags = qv.getTags().toByteArray();
837           }
838           increment.add(CellUtil.createCell(row, family, qualifier, qv.getTimestamp(),
839               KeyValue.Type.Put, value, tags));
840         }
841       }
842     }
843     if (proto.hasTimeRange()) {
844       TimeRange timeRange = protoToTimeRange(proto.getTimeRange());
845       increment.setTimeRange(timeRange.getMin(), timeRange.getMax());
846     }
847     increment.setDurability(toDurability(proto.getDurability()));
848     for (NameBytesPair attribute : proto.getAttributeList()) {
849       increment.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
850     }
851     return increment;
852   }
853 
854   /**
855    * Convert a protocol buffer Mutate to a Get.
856    * @param proto the protocol buffer Mutate to convert.
857    * @param cellScanner
858    * @return the converted client get.
859    * @throws IOException
860    */
861   public static Get toGet(final MutationProto proto, final CellScanner cellScanner)
862       throws IOException {
863     MutationType type = proto.getMutateType();
864     assert type == MutationType.INCREMENT || type == MutationType.APPEND : type.name();
865     byte[] row = proto.hasRow() ? proto.getRow().toByteArray() : null;
866     Get get = null;
867     int cellCount = proto.hasAssociatedCellCount() ? proto.getAssociatedCellCount() : 0;
868     if (cellCount > 0) {
869       // The proto has metadata only and the data is separate to be found in the cellScanner.
870       if (cellScanner == null) {
871         throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: "
872             + TextFormat.shortDebugString(proto));
873       }
874       for (int i = 0; i < cellCount; i++) {
875         if (!cellScanner.advance()) {
876           throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i
877               + " no cell returned: " + TextFormat.shortDebugString(proto));
878         }
879         Cell cell = cellScanner.current();
880         if (get == null) {
881           get = new Get(Bytes.copy(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength()));
882         }
883         get.addColumn(Bytes.copy(cell.getFamilyArray(), cell.getFamilyOffset(),
884           cell.getFamilyLength()), Bytes.copy(cell.getQualifierArray(), cell.getQualifierOffset(),
885           cell.getQualifierLength()));
886       }
887     } else {
888       get = new Get(row);
889       for (ColumnValue column : proto.getColumnValueList()) {
890         byte[] family = column.getFamily().toByteArray();
891         for (QualifierValue qv : column.getQualifierValueList()) {
892           byte[] qualifier = qv.getQualifier().toByteArray();
893           if (!qv.hasValue()) {
894             throw new DoNotRetryIOException("Missing required field: qualifier value");
895           }
896           get.addColumn(family, qualifier);
897         }
898       }
899     }
900     if (proto.hasTimeRange()) {
901       TimeRange timeRange = protoToTimeRange(proto.getTimeRange());
902       get.setTimeRange(timeRange.getMin(), timeRange.getMax());
903     }
904     for (NameBytesPair attribute : proto.getAttributeList()) {
905       get.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
906     }
907     return get;
908   }
909 
910   /**
911    * Convert a client Scan to a protocol buffer Scan
912    *
913    * @param scan the client Scan to convert
914    * @return the converted protocol buffer Scan
915    * @throws IOException
916    */
917   public static ClientProtos.Scan toScan(
918       final Scan scan) throws IOException {
919     ClientProtos.Scan.Builder scanBuilder =
920       ClientProtos.Scan.newBuilder();
921     scanBuilder.setCacheBlocks(scan.getCacheBlocks());
922     if (scan.getBatch() > 0) {
923       scanBuilder.setBatchSize(scan.getBatch());
924     }
925     if (scan.getMaxResultSize() > 0) {
926       scanBuilder.setMaxResultSize(scan.getMaxResultSize());
927     }
928     if (scan.isSmall()) {
929       scanBuilder.setSmall(scan.isSmall());
930     }
931     if (scan.getAllowPartialResults()) {
932       scanBuilder.setAllowPartialResults(scan.getAllowPartialResults());
933     }
934     Boolean loadColumnFamiliesOnDemand = scan.getLoadColumnFamiliesOnDemandValue();
935     if (loadColumnFamiliesOnDemand != null) {
936       scanBuilder.setLoadColumnFamiliesOnDemand(loadColumnFamiliesOnDemand.booleanValue());
937     }
938     scanBuilder.setMaxVersions(scan.getMaxVersions());
939     for (Entry<byte[], TimeRange> cftr : scan.getColumnFamilyTimeRange().entrySet()) {
940       HBaseProtos.ColumnFamilyTimeRange.Builder b = HBaseProtos.ColumnFamilyTimeRange.newBuilder();
941       b.setColumnFamily(ByteString.copyFrom(cftr.getKey()));
942       b.setTimeRange(timeRangeToProto(cftr.getValue()));
943       scanBuilder.addCfTimeRange(b);
944     }
945     TimeRange timeRange = scan.getTimeRange();
946     if (!timeRange.isAllTime()) {
947       HBaseProtos.TimeRange.Builder timeRangeBuilder =
948         HBaseProtos.TimeRange.newBuilder();
949       timeRangeBuilder.setFrom(timeRange.getMin());
950       timeRangeBuilder.setTo(timeRange.getMax());
951       scanBuilder.setTimeRange(timeRangeBuilder.build());
952     }
953     Map<String, byte[]> attributes = scan.getAttributesMap();
954     if (!attributes.isEmpty()) {
955       NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
956       for (Map.Entry<String, byte[]> attribute: attributes.entrySet()) {
957         attributeBuilder.setName(attribute.getKey());
958         attributeBuilder.setValue(ByteStringer.wrap(attribute.getValue()));
959         scanBuilder.addAttribute(attributeBuilder.build());
960       }
961     }
962     byte[] startRow = scan.getStartRow();
963     if (startRow != null && startRow.length > 0) {
964       scanBuilder.setStartRow(ByteStringer.wrap(startRow));
965     }
966     byte[] stopRow = scan.getStopRow();
967     if (stopRow != null && stopRow.length > 0) {
968       scanBuilder.setStopRow(ByteStringer.wrap(stopRow));
969     }
970     if (scan.hasFilter()) {
971       scanBuilder.setFilter(ProtobufUtil.toFilter(scan.getFilter()));
972     }
973     if (scan.hasFamilies()) {
974       Column.Builder columnBuilder = Column.newBuilder();
975       for (Map.Entry<byte[],NavigableSet<byte []>>
976           family: scan.getFamilyMap().entrySet()) {
977         columnBuilder.setFamily(ByteStringer.wrap(family.getKey()));
978         NavigableSet<byte []> qualifiers = family.getValue();
979         columnBuilder.clearQualifier();
980         if (qualifiers != null && qualifiers.size() > 0) {
981           for (byte [] qualifier: qualifiers) {
982             columnBuilder.addQualifier(ByteStringer.wrap(qualifier));
983           }
984         }
985         scanBuilder.addColumn(columnBuilder.build());
986       }
987     }
988     if (scan.getMaxResultsPerColumnFamily() >= 0) {
989       scanBuilder.setStoreLimit(scan.getMaxResultsPerColumnFamily());
990     }
991     if (scan.getRowOffsetPerColumnFamily() > 0) {
992       scanBuilder.setStoreOffset(scan.getRowOffsetPerColumnFamily());
993     }
994     if (scan.isReversed()) {
995       scanBuilder.setReversed(scan.isReversed());
996     }
997     if (scan.getConsistency() == Consistency.TIMELINE) {
998       scanBuilder.setConsistency(toConsistency(scan.getConsistency()));
999     }
1000     if (scan.getCaching() > 0) {
1001       scanBuilder.setCaching(scan.getCaching());
1002     }
1003     return scanBuilder.build();
1004   }
1005 
1006   /**
1007    * Convert a protocol buffer Scan to a client Scan
1008    *
1009    * @param proto the protocol buffer Scan to convert
1010    * @return the converted client Scan
1011    * @throws IOException
1012    */
1013   public static Scan toScan(
1014       final ClientProtos.Scan proto) throws IOException {
1015     byte [] startRow = HConstants.EMPTY_START_ROW;
1016     byte [] stopRow  = HConstants.EMPTY_END_ROW;
1017     if (proto.hasStartRow()) {
1018       startRow = proto.getStartRow().toByteArray();
1019     }
1020     if (proto.hasStopRow()) {
1021       stopRow = proto.getStopRow().toByteArray();
1022     }
1023     Scan scan = new Scan(startRow, stopRow);
1024     if (proto.hasCacheBlocks()) {
1025       scan.setCacheBlocks(proto.getCacheBlocks());
1026     }
1027     if (proto.hasMaxVersions()) {
1028       scan.setMaxVersions(proto.getMaxVersions());
1029     }
1030     if (proto.hasStoreLimit()) {
1031       scan.setMaxResultsPerColumnFamily(proto.getStoreLimit());
1032     }
1033     if (proto.hasStoreOffset()) {
1034       scan.setRowOffsetPerColumnFamily(proto.getStoreOffset());
1035     }
1036     if (proto.hasLoadColumnFamiliesOnDemand()) {
1037       scan.setLoadColumnFamiliesOnDemand(proto.getLoadColumnFamiliesOnDemand());
1038     }
1039     if (proto.getCfTimeRangeCount() > 0) {
1040       for (HBaseProtos.ColumnFamilyTimeRange cftr : proto.getCfTimeRangeList()) {
1041         TimeRange timeRange = protoToTimeRange(cftr.getTimeRange());
1042         scan.setColumnFamilyTimeRange(cftr.getColumnFamily().toByteArray(),
1043             timeRange.getMin(), timeRange.getMax());
1044       }
1045     }
1046     if (proto.hasTimeRange()) {
1047       TimeRange timeRange = protoToTimeRange(proto.getTimeRange());
1048       scan.setTimeRange(timeRange.getMin(), timeRange.getMax());
1049     }
1050     if (proto.hasFilter()) {
1051       FilterProtos.Filter filter = proto.getFilter();
1052       scan.setFilter(ProtobufUtil.toFilter(filter));
1053     }
1054     if (proto.hasBatchSize()) {
1055       scan.setBatch(proto.getBatchSize());
1056     }
1057     if (proto.hasMaxResultSize()) {
1058       scan.setMaxResultSize(proto.getMaxResultSize());
1059     }
1060     if (proto.hasSmall()) {
1061       scan.setSmall(proto.getSmall());
1062     }
1063     if (proto.hasAllowPartialResults()) {
1064       scan.setAllowPartialResults(proto.getAllowPartialResults());
1065     }
1066     for (NameBytesPair attribute: proto.getAttributeList()) {
1067       scan.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
1068     }
1069     if (proto.getColumnCount() > 0) {
1070       for (Column column: proto.getColumnList()) {
1071         byte[] family = column.getFamily().toByteArray();
1072         if (column.getQualifierCount() > 0) {
1073           for (ByteString qualifier: column.getQualifierList()) {
1074             scan.addColumn(family, qualifier.toByteArray());
1075           }
1076         } else {
1077           scan.addFamily(family);
1078         }
1079       }
1080     }
1081     if (proto.hasReversed()) {
1082       scan.setReversed(proto.getReversed());
1083     }
1084     if (proto.hasConsistency()) {
1085       scan.setConsistency(toConsistency(proto.getConsistency()));
1086     }
1087     if (proto.hasCaching()) {
1088       scan.setCaching(proto.getCaching());
1089     }
1090     return scan;
1091   }
1092 
1093   /**
1094    * Create a protocol buffer Get based on a client Get.
1095    *
1096    * @param get the client Get
1097    * @return a protocol buffer Get
1098    * @throws IOException
1099    */
1100   public static ClientProtos.Get toGet(
1101       final Get get) throws IOException {
1102     ClientProtos.Get.Builder builder =
1103       ClientProtos.Get.newBuilder();
1104     builder.setRow(ByteStringer.wrap(get.getRow()));
1105     builder.setCacheBlocks(get.getCacheBlocks());
1106     builder.setMaxVersions(get.getMaxVersions());
1107     if (get.getFilter() != null) {
1108       builder.setFilter(ProtobufUtil.toFilter(get.getFilter()));
1109     }
1110     for (Entry<byte[], TimeRange> cftr : get.getColumnFamilyTimeRange().entrySet()) {
1111       HBaseProtos.ColumnFamilyTimeRange.Builder b = HBaseProtos.ColumnFamilyTimeRange.newBuilder();
1112       b.setColumnFamily(ByteString.copyFrom(cftr.getKey()));
1113       b.setTimeRange(timeRangeToProto(cftr.getValue()));
1114       builder.addCfTimeRange(b);
1115     }
1116     TimeRange timeRange = get.getTimeRange();
1117     if (!timeRange.isAllTime()) {
1118       HBaseProtos.TimeRange.Builder timeRangeBuilder =
1119         HBaseProtos.TimeRange.newBuilder();
1120       timeRangeBuilder.setFrom(timeRange.getMin());
1121       timeRangeBuilder.setTo(timeRange.getMax());
1122       builder.setTimeRange(timeRangeBuilder.build());
1123     }
1124     Map<String, byte[]> attributes = get.getAttributesMap();
1125     if (!attributes.isEmpty()) {
1126       NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
1127       for (Map.Entry<String, byte[]> attribute: attributes.entrySet()) {
1128         attributeBuilder.setName(attribute.getKey());
1129         attributeBuilder.setValue(ByteStringer.wrap(attribute.getValue()));
1130         builder.addAttribute(attributeBuilder.build());
1131       }
1132     }
1133     if (get.hasFamilies()) {
1134       Column.Builder columnBuilder = Column.newBuilder();
1135       Map<byte[], NavigableSet<byte[]>> families = get.getFamilyMap();
1136       for (Map.Entry<byte[], NavigableSet<byte[]>> family: families.entrySet()) {
1137         NavigableSet<byte[]> qualifiers = family.getValue();
1138         columnBuilder.setFamily(ByteStringer.wrap(family.getKey()));
1139         columnBuilder.clearQualifier();
1140         if (qualifiers != null && qualifiers.size() > 0) {
1141           for (byte[] qualifier: qualifiers) {
1142             columnBuilder.addQualifier(ByteStringer.wrap(qualifier));
1143           }
1144         }
1145         builder.addColumn(columnBuilder.build());
1146       }
1147     }
1148     if (get.getMaxResultsPerColumnFamily() >= 0) {
1149       builder.setStoreLimit(get.getMaxResultsPerColumnFamily());
1150     }
1151     if (get.getRowOffsetPerColumnFamily() > 0) {
1152       builder.setStoreOffset(get.getRowOffsetPerColumnFamily());
1153     }
1154     if (get.isCheckExistenceOnly()){
1155       builder.setExistenceOnly(true);
1156     }
1157     if (get.isClosestRowBefore()){
1158       builder.setClosestRowBefore(true);
1159     }
1160     if (get.getConsistency() != null && get.getConsistency() != Consistency.STRONG) {
1161       builder.setConsistency(toConsistency(get.getConsistency()));
1162     }
1163 
1164     return builder.build();
1165   }
1166 
1167   static void setTimeRange(final MutationProto.Builder builder, final TimeRange timeRange) {
1168     if (!timeRange.isAllTime()) {
1169       HBaseProtos.TimeRange.Builder timeRangeBuilder =
1170         HBaseProtos.TimeRange.newBuilder();
1171       timeRangeBuilder.setFrom(timeRange.getMin());
1172       timeRangeBuilder.setTo(timeRange.getMax());
1173       builder.setTimeRange(timeRangeBuilder.build());
1174     }
1175   }
1176 
1177   /**
1178    * Convert a client Increment to a protobuf Mutate.
1179    *
1180    * @param increment
1181    * @return the converted mutate
1182    */
1183   public static MutationProto toMutation(
1184     final Increment increment, final MutationProto.Builder builder, long nonce) {
1185     builder.setRow(ByteStringer.wrap(increment.getRow()));
1186     builder.setMutateType(MutationType.INCREMENT);
1187     builder.setDurability(toDurability(increment.getDurability()));
1188     if (nonce != HConstants.NO_NONCE) {
1189       builder.setNonce(nonce);
1190     }
1191     TimeRange timeRange = increment.getTimeRange();
1192     setTimeRange(builder, timeRange);
1193     ColumnValue.Builder columnBuilder = ColumnValue.newBuilder();
1194     QualifierValue.Builder valueBuilder = QualifierValue.newBuilder();
1195     for (Map.Entry<byte[], List<Cell>> family: increment.getFamilyCellMap().entrySet()) {
1196       columnBuilder.setFamily(ByteStringer.wrap(family.getKey()));
1197       columnBuilder.clearQualifierValue();
1198       List<Cell> values = family.getValue();
1199       if (values != null && values.size() > 0) {
1200         for (Cell cell: values) {
1201           valueBuilder.clear();
1202           valueBuilder.setQualifier(ByteStringer.wrap(
1203               cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()));
1204           valueBuilder.setValue(ByteStringer.wrap(
1205               cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
1206           if (cell.getTagsLength() > 0) {
1207             valueBuilder.setTags(ByteStringer.wrap(cell.getTagsArray(),
1208                 cell.getTagsOffset(), cell.getTagsLength()));
1209           }
1210           columnBuilder.addQualifierValue(valueBuilder.build());
1211         }
1212       }
1213       builder.addColumnValue(columnBuilder.build());
1214     }
1215     Map<String, byte[]> attributes = increment.getAttributesMap();
1216     if (!attributes.isEmpty()) {
1217       NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
1218       for (Map.Entry<String, byte[]> attribute : attributes.entrySet()) {
1219         attributeBuilder.setName(attribute.getKey());
1220         attributeBuilder.setValue(ByteStringer.wrap(attribute.getValue()));
1221         builder.addAttribute(attributeBuilder.build());
1222       }
1223     }
1224     return builder.build();
1225   }
1226 
1227   public static MutationProto toMutation(final MutationType type, final Mutation mutation)
1228     throws IOException {
1229     return toMutation(type, mutation, HConstants.NO_NONCE);
1230   }
1231 
1232   /**
1233    * Create a protocol buffer Mutate based on a client Mutation
1234    *
1235    * @param type
1236    * @param mutation
1237    * @return a protobuf'd Mutation
1238    * @throws IOException
1239    */
1240   public static MutationProto toMutation(final MutationType type, final Mutation mutation,
1241     final long nonce) throws IOException {
1242     return toMutation(type, mutation, MutationProto.newBuilder(), nonce);
1243   }
1244 
1245   public static MutationProto toMutation(final MutationType type, final Mutation mutation,
1246       MutationProto.Builder builder) throws IOException {
1247     return toMutation(type, mutation, builder, HConstants.NO_NONCE);
1248   }
1249 
1250   public static MutationProto toMutation(final MutationType type, final Mutation mutation,
1251       MutationProto.Builder builder, long nonce)
1252   throws IOException {
1253     builder = getMutationBuilderAndSetCommonFields(type, mutation, builder);
1254     if (nonce != HConstants.NO_NONCE) {
1255       builder.setNonce(nonce);
1256     }
1257     ColumnValue.Builder columnBuilder = ColumnValue.newBuilder();
1258     QualifierValue.Builder valueBuilder = QualifierValue.newBuilder();
1259     for (Map.Entry<byte[],List<Cell>> family: mutation.getFamilyCellMap().entrySet()) {
1260       columnBuilder.clear();
1261       columnBuilder.setFamily(ByteStringer.wrap(family.getKey()));
1262       for (Cell cell: family.getValue()) {
1263         valueBuilder.clear();
1264         valueBuilder.setQualifier(ByteStringer.wrap(
1265             cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength()));
1266         valueBuilder.setValue(ByteStringer.wrap(
1267             cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()));
1268         valueBuilder.setTimestamp(cell.getTimestamp());
1269         if (type == MutationType.DELETE || (type == MutationType.PUT && CellUtil.isDelete(cell))) {
1270           KeyValue.Type keyValueType = KeyValue.Type.codeToType(cell.getTypeByte());
1271           valueBuilder.setDeleteType(toDeleteType(keyValueType));
1272         }
1273         columnBuilder.addQualifierValue(valueBuilder.build());
1274       }
1275       builder.addColumnValue(columnBuilder.build());
1276     }
1277     return builder.build();
1278   }
1279 
1280   /**
1281    * Create a protocol buffer MutationProto based on a client Mutation. Does NOT include data.
1282    * Understanding is that the Cell will be transported other than via protobuf.
1283    * @param type
1284    * @param mutation
1285    * @param builder
1286    * @return a protobuf'd Mutation
1287    * @throws IOException
1288    */
1289   public static MutationProto toMutationNoData(final MutationType type, final Mutation mutation,
1290       final MutationProto.Builder builder)  throws IOException {
1291     return toMutationNoData(type, mutation, builder, HConstants.NO_NONCE);
1292   }
1293 
1294   /**
1295    * Create a protocol buffer MutationProto based on a client Mutation.  Does NOT include data.
1296    * Understanding is that the Cell will be transported other than via protobuf.
1297    * @param type
1298    * @param mutation
1299    * @return a protobuf'd Mutation
1300    * @throws IOException
1301    */
1302   public static MutationProto toMutationNoData(final MutationType type, final Mutation mutation)
1303   throws IOException {
1304     MutationProto.Builder builder =  MutationProto.newBuilder();
1305     return toMutationNoData(type, mutation, builder);
1306   }
1307 
1308   public static MutationProto toMutationNoData(final MutationType type, final Mutation mutation,
1309       final MutationProto.Builder builder, long nonce) throws IOException {
1310     getMutationBuilderAndSetCommonFields(type, mutation, builder);
1311     builder.setAssociatedCellCount(mutation.size());
1312     if (mutation instanceof Increment) {
1313       setTimeRange(builder, ((Increment)mutation).getTimeRange());
1314     }
1315     if (nonce != HConstants.NO_NONCE) {
1316       builder.setNonce(nonce);
1317     }
1318     return builder.build();
1319   }
1320 
1321   /**
1322    * Code shared by {@link #toMutation(MutationType, Mutation)} and
1323    * {@link #toMutationNoData(MutationType, Mutation)}
1324    * @param type
1325    * @param mutation
1326    * @return A partly-filled out protobuf'd Mutation.
1327    */
1328   private static MutationProto.Builder getMutationBuilderAndSetCommonFields(final MutationType type,
1329       final Mutation mutation, MutationProto.Builder builder) {
1330     builder.setRow(ByteStringer.wrap(mutation.getRow()));
1331     builder.setMutateType(type);
1332     builder.setDurability(toDurability(mutation.getDurability()));
1333     builder.setTimestamp(mutation.getTimeStamp());
1334     Map<String, byte[]> attributes = mutation.getAttributesMap();
1335     if (!attributes.isEmpty()) {
1336       NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
1337       for (Map.Entry<String, byte[]> attribute: attributes.entrySet()) {
1338         attributeBuilder.setName(attribute.getKey());
1339         attributeBuilder.setValue(ByteStringer.wrap(attribute.getValue()));
1340         builder.addAttribute(attributeBuilder.build());
1341       }
1342     }
1343     return builder;
1344   }
1345 
1346   /**
1347    * Convert a client Result to a protocol buffer Result
1348    *
1349    * @param result the client Result to convert
1350    * @return the converted protocol buffer Result
1351    */
1352   public static ClientProtos.Result toResult(final Result result) {
1353     if (result.getExists() != null) {
1354       return toResult(result.getExists(), result.isStale());
1355     }
1356 
1357     Cell[] cells = result.rawCells();
1358     if (cells == null || cells.length == 0) {
1359       return result.isStale() ? EMPTY_RESULT_PB_STALE : EMPTY_RESULT_PB;
1360     }
1361 
1362     ClientProtos.Result.Builder builder = ClientProtos.Result.newBuilder();
1363     for (Cell c : cells) {
1364       builder.addCell(toCell(c));
1365     }
1366 
1367     builder.setStale(result.isStale());
1368     builder.setPartial(result.isPartial());
1369 
1370     return builder.build();
1371   }
1372 
1373   /**
1374    * Convert a client Result to a protocol buffer Result
1375    *
1376    * @param existence the client existence to send
1377    * @return the converted protocol buffer Result
1378    */
1379   public static ClientProtos.Result toResult(final boolean existence, boolean stale) {
1380     if (stale){
1381       return existence ? EMPTY_RESULT_PB_EXISTS_TRUE_STALE : EMPTY_RESULT_PB_EXISTS_FALSE_STALE;
1382     } else {
1383       return existence ? EMPTY_RESULT_PB_EXISTS_TRUE : EMPTY_RESULT_PB_EXISTS_FALSE;
1384     }
1385   }
1386 
1387   /**
1388    * Convert a client Result to a protocol buffer Result.
1389    * The pb Result does not include the Cell data.  That is for transport otherwise.
1390    *
1391    * @param result the client Result to convert
1392    * @return the converted protocol buffer Result
1393    */
1394   public static ClientProtos.Result toResultNoData(final Result result) {
1395     if (result.getExists() != null) return toResult(result.getExists(), result.isStale());
1396     int size = result.size();
1397     if (size == 0) return result.isStale() ? EMPTY_RESULT_PB_STALE : EMPTY_RESULT_PB;
1398     ClientProtos.Result.Builder builder = ClientProtos.Result.newBuilder();
1399     builder.setAssociatedCellCount(size);
1400     builder.setStale(result.isStale());
1401     return builder.build();
1402   }
1403 
1404   /**
1405    * Convert a protocol buffer Result to a client Result
1406    *
1407    * @param proto the protocol buffer Result to convert
1408    * @return the converted client Result
1409    */
1410   public static Result toResult(final ClientProtos.Result proto) {
1411     if (proto.hasExists()) {
1412       if (proto.getStale()) {
1413         return proto.getExists() ? EMPTY_RESULT_EXISTS_TRUE_STALE :EMPTY_RESULT_EXISTS_FALSE_STALE;
1414       }
1415       return proto.getExists() ? EMPTY_RESULT_EXISTS_TRUE : EMPTY_RESULT_EXISTS_FALSE;
1416     }
1417 
1418     List<CellProtos.Cell> values = proto.getCellList();
1419     if (values.isEmpty()){
1420       return proto.getStale() ? EMPTY_RESULT_STALE : EMPTY_RESULT;
1421     }
1422 
1423     List<Cell> cells = new ArrayList<Cell>(values.size());
1424     for (CellProtos.Cell c : values) {
1425       cells.add(toCell(c));
1426     }
1427     return Result.create(cells, null, proto.getStale(), proto.getPartial());
1428   }
1429 
1430   /**
1431    * Convert a protocol buffer Result to a client Result
1432    *
1433    * @param proto the protocol buffer Result to convert
1434    * @param scanner Optional cell scanner.
1435    * @return the converted client Result
1436    * @throws IOException
1437    */
1438   public static Result toResult(final ClientProtos.Result proto, final CellScanner scanner)
1439   throws IOException {
1440     List<CellProtos.Cell> values = proto.getCellList();
1441 
1442     if (proto.hasExists()) {
1443       if ((values != null && !values.isEmpty()) ||
1444           (proto.hasAssociatedCellCount() && proto.getAssociatedCellCount() > 0)) {
1445         throw new IllegalArgumentException("bad proto: exists with cells is no allowed " + proto);
1446       }
1447       if (proto.getStale()) {
1448         return proto.getExists() ? EMPTY_RESULT_EXISTS_TRUE_STALE :EMPTY_RESULT_EXISTS_FALSE_STALE;
1449       }
1450       return proto.getExists() ? EMPTY_RESULT_EXISTS_TRUE : EMPTY_RESULT_EXISTS_FALSE;
1451     }
1452 
1453     // TODO: Unit test that has some Cells in scanner and some in the proto.
1454     List<Cell> cells = null;
1455     if (proto.hasAssociatedCellCount()) {
1456       int count = proto.getAssociatedCellCount();
1457       cells = new ArrayList<Cell>(count + values.size());
1458       for (int i = 0; i < count; i++) {
1459         if (!scanner.advance()) throw new IOException("Failed get " + i + " of " + count);
1460         cells.add(scanner.current());
1461       }
1462     }
1463 
1464     if (!values.isEmpty()){
1465       if (cells == null) cells = new ArrayList<Cell>(values.size());
1466       for (CellProtos.Cell c: values) {
1467         cells.add(toCell(c));
1468       }
1469     }
1470 
1471     return (cells == null || cells.isEmpty())
1472         ? (proto.getStale() ? EMPTY_RESULT_STALE : EMPTY_RESULT)
1473         : Result.create(cells, null, proto.getStale());
1474   }
1475 
1476 
1477   /**
1478    * Convert a ByteArrayComparable to a protocol buffer Comparator
1479    *
1480    * @param comparator the ByteArrayComparable to convert
1481    * @return the converted protocol buffer Comparator
1482    */
1483   public static ComparatorProtos.Comparator toComparator(ByteArrayComparable comparator) {
1484     ComparatorProtos.Comparator.Builder builder = ComparatorProtos.Comparator.newBuilder();
1485     builder.setName(comparator.getClass().getName());
1486     builder.setSerializedComparator(ByteStringer.wrap(comparator.toByteArray()));
1487     return builder.build();
1488   }
1489 
1490   /**
1491    * Convert a protocol buffer Comparator to a ByteArrayComparable
1492    *
1493    * @param proto the protocol buffer Comparator to convert
1494    * @return the converted ByteArrayComparable
1495    */
1496   @SuppressWarnings("unchecked")
1497   public static ByteArrayComparable toComparator(ComparatorProtos.Comparator proto)
1498   throws IOException {
1499     String type = proto.getName();
1500     String funcName = "parseFrom";
1501     byte [] value = proto.getSerializedComparator().toByteArray();
1502     try {
1503       Class<? extends ByteArrayComparable> c =
1504         (Class<? extends ByteArrayComparable>)Class.forName(type, true, CLASS_LOADER);
1505       Method parseFrom = c.getMethod(funcName, byte[].class);
1506       if (parseFrom == null) {
1507         throw new IOException("Unable to locate function: " + funcName + " in type: " + type);
1508       }
1509       return (ByteArrayComparable)parseFrom.invoke(null, value);
1510     } catch (Exception e) {
1511       throw new IOException(e);
1512     }
1513   }
1514 
1515   /**
1516    * Convert a protocol buffer Filter to a client Filter
1517    *
1518    * @param proto the protocol buffer Filter to convert
1519    * @return the converted Filter
1520    */
1521   @SuppressWarnings("unchecked")
1522   public static Filter toFilter(FilterProtos.Filter proto) throws IOException {
1523     String type = proto.getName();
1524     final byte [] value = proto.getSerializedFilter().toByteArray();
1525     String funcName = "parseFrom";
1526     try {
1527       Class<? extends Filter> c =
1528         (Class<? extends Filter>)Class.forName(type, true, CLASS_LOADER);
1529       Method parseFrom = c.getMethod(funcName, byte[].class);
1530       if (parseFrom == null) {
1531         throw new IOException("Unable to locate function: " + funcName + " in type: " + type);
1532       }
1533       return (Filter)parseFrom.invoke(c, value);
1534     } catch (Exception e) {
1535       // Either we couldn't instantiate the method object, or "parseFrom" failed.
1536       // In either case, let's not retry.
1537       throw new DoNotRetryIOException(e);
1538     }
1539   }
1540 
1541   /**
1542    * Convert a client Filter to a protocol buffer Filter
1543    *
1544    * @param filter the Filter to convert
1545    * @return the converted protocol buffer Filter
1546    */
1547   public static FilterProtos.Filter toFilter(Filter filter) throws IOException {
1548     FilterProtos.Filter.Builder builder = FilterProtos.Filter.newBuilder();
1549     builder.setName(filter.getClass().getName());
1550     builder.setSerializedFilter(ByteStringer.wrap(filter.toByteArray()));
1551     return builder.build();
1552   }
1553 
1554   /**
1555    * Convert a delete KeyValue type to protocol buffer DeleteType.
1556    *
1557    * @param type
1558    * @return protocol buffer DeleteType
1559    * @throws IOException
1560    */
1561   public static DeleteType toDeleteType(
1562       KeyValue.Type type) throws IOException {
1563     switch (type) {
1564     case Delete:
1565       return DeleteType.DELETE_ONE_VERSION;
1566     case DeleteColumn:
1567       return DeleteType.DELETE_MULTIPLE_VERSIONS;
1568     case DeleteFamily:
1569       return DeleteType.DELETE_FAMILY;
1570     case DeleteFamilyVersion:
1571       return DeleteType.DELETE_FAMILY_VERSION;
1572     default:
1573         throw new IOException("Unknown delete type: " + type);
1574     }
1575   }
1576 
1577   /**
1578    * Convert a protocol buffer DeleteType to delete KeyValue type.
1579    *
1580    * @param type The DeleteType
1581    * @return The type.
1582    * @throws IOException
1583    */
1584   public static KeyValue.Type fromDeleteType(
1585       DeleteType type) throws IOException {
1586     switch (type) {
1587     case DELETE_ONE_VERSION:
1588       return KeyValue.Type.Delete;
1589     case DELETE_MULTIPLE_VERSIONS:
1590       return KeyValue.Type.DeleteColumn;
1591     case DELETE_FAMILY:
1592       return KeyValue.Type.DeleteFamily;
1593     case DELETE_FAMILY_VERSION:
1594       return KeyValue.Type.DeleteFamilyVersion;
1595     default:
1596       throw new IOException("Unknown delete type: " + type);
1597     }
1598   }
1599 
1600   /**
1601    * Convert a stringified protocol buffer exception Parameter to a Java Exception
1602    *
1603    * @param parameter the protocol buffer Parameter to convert
1604    * @return the converted Exception
1605    * @throws IOException if failed to deserialize the parameter
1606    */
1607   @SuppressWarnings("unchecked")
1608   public static Throwable toException(final NameBytesPair parameter) throws IOException {
1609     if (parameter == null || !parameter.hasValue()) return null;
1610     String desc = parameter.getValue().toStringUtf8();
1611     String type = parameter.getName();
1612     try {
1613       Class<? extends Throwable> c =
1614         (Class<? extends Throwable>)Class.forName(type, true, CLASS_LOADER);
1615       Constructor<? extends Throwable> cn = null;
1616       try {
1617         cn = c.getDeclaredConstructor(String.class);
1618         return cn.newInstance(desc);
1619       } catch (NoSuchMethodException e) {
1620         // Could be a raw RemoteException. See HBASE-8987.
1621         cn = c.getDeclaredConstructor(String.class, String.class);
1622         return cn.newInstance(type, desc);
1623       }
1624     } catch (Exception e) {
1625       throw new IOException(e);
1626     }
1627   }
1628 
1629 // Start helpers for Client
1630 
1631   /**
1632    * A helper to get a row of the closet one before using client protocol.
1633    *
1634    * @param client
1635    * @param regionName
1636    * @param row
1637    * @param family
1638    * @return the row or the closestRowBefore if it doesn't exist
1639    * @throws IOException
1640    * @deprecated since 0.99 - use reversed scanner instead.
1641    */
1642   @Deprecated
1643   public static Result getRowOrBefore(final ClientService.BlockingInterface client,
1644       final byte[] regionName, final byte[] row,
1645       final byte[] family) throws IOException {
1646     GetRequest request =
1647       RequestConverter.buildGetRowOrBeforeRequest(
1648         regionName, row, family);
1649     try {
1650       GetResponse response = client.get(null, request);
1651       if (!response.hasResult()) return null;
1652       // We pass 'null' RpcController. So Result will be pure RB.
1653       return toResult(response.getResult());
1654     } catch (ServiceException se) {
1655       throw getRemoteException(se);
1656     }
1657   }
1658 
1659   /**
1660    * A helper to bulk load a list of HFiles using client protocol.
1661    *
1662    * @param client
1663    * @param familyPaths
1664    * @param regionName
1665    * @param assignSeqNum
1666    * @return true if all are loaded
1667    * @throws IOException
1668    */
1669   public static boolean bulkLoadHFile(final ClientService.BlockingInterface client,
1670       final List<Pair<byte[], String>> familyPaths,
1671       final byte[] regionName, boolean assignSeqNum) throws IOException {
1672     BulkLoadHFileRequest request =
1673       RequestConverter.buildBulkLoadHFileRequest(familyPaths, regionName, assignSeqNum);
1674     try {
1675       BulkLoadHFileResponse response =
1676         client.bulkLoadHFile(null, request);
1677       return response.getLoaded();
1678     } catch (ServiceException se) {
1679       throw getRemoteException(se);
1680     }
1681   }
1682 
1683   public static CoprocessorServiceResponse execService(final RpcController controller,
1684       final ClientService.BlockingInterface client, final CoprocessorServiceCall call,
1685       final byte[] regionName) throws IOException {
1686     CoprocessorServiceRequest request = CoprocessorServiceRequest.newBuilder()
1687         .setCall(call).setRegion(
1688             RequestConverter.buildRegionSpecifier(REGION_NAME, regionName)).build();
1689     try {
1690       CoprocessorServiceResponse response =
1691           client.execService(controller, request);
1692       return response;
1693     } catch (ServiceException se) {
1694       throw getRemoteException(se);
1695     }
1696   }
1697 
1698   public static CoprocessorServiceResponse execService(final RpcController controller,
1699     final MasterService.BlockingInterface client, final CoprocessorServiceCall call)
1700   throws IOException {
1701     CoprocessorServiceRequest request = CoprocessorServiceRequest.newBuilder()
1702         .setCall(call).setRegion(
1703             RequestConverter.buildRegionSpecifier(REGION_NAME, HConstants.EMPTY_BYTE_ARRAY)).build();
1704     try {
1705       CoprocessorServiceResponse response =
1706           client.execMasterService(controller, request);
1707       return response;
1708     } catch (ServiceException se) {
1709       throw getRemoteException(se);
1710     }
1711   }
1712 
1713   /**
1714    * Make a region server endpoint call
1715    * @param client
1716    * @param call
1717    * @return CoprocessorServiceResponse
1718    * @throws IOException
1719    */
1720   public static CoprocessorServiceResponse execRegionServerService(
1721       final RpcController controller, final ClientService.BlockingInterface client,
1722       final CoprocessorServiceCall call)
1723       throws IOException {
1724     CoprocessorServiceRequest request =
1725         CoprocessorServiceRequest
1726             .newBuilder()
1727             .setCall(call)
1728             .setRegion(
1729               RequestConverter.buildRegionSpecifier(REGION_NAME, HConstants.EMPTY_BYTE_ARRAY))
1730             .build();
1731     try {
1732       CoprocessorServiceResponse response = client.execRegionServerService(controller, request);
1733       return response;
1734     } catch (ServiceException se) {
1735       throw getRemoteException(se);
1736     }
1737   }
1738 
1739   @SuppressWarnings("unchecked")
1740   public static <T extends Service> T newServiceStub(Class<T> service, RpcChannel channel)
1741       throws Exception {
1742     return (T)Methods.call(service, null, "newStub",
1743         new Class[]{ RpcChannel.class }, new Object[]{ channel });
1744   }
1745 
1746 // End helpers for Client
1747 // Start helpers for Admin
1748 
1749   /**
1750    * A helper to retrieve region info given a region name
1751    * using admin protocol.
1752    *
1753    * @param admin
1754    * @param regionName
1755    * @return the retrieved region info
1756    * @throws IOException
1757    */
1758   public static HRegionInfo getRegionInfo(final RpcController controller,
1759       final AdminService.BlockingInterface admin, final byte[] regionName) throws IOException {
1760     try {
1761       GetRegionInfoRequest request =
1762         RequestConverter.buildGetRegionInfoRequest(regionName);
1763       GetRegionInfoResponse response =
1764         admin.getRegionInfo(controller, request);
1765       return HRegionInfo.convert(response.getRegionInfo());
1766     } catch (ServiceException se) {
1767       throw getRemoteException(se);
1768     }
1769   }
1770 
1771   /**
1772    * A helper to close a region given a region name
1773    * using admin protocol.
1774    *
1775    * @param admin
1776    * @param regionName
1777    * @param transitionInZK
1778    * @throws IOException
1779    */
1780   public static void closeRegion(final RpcController controller, 
1781       final AdminService.BlockingInterface admin, final ServerName server, final byte[] regionName,
1782       final boolean transitionInZK) throws IOException {
1783     CloseRegionRequest closeRegionRequest =
1784       RequestConverter.buildCloseRegionRequest(server, regionName, transitionInZK);
1785     try {
1786       admin.closeRegion(controller, closeRegionRequest);
1787     } catch (ServiceException se) {
1788       throw getRemoteException(se);
1789     }
1790   }
1791 
1792   /**
1793    * A helper to close a region given a region name
1794    * using admin protocol.
1795    *
1796    * @param admin
1797    * @param regionName
1798    * @param versionOfClosingNode
1799    * @return true if the region is closed
1800    * @throws IOException
1801    */
1802   public static boolean closeRegion(final RpcController controller,
1803       final AdminService.BlockingInterface admin,
1804       final ServerName server,
1805       final byte[] regionName,
1806       final int versionOfClosingNode, final ServerName destinationServer,
1807       final boolean transitionInZK) throws IOException {
1808     CloseRegionRequest closeRegionRequest =
1809       RequestConverter.buildCloseRegionRequest(server,
1810         regionName, versionOfClosingNode, destinationServer, transitionInZK);
1811     try {
1812       CloseRegionResponse response = admin.closeRegion(controller, closeRegionRequest);
1813       return ResponseConverter.isClosed(response);
1814     } catch (ServiceException se) {
1815       throw getRemoteException(se);
1816     }
1817   }
1818 
1819   /**
1820    * A helper to warmup a region given a region name
1821    * using admin protocol
1822    *
1823    * @param admin
1824    * @param regionInfo
1825    *
1826    */
1827   public static void warmupRegion(final RpcController controller,
1828       final AdminService.BlockingInterface admin, final HRegionInfo regionInfo) throws IOException {
1829 
1830     try {
1831       WarmupRegionRequest warmupRegionRequest =
1832            RequestConverter.buildWarmupRegionRequest(regionInfo);
1833 
1834       admin.warmupRegion(controller, warmupRegionRequest);
1835     } catch (ServiceException e) {
1836       throw getRemoteException(e);
1837     }
1838   }
1839 
1840   /**
1841    * A helper to open a region using admin protocol.
1842    * @param admin
1843    * @param region
1844    * @throws IOException
1845    */
1846   public static void openRegion(final RpcController controller,
1847       final AdminService.BlockingInterface admin, ServerName server, final HRegionInfo region)
1848           throws IOException {
1849     OpenRegionRequest request =
1850       RequestConverter.buildOpenRegionRequest(server, region, -1, null, null);
1851     try {
1852       admin.openRegion(controller, request);
1853     } catch (ServiceException se) {
1854       throw ProtobufUtil.getRemoteException(se);
1855     }
1856   }
1857 
1858   /**
1859    * A helper to get the all the online regions on a region
1860    * server using admin protocol.
1861    *
1862    * @param admin
1863    * @return a list of online region info
1864    * @throws IOException
1865    */
1866   public static List<HRegionInfo> getOnlineRegions(final AdminService.BlockingInterface admin)
1867       throws IOException {
1868     return getOnlineRegions(null, admin);
1869   }
1870 
1871   /**
1872    * A helper to get the all the online regions on a region
1873    * server using admin protocol.
1874    * @return a list of online region info
1875    */
1876   public static List<HRegionInfo> getOnlineRegions(final RpcController controller,
1877       final AdminService.BlockingInterface admin)
1878   throws IOException {
1879     GetOnlineRegionRequest request = RequestConverter.buildGetOnlineRegionRequest();
1880     GetOnlineRegionResponse response = null;
1881     try {
1882       response = admin.getOnlineRegion(controller, request);
1883     } catch (ServiceException se) {
1884       throw getRemoteException(se);
1885     }
1886     return getRegionInfos(response);
1887   }
1888 
1889   /**
1890    * Get the list of region info from a GetOnlineRegionResponse
1891    *
1892    * @param proto the GetOnlineRegionResponse
1893    * @return the list of region info or null if <code>proto</code> is null
1894    */
1895   static List<HRegionInfo> getRegionInfos(final GetOnlineRegionResponse proto) {
1896     if (proto == null) return null;
1897     List<HRegionInfo> regionInfos = new ArrayList<HRegionInfo>();
1898     for (RegionInfo regionInfo: proto.getRegionInfoList()) {
1899       regionInfos.add(HRegionInfo.convert(regionInfo));
1900     }
1901     return regionInfos;
1902   }
1903 
1904   /**
1905    * A helper to get the info of a region server using admin protocol.
1906    * @return the server name
1907    */
1908   public static ServerInfo getServerInfo(final RpcController controller,
1909       final AdminService.BlockingInterface admin)
1910   throws IOException {
1911     GetServerInfoRequest request = RequestConverter.buildGetServerInfoRequest();
1912     try {
1913       GetServerInfoResponse response = admin.getServerInfo(controller, request);
1914       return response.getServerInfo();
1915     } catch (ServiceException se) {
1916       throw getRemoteException(se);
1917     }
1918   }
1919 
1920   /**
1921    * A helper to get the list of files of a column family
1922    * on a given region using admin protocol.
1923    *
1924    * @return the list of store files
1925    */
1926   public static List<String> getStoreFiles(final AdminService.BlockingInterface admin,
1927       final byte[] regionName, final byte[] family)
1928   throws IOException {
1929     return getStoreFiles(null, admin, regionName, family);
1930   }
1931 
1932   /**
1933    * A helper to get the list of files of a column family
1934    * on a given region using admin protocol.
1935    *
1936    * @return the list of store files
1937    */
1938   public static List<String> getStoreFiles(final RpcController controller,
1939       final AdminService.BlockingInterface admin, final byte[] regionName, final byte[] family)
1940   throws IOException {
1941     GetStoreFileRequest request =
1942       RequestConverter.buildGetStoreFileRequest(regionName, family);
1943     try {
1944       GetStoreFileResponse response = admin.getStoreFile(controller, request);
1945       return response.getStoreFileList();
1946     } catch (ServiceException se) {
1947       throw ProtobufUtil.getRemoteException(se);
1948     }
1949   }
1950 
1951   /**
1952    * A helper to split a region using admin protocol.
1953    *
1954    * @param admin
1955    * @param hri
1956    * @param splitPoint
1957    * @throws IOException
1958    */
1959   public static void split(final RpcController controller,
1960       final AdminService.BlockingInterface admin, final HRegionInfo hri, byte[] splitPoint)
1961           throws IOException {
1962     SplitRegionRequest request =
1963       RequestConverter.buildSplitRegionRequest(hri.getRegionName(), splitPoint);
1964     try {
1965       admin.splitRegion(controller, request);
1966     } catch (ServiceException se) {
1967       throw ProtobufUtil.getRemoteException(se);
1968     }
1969   }
1970 
1971   /**
1972    * A helper to merge regions using admin protocol. Send request to
1973    * regionserver.
1974    * @param admin
1975    * @param region_a
1976    * @param region_b
1977    * @param forcible true if do a compulsory merge, otherwise we will only merge
1978    *          two adjacent regions
1979    * @param user effective user
1980    * @throws IOException
1981    */
1982   public static void mergeRegions(final RpcController controller,
1983       final AdminService.BlockingInterface admin,
1984       final HRegionInfo region_a, final HRegionInfo region_b,
1985       final boolean forcible, final User user) throws IOException {
1986     final MergeRegionsRequest request = RequestConverter.buildMergeRegionsRequest(
1987         region_a.getRegionName(), region_b.getRegionName(),forcible);
1988     if (user != null) {
1989       try {
1990         user.getUGI().doAs(new PrivilegedExceptionAction<Void>() {
1991           @Override
1992           public Void run() throws Exception {
1993             try {
1994               admin.mergeRegions(controller, request);
1995             } catch (ServiceException se) {
1996               throw ProtobufUtil.getRemoteException(se);
1997             }
1998             return null;
1999           }
2000         });
2001       } catch (InterruptedException ie) {
2002         InterruptedIOException iioe = new InterruptedIOException();
2003         iioe.initCause(ie);
2004         throw iioe;
2005       }
2006     } else {
2007       try {
2008         admin.mergeRegions(controller, request);
2009       } catch (ServiceException se) {
2010         throw ProtobufUtil.getRemoteException(se);
2011       }
2012     }
2013   }
2014 
2015 // End helpers for Admin
2016 
2017   /*
2018    * Get the total (read + write) requests from a RegionLoad pb
2019    * @param rl - RegionLoad pb
2020    * @return total (read + write) requests
2021    */
2022   public static long getTotalRequestsCount(RegionLoad rl) {
2023     if (rl == null) {
2024       return 0;
2025     }
2026 
2027     return rl.getReadRequestsCount() + rl.getWriteRequestsCount();
2028   }
2029 
2030 
2031   /**
2032    * @param m Message to get delimited pb serialization of (with pb magic prefix)
2033    */
2034   public static byte [] toDelimitedByteArray(final Message m) throws IOException {
2035     // Allocate arbitrary big size so we avoid resizing.
2036     ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
2037     baos.write(PB_MAGIC);
2038     m.writeDelimitedTo(baos);
2039     return baos.toByteArray();
2040   }
2041 
2042   /**
2043    * Converts a Permission proto to a client Permission object.
2044    *
2045    * @param proto the protobuf Permission
2046    * @return the converted Permission
2047    */
2048   public static Permission toPermission(AccessControlProtos.Permission proto) {
2049     if (proto.getType() != AccessControlProtos.Permission.Type.Global) {
2050       return toTablePermission(proto);
2051     } else {
2052       List<Permission.Action> actions = toPermissionActions(proto.getGlobalPermission().getActionList());
2053       return new Permission(actions.toArray(new Permission.Action[actions.size()]));
2054     }
2055   }
2056 
2057   /**
2058    * Converts a Permission proto to a client TablePermission object.
2059    *
2060    * @param proto the protobuf Permission
2061    * @return the converted TablePermission
2062    */
2063   public static TablePermission toTablePermission(AccessControlProtos.Permission proto) {
2064     if(proto.getType() == AccessControlProtos.Permission.Type.Global) {
2065       AccessControlProtos.GlobalPermission perm = proto.getGlobalPermission();
2066       List<Permission.Action> actions = toPermissionActions(perm.getActionList());
2067 
2068       return new TablePermission(null, null, null,
2069           actions.toArray(new Permission.Action[actions.size()]));
2070     }
2071     if(proto.getType() == AccessControlProtos.Permission.Type.Namespace) {
2072       AccessControlProtos.NamespacePermission perm = proto.getNamespacePermission();
2073       List<Permission.Action> actions = toPermissionActions(perm.getActionList());
2074 
2075       if(!proto.hasNamespacePermission()) {
2076         throw new IllegalStateException("Namespace must not be empty in NamespacePermission");
2077       }
2078       String namespace = perm.getNamespaceName().toStringUtf8();
2079       return new TablePermission(namespace, actions.toArray(new Permission.Action[actions.size()]));
2080     }
2081     if(proto.getType() == AccessControlProtos.Permission.Type.Table) {
2082       AccessControlProtos.TablePermission perm = proto.getTablePermission();
2083       List<Permission.Action> actions = toPermissionActions(perm.getActionList());
2084 
2085       byte[] qualifier = null;
2086       byte[] family = null;
2087       TableName table = null;
2088 
2089       if (!perm.hasTableName()) {
2090         throw new IllegalStateException("TableName cannot be empty");
2091       }
2092       table = ProtobufUtil.toTableName(perm.getTableName());
2093 
2094       if (perm.hasFamily()) family = perm.getFamily().toByteArray();
2095       if (perm.hasQualifier()) qualifier = perm.getQualifier().toByteArray();
2096 
2097       return new TablePermission(table, family, qualifier,
2098           actions.toArray(new Permission.Action[actions.size()]));
2099     }
2100     throw new IllegalStateException("Unrecognize Perm Type: "+proto.getType());
2101   }
2102 
2103   /**
2104    * Convert a client Permission to a Permission proto
2105    *
2106    * @param perm the client Permission
2107    * @return the protobuf Permission
2108    */
2109   public static AccessControlProtos.Permission toPermission(Permission perm) {
2110     AccessControlProtos.Permission.Builder ret = AccessControlProtos.Permission.newBuilder();
2111     if (perm instanceof TablePermission) {
2112       TablePermission tablePerm = (TablePermission)perm;
2113       if(tablePerm.hasNamespace()) {
2114         ret.setType(AccessControlProtos.Permission.Type.Namespace);
2115 
2116         AccessControlProtos.NamespacePermission.Builder builder =
2117             AccessControlProtos.NamespacePermission.newBuilder();
2118         builder.setNamespaceName(ByteString.copyFromUtf8(tablePerm.getNamespace()));
2119         Permission.Action actions[] = perm.getActions();
2120         if (actions != null) {
2121           for (Permission.Action a : actions) {
2122             builder.addAction(toPermissionAction(a));
2123           }
2124         }
2125         ret.setNamespacePermission(builder);
2126         return ret.build();
2127       } else if (tablePerm.hasTable()) {
2128         ret.setType(AccessControlProtos.Permission.Type.Table);
2129 
2130         AccessControlProtos.TablePermission.Builder builder =
2131             AccessControlProtos.TablePermission.newBuilder();
2132         builder.setTableName(ProtobufUtil.toProtoTableName(tablePerm.getTableName()));
2133         if (tablePerm.hasFamily()) {
2134           builder.setFamily(ByteStringer.wrap(tablePerm.getFamily()));
2135         }
2136         if (tablePerm.hasQualifier()) {
2137           builder.setQualifier(ByteStringer.wrap(tablePerm.getQualifier()));
2138         }
2139         Permission.Action actions[] = perm.getActions();
2140         if (actions != null) {
2141           for (Permission.Action a : actions) {
2142             builder.addAction(toPermissionAction(a));
2143           }
2144         }
2145         ret.setTablePermission(builder);
2146         return ret.build();
2147       }
2148     }
2149 
2150     ret.setType(AccessControlProtos.Permission.Type.Global);
2151 
2152     AccessControlProtos.GlobalPermission.Builder builder =
2153         AccessControlProtos.GlobalPermission.newBuilder();
2154     Permission.Action actions[] = perm.getActions();
2155     if (actions != null) {
2156       for (Permission.Action a: actions) {
2157         builder.addAction(toPermissionAction(a));
2158       }
2159     }
2160     ret.setGlobalPermission(builder);
2161     return ret.build();
2162   }
2163 
2164   /**
2165    * Converts a list of Permission.Action proto to a list of client Permission.Action objects.
2166    *
2167    * @param protoActions the list of protobuf Actions
2168    * @return the converted list of Actions
2169    */
2170   public static List<Permission.Action> toPermissionActions(
2171       List<AccessControlProtos.Permission.Action> protoActions) {
2172     List<Permission.Action> actions = new ArrayList<Permission.Action>(protoActions.size());
2173     for (AccessControlProtos.Permission.Action a : protoActions) {
2174       actions.add(toPermissionAction(a));
2175     }
2176     return actions;
2177   }
2178 
2179   /**
2180    * Converts a Permission.Action proto to a client Permission.Action object.
2181    *
2182    * @param action the protobuf Action
2183    * @return the converted Action
2184    */
2185   public static Permission.Action toPermissionAction(
2186       AccessControlProtos.Permission.Action action) {
2187     switch (action) {
2188       case READ:
2189         return Permission.Action.READ;
2190       case WRITE:
2191         return Permission.Action.WRITE;
2192       case EXEC:
2193         return Permission.Action.EXEC;
2194       case CREATE:
2195         return Permission.Action.CREATE;
2196       case ADMIN:
2197         return Permission.Action.ADMIN;
2198     }
2199     throw new IllegalArgumentException("Unknown action value "+action.name());
2200   }
2201 
2202   /**
2203    * Convert a client Permission.Action to a Permission.Action proto
2204    *
2205    * @param action the client Action
2206    * @return the protobuf Action
2207    */
2208   public static AccessControlProtos.Permission.Action toPermissionAction(
2209       Permission.Action action) {
2210     switch (action) {
2211       case READ:
2212         return AccessControlProtos.Permission.Action.READ;
2213       case WRITE:
2214         return AccessControlProtos.Permission.Action.WRITE;
2215       case EXEC:
2216         return AccessControlProtos.Permission.Action.EXEC;
2217       case CREATE:
2218         return AccessControlProtos.Permission.Action.CREATE;
2219       case ADMIN:
2220         return AccessControlProtos.Permission.Action.ADMIN;
2221     }
2222     throw new IllegalArgumentException("Unknown action value "+action.name());
2223   }
2224 
2225   /**
2226    * Convert a client user permission to a user permission proto
2227    *
2228    * @param perm the client UserPermission
2229    * @return the protobuf UserPermission
2230    */
2231   public static AccessControlProtos.UserPermission toUserPermission(UserPermission perm) {
2232     return AccessControlProtos.UserPermission.newBuilder()
2233         .setUser(ByteStringer.wrap(perm.getUser()))
2234         .setPermission(toPermission(perm))
2235         .build();
2236   }
2237 
2238   /**
2239    * Converts a user permission proto to a client user permission object.
2240    *
2241    * @param proto the protobuf UserPermission
2242    * @return the converted UserPermission
2243    */
2244   public static UserPermission toUserPermission(AccessControlProtos.UserPermission proto) {
2245     return new UserPermission(proto.getUser().toByteArray(),
2246         toTablePermission(proto.getPermission()));
2247   }
2248 
2249   /**
2250    * Convert a ListMultimap&lt;String, TablePermission&gt; where key is username
2251    * to a protobuf UserPermission
2252    *
2253    * @param perm the list of user and table permissions
2254    * @return the protobuf UserTablePermissions
2255    */
2256   public static AccessControlProtos.UsersAndPermissions toUserTablePermissions(
2257       ListMultimap<String, TablePermission> perm) {
2258     AccessControlProtos.UsersAndPermissions.Builder builder =
2259                   AccessControlProtos.UsersAndPermissions.newBuilder();
2260     for (Map.Entry<String, Collection<TablePermission>> entry : perm.asMap().entrySet()) {
2261       AccessControlProtos.UsersAndPermissions.UserPermissions.Builder userPermBuilder =
2262                   AccessControlProtos.UsersAndPermissions.UserPermissions.newBuilder();
2263       userPermBuilder.setUser(ByteString.copyFromUtf8(entry.getKey()));
2264       for (TablePermission tablePerm: entry.getValue()) {
2265         userPermBuilder.addPermissions(toPermission(tablePerm));
2266       }
2267       builder.addUserPermissions(userPermBuilder.build());
2268     }
2269     return builder.build();
2270   }
2271 
2272   /**
2273    * A utility used to grant a user global permissions.
2274    * <p>
2275    * It's also called by the shell, in case you want to find references.
2276    *
2277    * @param protocol the AccessControlService protocol proxy
2278    * @param userShortName the short name of the user to grant permissions
2279    * @param actions the permissions to be granted
2280    * @throws ServiceException
2281    */
2282   public static void grant(RpcController controller,
2283       AccessControlService.BlockingInterface protocol, String userShortName,
2284       Permission.Action... actions) throws ServiceException {
2285     List<AccessControlProtos.Permission.Action> permActions =
2286         Lists.newArrayListWithCapacity(actions.length);
2287     for (Permission.Action a : actions) {
2288       permActions.add(ProtobufUtil.toPermissionAction(a));
2289     }
2290     AccessControlProtos.GrantRequest request = RequestConverter.
2291       buildGrantRequest(userShortName, permActions.toArray(
2292         new AccessControlProtos.Permission.Action[actions.length]));
2293     protocol.grant(controller, request);
2294   }
2295 
2296   /**
2297    * A utility used to grant a user table permissions. The permissions will
2298    * be for a table table/column family/qualifier.
2299    * <p>
2300    * It's also called by the shell, in case you want to find references.
2301    *
2302    * @param protocol the AccessControlService protocol proxy
2303    * @param userShortName the short name of the user to grant permissions
2304    * @param tableName optional table name
2305    * @param f optional column family
2306    * @param q optional qualifier
2307    * @param actions the permissions to be granted
2308    * @throws ServiceException
2309    */
2310   public static void grant(RpcController controller,
2311       AccessControlService.BlockingInterface protocol, String userShortName, TableName tableName,
2312       byte[] f, byte[] q, Permission.Action... actions) throws ServiceException {
2313     List<AccessControlProtos.Permission.Action> permActions =
2314         Lists.newArrayListWithCapacity(actions.length);
2315     for (Permission.Action a : actions) {
2316       permActions.add(ProtobufUtil.toPermissionAction(a));
2317     }
2318     AccessControlProtos.GrantRequest request = RequestConverter.
2319       buildGrantRequest(userShortName, tableName, f, q, permActions.toArray(
2320         new AccessControlProtos.Permission.Action[actions.length]));
2321     protocol.grant(controller, request);
2322   }
2323 
2324   /**
2325    * A utility used to grant a user namespace permissions.
2326    * <p>
2327    * It's also called by the shell, in case you want to find references.
2328    *
2329    * @param protocol the AccessControlService protocol proxy
2330    * @param namespace the short name of the user to grant permissions
2331    * @param actions the permissions to be granted
2332    * @throws ServiceException
2333    */
2334   public static void grant(RpcController controller,
2335       AccessControlService.BlockingInterface protocol, String userShortName, String namespace,
2336       Permission.Action... actions) throws ServiceException {
2337     List<AccessControlProtos.Permission.Action> permActions =
2338         Lists.newArrayListWithCapacity(actions.length);
2339     for (Permission.Action a : actions) {
2340       permActions.add(ProtobufUtil.toPermissionAction(a));
2341     }
2342     AccessControlProtos.GrantRequest request = RequestConverter.
2343       buildGrantRequest(userShortName, namespace, permActions.toArray(
2344         new AccessControlProtos.Permission.Action[actions.length]));
2345     protocol.grant(controller, request);
2346   }
2347 
2348   /**
2349    * A utility used to revoke a user's global permissions.
2350    * <p>
2351    * It's also called by the shell, in case you want to find references.
2352    *
2353    * @param protocol the AccessControlService protocol proxy
2354    * @param userShortName the short name of the user to revoke permissions
2355    * @param actions the permissions to be revoked
2356    * @throws ServiceException
2357    */
2358   public static void revoke(RpcController controller,
2359       AccessControlService.BlockingInterface protocol, String userShortName,
2360       Permission.Action... actions) throws ServiceException {
2361     List<AccessControlProtos.Permission.Action> permActions =
2362         Lists.newArrayListWithCapacity(actions.length);
2363     for (Permission.Action a : actions) {
2364       permActions.add(ProtobufUtil.toPermissionAction(a));
2365     }
2366     AccessControlProtos.RevokeRequest request = RequestConverter.
2367       buildRevokeRequest(userShortName, permActions.toArray(
2368         new AccessControlProtos.Permission.Action[actions.length]));
2369     protocol.revoke(controller, request);
2370   }
2371 
2372   /**
2373    * A utility used to revoke a user's table permissions. The permissions will
2374    * be for a table/column family/qualifier.
2375    * <p>
2376    * It's also called by the shell, in case you want to find references.
2377    *
2378    * @param protocol the AccessControlService protocol proxy
2379    * @param userShortName the short name of the user to revoke permissions
2380    * @param tableName optional table name
2381    * @param f optional column family
2382    * @param q optional qualifier
2383    * @param actions the permissions to be revoked
2384    * @throws ServiceException
2385    */
2386   public static void revoke(RpcController controller,
2387       AccessControlService.BlockingInterface protocol, String userShortName, TableName tableName,
2388       byte[] f, byte[] q, Permission.Action... actions) throws ServiceException {
2389     List<AccessControlProtos.Permission.Action> permActions =
2390         Lists.newArrayListWithCapacity(actions.length);
2391     for (Permission.Action a : actions) {
2392       permActions.add(ProtobufUtil.toPermissionAction(a));
2393     }
2394     AccessControlProtos.RevokeRequest request = RequestConverter.
2395       buildRevokeRequest(userShortName, tableName, f, q, permActions.toArray(
2396         new AccessControlProtos.Permission.Action[actions.length]));
2397     protocol.revoke(controller, request);
2398   }
2399 
2400   /**
2401    * A utility used to revoke a user's namespace permissions.
2402    * <p>
2403    * It's also called by the shell, in case you want to find references.
2404    *
2405    * @param protocol the AccessControlService protocol proxy
2406    * @param userShortName the short name of the user to revoke permissions
2407    * @param namespace optional table name
2408    * @param actions the permissions to be revoked
2409    * @throws ServiceException
2410    */
2411   public static void revoke(RpcController controller,
2412       AccessControlService.BlockingInterface protocol, String userShortName, String namespace,
2413       Permission.Action... actions) throws ServiceException {
2414     List<AccessControlProtos.Permission.Action> permActions =
2415         Lists.newArrayListWithCapacity(actions.length);
2416     for (Permission.Action a : actions) {
2417       permActions.add(ProtobufUtil.toPermissionAction(a));
2418     }
2419     AccessControlProtos.RevokeRequest request = RequestConverter.
2420       buildRevokeRequest(userShortName, namespace, permActions.toArray(
2421         new AccessControlProtos.Permission.Action[actions.length]));
2422     protocol.revoke(controller, request);
2423   }
2424 
2425   /**
2426    * A utility used to get user's global permissions.
2427    * <p>
2428    * It's also called by the shell, in case you want to find references.
2429    *
2430    * @param protocol the AccessControlService protocol proxy
2431    * @throws ServiceException
2432    */
2433   public static List<UserPermission> getUserPermissions(RpcController controller,
2434       AccessControlService.BlockingInterface protocol) throws ServiceException {
2435     AccessControlProtos.GetUserPermissionsRequest.Builder builder =
2436       AccessControlProtos.GetUserPermissionsRequest.newBuilder();
2437     builder.setType(AccessControlProtos.Permission.Type.Global);
2438     AccessControlProtos.GetUserPermissionsRequest request = builder.build();
2439     AccessControlProtos.GetUserPermissionsResponse response =
2440       protocol.getUserPermissions(controller, request);
2441     List<UserPermission> perms = new ArrayList<UserPermission>(response.getUserPermissionCount());
2442     for (AccessControlProtos.UserPermission perm: response.getUserPermissionList()) {
2443       perms.add(ProtobufUtil.toUserPermission(perm));
2444     }
2445     return perms;
2446   }
2447 
2448   /**
2449    * A utility used to get user table permissions.
2450    * <p>
2451    * It's also called by the shell, in case you want to find references.
2452    *
2453    * @param protocol the AccessControlService protocol proxy
2454    * @param t optional table name
2455    * @throws ServiceException
2456    */
2457   public static List<UserPermission> getUserPermissions(RpcController controller,
2458       AccessControlService.BlockingInterface protocol,
2459       TableName t) throws ServiceException {
2460     AccessControlProtos.GetUserPermissionsRequest.Builder builder =
2461       AccessControlProtos.GetUserPermissionsRequest.newBuilder();
2462     if (t != null) {
2463       builder.setTableName(ProtobufUtil.toProtoTableName(t));
2464     }
2465     builder.setType(AccessControlProtos.Permission.Type.Table);
2466     AccessControlProtos.GetUserPermissionsRequest request = builder.build();
2467     AccessControlProtos.GetUserPermissionsResponse response =
2468       protocol.getUserPermissions(controller, request);
2469     List<UserPermission> perms = new ArrayList<UserPermission>(response.getUserPermissionCount());
2470     for (AccessControlProtos.UserPermission perm: response.getUserPermissionList()) {
2471       perms.add(ProtobufUtil.toUserPermission(perm));
2472     }
2473     return perms;
2474   }
2475 
2476   /**
2477    * A utility used to get permissions for selected namespace.
2478    * <p>
2479    * It's also called by the shell, in case you want to find references.
2480    *
2481    * @param protocol the AccessControlService protocol proxy
2482    * @param namespace name of the namespace
2483    * @throws ServiceException
2484    */
2485   public static List<UserPermission> getUserPermissions(RpcController controller,
2486       AccessControlService.BlockingInterface protocol,
2487       byte[] namespace) throws ServiceException {
2488     AccessControlProtos.GetUserPermissionsRequest.Builder builder =
2489       AccessControlProtos.GetUserPermissionsRequest.newBuilder();
2490     if (namespace != null) {
2491       builder.setNamespaceName(ByteStringer.wrap(namespace));
2492     }
2493     builder.setType(AccessControlProtos.Permission.Type.Namespace);
2494     AccessControlProtos.GetUserPermissionsRequest request = builder.build();
2495     AccessControlProtos.GetUserPermissionsResponse response =
2496       protocol.getUserPermissions(controller, request);
2497     List<UserPermission> perms = new ArrayList<UserPermission>(response.getUserPermissionCount());
2498     for (AccessControlProtos.UserPermission perm: response.getUserPermissionList()) {
2499       perms.add(ProtobufUtil.toUserPermission(perm));
2500     }
2501     return perms;
2502   }
2503 
2504   /**
2505    * Convert a protobuf UserTablePermissions to a
2506    * ListMultimap&lt;String, TablePermission&gt; where key is username.
2507    *
2508    * @param proto the protobuf UserPermission
2509    * @return the converted UserPermission
2510    */
2511   public static ListMultimap<String, TablePermission> toUserTablePermissions(
2512       AccessControlProtos.UsersAndPermissions proto) {
2513     ListMultimap<String, TablePermission> perms = ArrayListMultimap.create();
2514     AccessControlProtos.UsersAndPermissions.UserPermissions userPerm;
2515 
2516     for (int i = 0; i < proto.getUserPermissionsCount(); i++) {
2517       userPerm = proto.getUserPermissions(i);
2518       for (int j = 0; j < userPerm.getPermissionsCount(); j++) {
2519         TablePermission tablePerm = toTablePermission(userPerm.getPermissions(j));
2520         perms.put(userPerm.getUser().toStringUtf8(), tablePerm);
2521       }
2522     }
2523 
2524     return perms;
2525   }
2526 
2527   /**
2528    * Converts a Token instance (with embedded identifier) to the protobuf representation.
2529    *
2530    * @param token the Token instance to copy
2531    * @return the protobuf Token message
2532    */
2533   public static AuthenticationProtos.Token toToken(Token<AuthenticationTokenIdentifier> token) {
2534     AuthenticationProtos.Token.Builder builder = AuthenticationProtos.Token.newBuilder();
2535     builder.setIdentifier(ByteStringer.wrap(token.getIdentifier()));
2536     builder.setPassword(ByteStringer.wrap(token.getPassword()));
2537     if (token.getService() != null) {
2538       builder.setService(ByteString.copyFromUtf8(token.getService().toString()));
2539     }
2540     return builder.build();
2541   }
2542 
2543   /**
2544    * Converts a protobuf Token message back into a Token instance.
2545    *
2546    * @param proto the protobuf Token message
2547    * @return the Token instance
2548    */
2549   public static Token<AuthenticationTokenIdentifier> toToken(AuthenticationProtos.Token proto) {
2550     return new Token<AuthenticationTokenIdentifier>(
2551         proto.hasIdentifier() ? proto.getIdentifier().toByteArray() : null,
2552         proto.hasPassword() ? proto.getPassword().toByteArray() : null,
2553         AuthenticationTokenIdentifier.AUTH_TOKEN_TYPE,
2554         proto.hasService() ? new Text(proto.getService().toStringUtf8()) : null);
2555   }
2556 
2557   /**
2558    * Find the HRegion encoded name based on a region specifier
2559    *
2560    * @param regionSpecifier the region specifier
2561    * @return the corresponding region's encoded name
2562    * @throws DoNotRetryIOException if the specifier type is unsupported
2563    */
2564   public static String getRegionEncodedName(
2565       final RegionSpecifier regionSpecifier) throws DoNotRetryIOException {
2566     ByteString value = regionSpecifier.getValue();
2567     RegionSpecifierType type = regionSpecifier.getType();
2568     switch (type) {
2569       case REGION_NAME:
2570         return HRegionInfo.encodeRegionName(value.toByteArray());
2571       case ENCODED_REGION_NAME:
2572         return value.toStringUtf8();
2573       default:
2574         throw new DoNotRetryIOException(
2575           "Unsupported region specifier type: " + type);
2576     }
2577   }
2578 
2579   public static ScanMetrics toScanMetrics(final byte[] bytes) {
2580     Parser<MapReduceProtos.ScanMetrics> parser = MapReduceProtos.ScanMetrics.PARSER;
2581     MapReduceProtos.ScanMetrics pScanMetrics = null;
2582     try {
2583       pScanMetrics = parser.parseFrom(bytes);
2584     } catch (InvalidProtocolBufferException e) {
2585       //Ignored there are just no key values to add.
2586     }
2587     ScanMetrics scanMetrics = new ScanMetrics();
2588     if (pScanMetrics != null) {
2589       for (HBaseProtos.NameInt64Pair pair : pScanMetrics.getMetricsList()) {
2590         if (pair.hasName() && pair.hasValue()) {
2591           scanMetrics.setCounter(pair.getName(), pair.getValue());
2592         }
2593       }
2594     }
2595     return scanMetrics;
2596   }
2597 
2598   public static MapReduceProtos.ScanMetrics toScanMetrics(ScanMetrics scanMetrics) {
2599     MapReduceProtos.ScanMetrics.Builder builder = MapReduceProtos.ScanMetrics.newBuilder();
2600     Map<String, Long> metrics = scanMetrics.getMetricsMap();
2601     for (Entry<String, Long> e : metrics.entrySet()) {
2602       HBaseProtos.NameInt64Pair nameInt64Pair =
2603           HBaseProtos.NameInt64Pair.newBuilder()
2604               .setName(e.getKey())
2605               .setValue(e.getValue())
2606               .build();
2607       builder.addMetrics(nameInt64Pair);
2608     }
2609     return builder.build();
2610   }
2611 
2612   /**
2613    * Unwraps an exception from a protobuf service into the underlying (expected) IOException.
2614    * This method will <strong>always</strong> throw an exception.
2615    * @param se the {@code ServiceException} instance to convert into an {@code IOException}
2616    */
2617   public static void toIOException(ServiceException se) throws IOException {
2618     if (se == null) {
2619       throw new NullPointerException("Null service exception passed!");
2620     }
2621 
2622     Throwable cause = se.getCause();
2623     if (cause != null && cause instanceof IOException) {
2624       throw (IOException)cause;
2625     }
2626     throw new IOException(se);
2627   }
2628 
2629   public static CellProtos.Cell toCell(final Cell kv) {
2630     // Doing this is going to kill us if we do it for all data passed.
2631     // St.Ack 20121205
2632     CellProtos.Cell.Builder kvbuilder = CellProtos.Cell.newBuilder();
2633     kvbuilder.setRow(ByteStringer.wrap(kv.getRowArray(), kv.getRowOffset(),
2634         kv.getRowLength()));
2635     kvbuilder.setFamily(ByteStringer.wrap(kv.getFamilyArray(),
2636         kv.getFamilyOffset(), kv.getFamilyLength()));
2637     kvbuilder.setQualifier(ByteStringer.wrap(kv.getQualifierArray(),
2638         kv.getQualifierOffset(), kv.getQualifierLength()));
2639     kvbuilder.setCellType(CellProtos.CellType.valueOf(kv.getTypeByte()));
2640     kvbuilder.setTimestamp(kv.getTimestamp());
2641     kvbuilder.setValue(ByteStringer.wrap(kv.getValueArray(), kv.getValueOffset(),
2642         kv.getValueLength()));
2643     return kvbuilder.build();
2644   }
2645 
2646   public static Cell toCell(final CellProtos.Cell cell) {
2647     // Doing this is going to kill us if we do it for all data passed.
2648     // St.Ack 20121205
2649     return CellUtil.createCell(cell.getRow().toByteArray(),
2650       cell.getFamily().toByteArray(),
2651       cell.getQualifier().toByteArray(),
2652       cell.getTimestamp(),
2653       (byte)cell.getCellType().getNumber(),
2654       cell.getValue().toByteArray());
2655   }
2656 
2657   public static HBaseProtos.NamespaceDescriptor toProtoNamespaceDescriptor(NamespaceDescriptor ns) {
2658     HBaseProtos.NamespaceDescriptor.Builder b =
2659         HBaseProtos.NamespaceDescriptor.newBuilder()
2660             .setName(ByteString.copyFromUtf8(ns.getName()));
2661     for(Map.Entry<String, String> entry: ns.getConfiguration().entrySet()) {
2662       b.addConfiguration(HBaseProtos.NameStringPair.newBuilder()
2663           .setName(entry.getKey())
2664           .setValue(entry.getValue()));
2665     }
2666     return b.build();
2667   }
2668 
2669   public static NamespaceDescriptor toNamespaceDescriptor(
2670       HBaseProtos.NamespaceDescriptor desc) throws IOException {
2671     NamespaceDescriptor.Builder b =
2672       NamespaceDescriptor.create(desc.getName().toStringUtf8());
2673     for(HBaseProtos.NameStringPair prop : desc.getConfigurationList()) {
2674       b.addConfiguration(prop.getName(), prop.getValue());
2675     }
2676     return b.build();
2677   }
2678 
2679   /**
2680    * Get an instance of the argument type declared in a class's signature. The
2681    * argument type is assumed to be a PB Message subclass, and the instance is
2682    * created using parseFrom method on the passed ByteString.
2683    * @param runtimeClass the runtime type of the class
2684    * @param position the position of the argument in the class declaration
2685    * @param b the ByteString which should be parsed to get the instance created
2686    * @return the instance
2687    * @throws IOException
2688    */
2689   @SuppressWarnings("unchecked")
2690   public static <T extends Message>
2691   T getParsedGenericInstance(Class<?> runtimeClass, int position, ByteString b)
2692       throws IOException {
2693     Type type = runtimeClass.getGenericSuperclass();
2694     Type argType = ((ParameterizedType)type).getActualTypeArguments()[position];
2695     Class<T> classType = (Class<T>)argType;
2696     T inst;
2697     try {
2698       Method m = classType.getMethod("parseFrom", ByteString.class);
2699       inst = (T)m.invoke(null, b);
2700       return inst;
2701     } catch (SecurityException e) {
2702       throw new IOException(e);
2703     } catch (NoSuchMethodException e) {
2704       throw new IOException(e);
2705     } catch (IllegalArgumentException e) {
2706       throw new IOException(e);
2707     } catch (InvocationTargetException e) {
2708       throw new IOException(e);
2709     } catch (IllegalAccessException e) {
2710       throw new IOException(e);
2711     }
2712   }
2713 
2714   public static CompactionDescriptor toCompactionDescriptor(HRegionInfo info, byte[] family,
2715       List<Path> inputPaths, List<Path> outputPaths, Path storeDir) {
2716     return toCompactionDescriptor(info, null, family, inputPaths, outputPaths, storeDir);
2717   }
2718 
2719   @SuppressWarnings("deprecation")
2720   public static CompactionDescriptor toCompactionDescriptor(HRegionInfo info, byte[] regionName,
2721       byte[] family, List<Path> inputPaths, List<Path> outputPaths, Path storeDir) {
2722     // compaction descriptor contains relative paths.
2723     // input / output paths are relative to the store dir
2724     // store dir is relative to region dir
2725     CompactionDescriptor.Builder builder = CompactionDescriptor.newBuilder()
2726         .setTableName(ByteStringer.wrap(info.getTableName()))
2727         .setEncodedRegionName(ByteStringer.wrap(
2728           regionName == null ? info.getEncodedNameAsBytes() : regionName))
2729         .setFamilyName(ByteStringer.wrap(family))
2730         .setStoreHomeDir(storeDir.getName()); //make relative
2731     for (Path inputPath : inputPaths) {
2732       builder.addCompactionInput(inputPath.getName()); //relative path
2733     }
2734     for (Path outputPath : outputPaths) {
2735       builder.addCompactionOutput(outputPath.getName());
2736     }
2737     builder.setRegionName(ByteStringer.wrap(info.getRegionName()));
2738     return builder.build();
2739   }
2740 
2741   public static FlushDescriptor toFlushDescriptor(FlushAction action, HRegionInfo hri,
2742       long flushSeqId, Map<byte[], List<Path>> committedFiles) {
2743     FlushDescriptor.Builder desc = FlushDescriptor.newBuilder()
2744         .setAction(action)
2745         .setEncodedRegionName(ByteStringer.wrap(hri.getEncodedNameAsBytes()))
2746         .setRegionName(ByteStringer.wrap(hri.getRegionName()))
2747         .setFlushSequenceNumber(flushSeqId)
2748         .setTableName(ByteStringer.wrap(hri.getTable().getName()));
2749 
2750     for (Map.Entry<byte[], List<Path>> entry : committedFiles.entrySet()) {
2751       WALProtos.FlushDescriptor.StoreFlushDescriptor.Builder builder =
2752           WALProtos.FlushDescriptor.StoreFlushDescriptor.newBuilder()
2753           .setFamilyName(ByteStringer.wrap(entry.getKey()))
2754           .setStoreHomeDir(Bytes.toString(entry.getKey())); //relative to region
2755       if (entry.getValue() != null) {
2756         for (Path path : entry.getValue()) {
2757           builder.addFlushOutput(path.getName());
2758         }
2759       }
2760       desc.addStoreFlushes(builder);
2761     }
2762     return desc.build();
2763   }
2764 
2765   public static RegionEventDescriptor toRegionEventDescriptor(
2766       EventType eventType, HRegionInfo hri, long seqId, ServerName server,
2767       Map<byte[], List<Path>> storeFiles) {
2768     final byte[] tableNameAsBytes = hri.getTable().getName();
2769     final byte[] encodedNameAsBytes = hri.getEncodedNameAsBytes();
2770     final byte[] regionNameAsBytes = hri.getRegionName();
2771     return toRegionEventDescriptor(eventType,
2772         tableNameAsBytes,
2773         encodedNameAsBytes,
2774         regionNameAsBytes,
2775         seqId,
2776 
2777         server,
2778         storeFiles);
2779   }
2780 
2781   public static RegionEventDescriptor toRegionEventDescriptor(EventType eventType,
2782                                                               byte[] tableNameAsBytes,
2783                                                               byte[] encodedNameAsBytes,
2784                                                               byte[] regionNameAsBytes,
2785                                                                long seqId,
2786 
2787                                                               ServerName server,
2788                                                               Map<byte[], List<Path>> storeFiles) {
2789     RegionEventDescriptor.Builder desc = RegionEventDescriptor.newBuilder()
2790         .setEventType(eventType)
2791         .setTableName(ByteStringer.wrap(tableNameAsBytes))
2792         .setEncodedRegionName(ByteStringer.wrap(encodedNameAsBytes))
2793         .setRegionName(ByteStringer.wrap(regionNameAsBytes))
2794         .setLogSequenceNumber(seqId)
2795         .setServer(toServerName(server));
2796 
2797     for (Entry<byte[], List<Path>> entry : storeFiles.entrySet()) {
2798       StoreDescriptor.Builder builder = StoreDescriptor.newBuilder()
2799           .setFamilyName(ByteStringer.wrap(entry.getKey()))
2800           .setStoreHomeDir(Bytes.toString(entry.getKey()));
2801       for (Path path : entry.getValue()) {
2802         builder.addStoreFile(path.getName());
2803       }
2804 
2805       desc.addStores(builder);
2806     }
2807     return desc.build();
2808   }
2809 
2810   /**
2811    * Return short version of Message toString'd, shorter than TextFormat#shortDebugString.
2812    * Tries to NOT print out data both because it can be big but also so we do not have data in our
2813    * logs. Use judiciously.
2814    * @param m
2815    * @return toString of passed <code>m</code>
2816    */
2817   public static String getShortTextFormat(Message m) {
2818     if (m == null) return "null";
2819     if (m instanceof ScanRequest) {
2820       // This should be small and safe to output.  No data.
2821       return TextFormat.shortDebugString(m);
2822     } else if (m instanceof RegionServerReportRequest) {
2823       // Print a short message only, just the servername and the requests, not the full load.
2824       RegionServerReportRequest r = (RegionServerReportRequest)m;
2825       return "server " + TextFormat.shortDebugString(r.getServer()) +
2826         " load { numberOfRequests: " + r.getLoad().getNumberOfRequests() + " }";
2827     } else if (m instanceof RegionServerStartupRequest) {
2828       // Should be small enough.
2829       return TextFormat.shortDebugString(m);
2830     } else if (m instanceof MutationProto) {
2831       return toShortString((MutationProto)m);
2832     } else if (m instanceof GetRequest) {
2833       GetRequest r = (GetRequest) m;
2834       return "region= " + getStringForByteString(r.getRegion().getValue()) +
2835           ", row=" + getStringForByteString(r.getGet().getRow());
2836     } else if (m instanceof ClientProtos.MultiRequest) {
2837       ClientProtos.MultiRequest r = (ClientProtos.MultiRequest) m;
2838       // Get first set of Actions.
2839       ClientProtos.RegionAction actions = r.getRegionActionList().get(0);
2840       String row = actions.getActionCount() <= 0? "":
2841         getStringForByteString(actions.getAction(0).hasGet()?
2842           actions.getAction(0).getGet().getRow():
2843           actions.getAction(0).getMutation().getRow());
2844       return "region= " + getStringForByteString(actions.getRegion().getValue()) +
2845           ", for " + r.getRegionActionCount() +
2846           " actions and 1st row key=" + row;
2847     } else if (m instanceof ClientProtos.MutateRequest) {
2848       ClientProtos.MutateRequest r = (ClientProtos.MutateRequest) m;
2849       return "region= " + getStringForByteString(r.getRegion().getValue()) +
2850           ", row=" + getStringForByteString(r.getMutation().getRow());
2851     }
2852     return "TODO: " + m.getClass().toString();
2853   }
2854 
2855   private static String getStringForByteString(ByteString bs) {
2856     return Bytes.toStringBinary(bs.toByteArray());
2857   }
2858 
2859   /**
2860    * Print out some subset of a MutationProto rather than all of it and its data
2861    * @param proto Protobuf to print out
2862    * @return Short String of mutation proto
2863    */
2864   static String toShortString(final MutationProto proto) {
2865     return "row=" + Bytes.toString(proto.getRow().toByteArray()) +
2866         ", type=" + proto.getMutateType().toString();
2867   }
2868 
2869   public static TableName toTableName(HBaseProtos.TableName tableNamePB) {
2870     return TableName.valueOf(tableNamePB.getNamespace().asReadOnlyByteBuffer(),
2871         tableNamePB.getQualifier().asReadOnlyByteBuffer());
2872   }
2873 
2874   public static HBaseProtos.TableName toProtoTableName(TableName tableName) {
2875     return HBaseProtos.TableName.newBuilder()
2876         .setNamespace(ByteStringer.wrap(tableName.getNamespace()))
2877         .setQualifier(ByteStringer.wrap(tableName.getQualifier())).build();
2878   }
2879 
2880   public static TableName[] getTableNameArray(List<HBaseProtos.TableName> tableNamesList) {
2881     if (tableNamesList == null) {
2882       return new TableName[0];
2883     }
2884     TableName[] tableNames = new TableName[tableNamesList.size()];
2885     for (int i = 0; i < tableNamesList.size(); i++) {
2886       tableNames[i] = toTableName(tableNamesList.get(i));
2887     }
2888     return tableNames;
2889   }
2890 
2891   /**
2892    * Convert a protocol buffer CellVisibility to a client CellVisibility
2893    *
2894    * @param proto
2895    * @return the converted client CellVisibility
2896    */
2897   public static CellVisibility toCellVisibility(ClientProtos.CellVisibility proto) {
2898     if (proto == null) return null;
2899     return new CellVisibility(proto.getExpression());
2900   }
2901 
2902   /**
2903    * Convert a protocol buffer CellVisibility bytes to a client CellVisibility
2904    *
2905    * @param protoBytes
2906    * @return the converted client CellVisibility
2907    * @throws DeserializationException
2908    */
2909   public static CellVisibility toCellVisibility(byte[] protoBytes) throws DeserializationException {
2910     if (protoBytes == null) return null;
2911     ClientProtos.CellVisibility.Builder builder = ClientProtos.CellVisibility.newBuilder();
2912     ClientProtos.CellVisibility proto = null;
2913     try {
2914       ProtobufUtil.mergeFrom(builder, protoBytes);
2915       proto = builder.build();
2916     } catch (IOException e) {
2917       throw new DeserializationException(e);
2918     }
2919     return toCellVisibility(proto);
2920   }
2921 
2922   /**
2923    * Create a protocol buffer CellVisibility based on a client CellVisibility.
2924    *
2925    * @param cellVisibility
2926    * @return a protocol buffer CellVisibility
2927    */
2928   public static ClientProtos.CellVisibility toCellVisibility(CellVisibility cellVisibility) {
2929     ClientProtos.CellVisibility.Builder builder = ClientProtos.CellVisibility.newBuilder();
2930     builder.setExpression(cellVisibility.getExpression());
2931     return builder.build();
2932   }
2933 
2934   /**
2935    * Convert a protocol buffer Authorizations to a client Authorizations
2936    *
2937    * @param proto
2938    * @return the converted client Authorizations
2939    */
2940   public static Authorizations toAuthorizations(ClientProtos.Authorizations proto) {
2941     if (proto == null) return null;
2942     return new Authorizations(proto.getLabelList());
2943   }
2944 
2945   /**
2946    * Convert a protocol buffer Authorizations bytes to a client Authorizations
2947    *
2948    * @param protoBytes
2949    * @return the converted client Authorizations
2950    * @throws DeserializationException
2951    */
2952   public static Authorizations toAuthorizations(byte[] protoBytes) throws DeserializationException {
2953     if (protoBytes == null) return null;
2954     ClientProtos.Authorizations.Builder builder = ClientProtos.Authorizations.newBuilder();
2955     ClientProtos.Authorizations proto = null;
2956     try {
2957       ProtobufUtil.mergeFrom(builder, protoBytes);
2958       proto = builder.build();
2959     } catch (IOException e) {
2960       throw new DeserializationException(e);
2961     }
2962     return toAuthorizations(proto);
2963   }
2964 
2965   /**
2966    * Create a protocol buffer Authorizations based on a client Authorizations.
2967    *
2968    * @param authorizations
2969    * @return a protocol buffer Authorizations
2970    */
2971   public static ClientProtos.Authorizations toAuthorizations(Authorizations authorizations) {
2972     ClientProtos.Authorizations.Builder builder = ClientProtos.Authorizations.newBuilder();
2973     for (String label : authorizations.getLabels()) {
2974       builder.addLabel(label);
2975     }
2976     return builder.build();
2977   }
2978 
2979   public static AccessControlProtos.UsersAndPermissions toUsersAndPermissions(String user,
2980       Permission perms) {
2981     return AccessControlProtos.UsersAndPermissions.newBuilder()
2982       .addUserPermissions(AccessControlProtos.UsersAndPermissions.UserPermissions.newBuilder()
2983         .setUser(ByteString.copyFromUtf8(user))
2984         .addPermissions(toPermission(perms))
2985         .build())
2986       .build();
2987   }
2988 
2989   public static AccessControlProtos.UsersAndPermissions toUsersAndPermissions(
2990       ListMultimap<String, Permission> perms) {
2991     AccessControlProtos.UsersAndPermissions.Builder builder =
2992         AccessControlProtos.UsersAndPermissions.newBuilder();
2993     for (Map.Entry<String, Collection<Permission>> entry : perms.asMap().entrySet()) {
2994       AccessControlProtos.UsersAndPermissions.UserPermissions.Builder userPermBuilder =
2995         AccessControlProtos.UsersAndPermissions.UserPermissions.newBuilder();
2996       userPermBuilder.setUser(ByteString.copyFromUtf8(entry.getKey()));
2997       for (Permission perm: entry.getValue()) {
2998         userPermBuilder.addPermissions(toPermission(perm));
2999       }
3000       builder.addUserPermissions(userPermBuilder.build());
3001     }
3002     return builder.build();
3003   }
3004 
3005   public static ListMultimap<String, Permission> toUsersAndPermissions(
3006       AccessControlProtos.UsersAndPermissions proto) {
3007     ListMultimap<String, Permission> result = ArrayListMultimap.create();
3008     for (AccessControlProtos.UsersAndPermissions.UserPermissions userPerms:
3009         proto.getUserPermissionsList()) {
3010       String user = userPerms.getUser().toStringUtf8();
3011       for (AccessControlProtos.Permission perm: userPerms.getPermissionsList()) {
3012         result.put(user, toPermission(perm));
3013       }
3014     }
3015     return result;
3016   }
3017   
3018   /**
3019    * Convert a protocol buffer TimeUnit to a client TimeUnit
3020    * @param proto
3021    * @return the converted client TimeUnit
3022    */
3023   public static TimeUnit toTimeUnit(final HBaseProtos.TimeUnit proto) {
3024     switch (proto) {
3025     case NANOSECONDS:
3026       return TimeUnit.NANOSECONDS;
3027     case MICROSECONDS:
3028       return TimeUnit.MICROSECONDS;
3029     case MILLISECONDS:
3030       return TimeUnit.MILLISECONDS;
3031     case SECONDS:
3032       return TimeUnit.SECONDS;
3033     case MINUTES:
3034       return TimeUnit.MINUTES;
3035     case HOURS:
3036       return TimeUnit.HOURS;
3037     case DAYS:
3038       return TimeUnit.DAYS;
3039     default:
3040       throw new RuntimeException("Invalid TimeUnit " + proto);
3041     }
3042   }
3043 
3044   /**
3045    * Convert a client TimeUnit to a protocol buffer TimeUnit
3046    * @param timeUnit
3047    * @return the converted protocol buffer TimeUnit
3048    */
3049   public static HBaseProtos.TimeUnit toProtoTimeUnit(final TimeUnit timeUnit) {
3050     switch (timeUnit) {
3051     case NANOSECONDS:
3052       return HBaseProtos.TimeUnit.NANOSECONDS;
3053     case MICROSECONDS:
3054       return HBaseProtos.TimeUnit.MICROSECONDS;
3055     case MILLISECONDS:
3056       return HBaseProtos.TimeUnit.MILLISECONDS;
3057     case SECONDS:
3058       return HBaseProtos.TimeUnit.SECONDS;
3059     case MINUTES:
3060       return HBaseProtos.TimeUnit.MINUTES;
3061     case HOURS:
3062       return HBaseProtos.TimeUnit.HOURS;
3063     case DAYS:
3064       return HBaseProtos.TimeUnit.DAYS;
3065     default:
3066       throw new RuntimeException("Invalid TimeUnit " + timeUnit);
3067     }
3068   }
3069 
3070   /**
3071    * Convert a protocol buffer ThrottleType to a client ThrottleType
3072    * @param proto
3073    * @return the converted client ThrottleType
3074    */
3075   public static ThrottleType toThrottleType(final QuotaProtos.ThrottleType proto) {
3076     switch (proto) {
3077     case REQUEST_NUMBER:
3078       return ThrottleType.REQUEST_NUMBER;
3079     case REQUEST_SIZE:
3080       return ThrottleType.REQUEST_SIZE;
3081     case WRITE_NUMBER:
3082       return ThrottleType.WRITE_NUMBER;
3083     case WRITE_SIZE:
3084       return ThrottleType.WRITE_SIZE;
3085     case READ_NUMBER:
3086       return ThrottleType.READ_NUMBER;
3087     case READ_SIZE:
3088       return ThrottleType.READ_SIZE;
3089     default:
3090       throw new RuntimeException("Invalid ThrottleType " + proto);
3091     }
3092   }
3093 
3094   /**
3095    * Convert a client ThrottleType to a protocol buffer ThrottleType
3096    * @param type
3097    * @return the converted protocol buffer ThrottleType
3098    */
3099   public static QuotaProtos.ThrottleType toProtoThrottleType(final ThrottleType type) {
3100     switch (type) {
3101     case REQUEST_NUMBER:
3102       return QuotaProtos.ThrottleType.REQUEST_NUMBER;
3103     case REQUEST_SIZE:
3104       return QuotaProtos.ThrottleType.REQUEST_SIZE;
3105     case WRITE_NUMBER:
3106       return QuotaProtos.ThrottleType.WRITE_NUMBER;
3107     case WRITE_SIZE:
3108       return QuotaProtos.ThrottleType.WRITE_SIZE;
3109     case READ_NUMBER:
3110       return QuotaProtos.ThrottleType.READ_NUMBER;
3111     case READ_SIZE:
3112       return QuotaProtos.ThrottleType.READ_SIZE;
3113     default:
3114       throw new RuntimeException("Invalid ThrottleType " + type);
3115     }
3116   }
3117 
3118   /**
3119    * Convert a protocol buffer QuotaScope to a client QuotaScope
3120    * @param proto
3121    * @return the converted client QuotaScope
3122    */
3123   public static QuotaScope toQuotaScope(final QuotaProtos.QuotaScope proto) {
3124     switch (proto) {
3125     case CLUSTER:
3126       return QuotaScope.CLUSTER;
3127     case MACHINE:
3128       return QuotaScope.MACHINE;
3129     default:
3130       throw new RuntimeException("Invalid QuotaScope " + proto);
3131     }
3132   }
3133 
3134   /**
3135    * Convert a client QuotaScope to a protocol buffer QuotaScope
3136    * @param scope
3137    * @return the converted protocol buffer QuotaScope
3138    */
3139   public static QuotaProtos.QuotaScope toProtoQuotaScope(final QuotaScope scope) {
3140     switch (scope) {
3141     case CLUSTER:
3142       return QuotaProtos.QuotaScope.CLUSTER;
3143     case MACHINE:
3144       return QuotaProtos.QuotaScope.MACHINE;
3145     default:
3146       throw new RuntimeException("Invalid QuotaScope " + scope);
3147     }
3148   }
3149 
3150   /**
3151    * Convert a protocol buffer QuotaType to a client QuotaType
3152    * @param proto
3153    * @return the converted client QuotaType
3154    */
3155   public static QuotaType toQuotaScope(final QuotaProtos.QuotaType proto) {
3156     switch (proto) {
3157     case THROTTLE:
3158       return QuotaType.THROTTLE;
3159     default:
3160       throw new RuntimeException("Invalid QuotaType " + proto);
3161     }
3162   }
3163 
3164   /**
3165    * Convert a client QuotaType to a protocol buffer QuotaType
3166    * @param type
3167    * @return the converted protocol buffer QuotaType
3168    */
3169   public static QuotaProtos.QuotaType toProtoQuotaScope(final QuotaType type) {
3170     switch (type) {
3171     case THROTTLE:
3172       return QuotaProtos.QuotaType.THROTTLE;
3173     default:
3174       throw new RuntimeException("Invalid QuotaType " + type);
3175     }
3176   }
3177 
3178   /**
3179    * Build a protocol buffer TimedQuota
3180    * @param limit the allowed number of request/data per timeUnit
3181    * @param timeUnit the limit time unit
3182    * @param scope the quota scope
3183    * @return the protocol buffer TimedQuota
3184    */
3185   public static QuotaProtos.TimedQuota toTimedQuota(final long limit, final TimeUnit timeUnit,
3186       final QuotaScope scope) {
3187     return QuotaProtos.TimedQuota.newBuilder().setSoftLimit(limit)
3188         .setTimeUnit(toProtoTimeUnit(timeUnit)).setScope(toProtoQuotaScope(scope)).build();
3189   }
3190 
3191   /**
3192    * Generates a marker for the WAL so that we propagate the notion of a bulk region load
3193    * throughout the WAL.
3194    *
3195    * @param tableName         The tableName into which the bulk load is being imported into.
3196    * @param encodedRegionName Encoded region name of the region which is being bulk loaded.
3197    * @param storeFiles        A set of store files of a column family are bulk loaded.
3198    * @param storeFilesSize  Map of store files and their lengths
3199    * @param bulkloadSeqId     sequence ID (by a force flush) used to create bulk load hfile
3200    *                          name
3201    * @return The WAL log marker for bulk loads.
3202    */
3203   public static WALProtos.BulkLoadDescriptor toBulkLoadDescriptor(TableName tableName,
3204       ByteString encodedRegionName, Map<byte[], List<Path>> storeFiles,
3205       Map<String, Long> storeFilesSize, long bulkloadSeqId) {
3206     BulkLoadDescriptor.Builder desc =
3207         BulkLoadDescriptor.newBuilder()
3208         .setTableName(ProtobufUtil.toProtoTableName(tableName))
3209         .setEncodedRegionName(encodedRegionName).setBulkloadSeqNum(bulkloadSeqId);
3210 
3211     for (Map.Entry<byte[], List<Path>> entry : storeFiles.entrySet()) {
3212       WALProtos.StoreDescriptor.Builder builder = StoreDescriptor.newBuilder()
3213           .setFamilyName(ByteStringer.wrap(entry.getKey()))
3214           .setStoreHomeDir(Bytes.toString(entry.getKey())); // relative to region
3215       for (Path path : entry.getValue()) {
3216         String name = path.getName();
3217         builder.addStoreFile(name);
3218         Long size = storeFilesSize.get(name) == null ? (Long) 0L : storeFilesSize.get(name);
3219         builder.setStoreFileSizeBytes(size);
3220       }
3221       desc.addStores(builder);
3222     }
3223 
3224     return desc.build();
3225   }
3226 
3227   /**
3228    * This version of protobuf's mergeDelimitedFrom avoids the hard-coded 64MB limit for decoding
3229    * buffers
3230    * @param builder current message builder
3231    * @param in Inputsream with delimited protobuf data
3232    * @throws IOException
3233    */
3234   public static void mergeDelimitedFrom(Message.Builder builder, InputStream in)
3235     throws IOException {
3236     // This used to be builder.mergeDelimitedFrom(in);
3237     // but is replaced to allow us to bump the protobuf size limit.
3238     final int firstByte = in.read();
3239     if (firstByte != -1) {
3240       final int size = CodedInputStream.readRawVarint32(firstByte, in);
3241       final InputStream limitedInput = new LimitInputStream(in, size);
3242       final CodedInputStream codedInput = CodedInputStream.newInstance(limitedInput);
3243       codedInput.setSizeLimit(size);
3244       builder.mergeFrom(codedInput);
3245       codedInput.checkLastTagWas(0);
3246     }
3247   }
3248 
3249   /**
3250    * This version of protobuf's mergeFrom avoids the hard-coded 64MB limit for decoding
3251    * buffers where the message size is known
3252    * @param builder current message builder
3253    * @param in InputStream containing protobuf data
3254    * @param size known size of protobuf data
3255    * @throws IOException 
3256    */
3257   public static void mergeFrom(Message.Builder builder, InputStream in, int size)
3258       throws IOException {
3259     final CodedInputStream codedInput = CodedInputStream.newInstance(in);
3260     codedInput.setSizeLimit(size);
3261     builder.mergeFrom(codedInput);
3262     codedInput.checkLastTagWas(0);
3263   }
3264 
3265   /**
3266    * This version of protobuf's mergeFrom avoids the hard-coded 64MB limit for decoding
3267    * buffers where the message size is not known
3268    * @param builder current message builder
3269    * @param in InputStream containing protobuf data
3270    * @throws IOException 
3271    */
3272   public static void mergeFrom(Message.Builder builder, InputStream in)
3273       throws IOException {
3274     final CodedInputStream codedInput = CodedInputStream.newInstance(in);
3275     codedInput.setSizeLimit(Integer.MAX_VALUE);
3276     builder.mergeFrom(codedInput);
3277     codedInput.checkLastTagWas(0);
3278   }
3279 
3280   /**
3281    * This version of protobuf's mergeFrom avoids the hard-coded 64MB limit for decoding
3282    * buffers when working with ByteStrings
3283    * @param builder current message builder
3284    * @param bs ByteString containing the 
3285    * @throws IOException 
3286    */
3287   public static void mergeFrom(Message.Builder builder, ByteString bs) throws IOException {
3288     final CodedInputStream codedInput = bs.newCodedInput();
3289     codedInput.setSizeLimit(bs.size());
3290     builder.mergeFrom(codedInput);
3291     codedInput.checkLastTagWas(0);
3292   }
3293 
3294   /**
3295    * This version of protobuf's mergeFrom avoids the hard-coded 64MB limit for decoding
3296    * buffers when working with byte arrays
3297    * @param builder current message builder
3298    * @param b byte array
3299    * @throws IOException 
3300    */
3301   public static void mergeFrom(Message.Builder builder, byte[] b) throws IOException {
3302     final CodedInputStream codedInput = CodedInputStream.newInstance(b);
3303     codedInput.setSizeLimit(b.length);
3304     builder.mergeFrom(codedInput);
3305     codedInput.checkLastTagWas(0);
3306   }
3307 
3308   /**
3309    * This version of protobuf's mergeFrom avoids the hard-coded 64MB limit for decoding
3310    * buffers when working with byte arrays
3311    * @param builder current message builder
3312    * @param b byte array
3313    * @param offset
3314    * @param length
3315    * @throws IOException
3316    */
3317   public static void mergeFrom(Message.Builder builder, byte[] b, int offset, int length)
3318       throws IOException {
3319     final CodedInputStream codedInput = CodedInputStream.newInstance(b, offset, length);
3320     codedInput.setSizeLimit(length);
3321     builder.mergeFrom(codedInput);
3322     codedInput.checkLastTagWas(0);
3323   }
3324 
3325   public static void mergeFrom(Message.Builder builder, CodedInputStream codedInput, int length)
3326       throws IOException {
3327     codedInput.resetSizeCounter();
3328     int prevLimit = codedInput.setSizeLimit(length);
3329 
3330     int limit = codedInput.pushLimit(length);
3331     builder.mergeFrom(codedInput);
3332     codedInput.popLimit(limit);
3333 
3334     codedInput.checkLastTagWas(0);
3335     codedInput.setSizeLimit(prevLimit);
3336   }
3337 
3338   public static ReplicationLoadSink toReplicationLoadSink(
3339       ClusterStatusProtos.ReplicationLoadSink cls) {
3340     return new ReplicationLoadSink(cls.getAgeOfLastAppliedOp(), cls.getTimeStampsOfLastAppliedOp());
3341   }
3342 
3343   public static ReplicationLoadSource toReplicationLoadSource(
3344       ClusterStatusProtos.ReplicationLoadSource cls) {
3345     return new ReplicationLoadSource(cls.getPeerID(), cls.getAgeOfLastShippedOp(),
3346         cls.getSizeOfLogQueue(), cls.getTimeStampOfLastShippedOp(), cls.getReplicationLag());
3347   }
3348 
3349   public static List<ReplicationLoadSource> toReplicationLoadSourceList(
3350       List<ClusterStatusProtos.ReplicationLoadSource> clsList) {
3351     ArrayList<ReplicationLoadSource> rlsList = new ArrayList<ReplicationLoadSource>();
3352     for (ClusterStatusProtos.ReplicationLoadSource cls : clsList) {
3353       rlsList.add(toReplicationLoadSource(cls));
3354     }
3355     return rlsList;
3356   }
3357 
3358   /**
3359    * Get a protocol buffer VersionInfo
3360    *
3361    * @return the converted protocol buffer VersionInfo
3362    */
3363   public static HBaseProtos.VersionInfo getVersionInfo() {
3364     HBaseProtos.VersionInfo.Builder builder = HBaseProtos.VersionInfo.newBuilder();
3365     String version = VersionInfo.getVersion();
3366     builder.setVersion(version);
3367     String[] components = version.split("\\.");
3368     if (components != null && components.length > 2) {
3369       builder.setVersionMajor(Integer.parseInt(components[0]));
3370       builder.setVersionMinor(Integer.parseInt(components[1]));
3371     }
3372     builder.setUrl(VersionInfo.getUrl());
3373     builder.setRevision(VersionInfo.getRevision());
3374     builder.setUser(VersionInfo.getUser());
3375     builder.setDate(VersionInfo.getDate());
3376     builder.setSrcChecksum(VersionInfo.getSrcChecksum());
3377     return builder.build();
3378   }
3379 
3380   /**
3381    * Convert SecurityCapabilitiesResponse.Capability to SecurityCapability
3382    * @param capabilities capabilities returned in the SecurityCapabilitiesResponse message
3383    * @return the converted list of SecurityCapability elements
3384    */
3385   public static List<SecurityCapability> toSecurityCapabilityList(
3386       List<MasterProtos.SecurityCapabilitiesResponse.Capability> capabilities) {
3387     List<SecurityCapability> scList = new ArrayList<>(capabilities.size());
3388     for (MasterProtos.SecurityCapabilitiesResponse.Capability c: capabilities) {
3389       try {
3390         scList.add(SecurityCapability.valueOf(c.getNumber()));
3391       } catch (IllegalArgumentException e) {
3392         // Unknown capability, just ignore it. We don't understand the new capability
3393         // but don't care since by definition we cannot take advantage of it.
3394       }
3395     }
3396     return scList;
3397   }
3398 
3399   private static HBaseProtos.TimeRange.Builder timeRangeToProto(TimeRange timeRange) {
3400     HBaseProtos.TimeRange.Builder timeRangeBuilder =
3401         HBaseProtos.TimeRange.newBuilder();
3402     timeRangeBuilder.setFrom(timeRange.getMin());
3403     timeRangeBuilder.setTo(timeRange.getMax());
3404     return timeRangeBuilder;
3405   }
3406 
3407   private static TimeRange protoToTimeRange(HBaseProtos.TimeRange timeRange) throws IOException {
3408       long minStamp = 0;
3409       long maxStamp = Long.MAX_VALUE;
3410       if (timeRange.hasFrom()) {
3411         minStamp = timeRange.getFrom();
3412       }
3413       if (timeRange.hasTo()) {
3414         maxStamp = timeRange.getTo();
3415       }
3416     return new TimeRange(minStamp, maxStamp);
3417   }
3418 
3419 }