View Javadoc

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