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