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