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