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