View Javadoc

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