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