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