View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.protobuf;
19  
20  
21  import static org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier.RegionSpecifierType.REGION_NAME;
22  
23  import java.io.ByteArrayOutputStream;
24  import java.io.IOException;
25  import java.lang.reflect.Constructor;
26  import java.lang.reflect.InvocationTargetException;
27  import java.lang.reflect.Method;
28  import java.lang.reflect.ParameterizedType;
29  import java.lang.reflect.Type;
30  import java.util.ArrayList;
31  import java.util.Collection;
32  import java.util.HashMap;
33  import java.util.List;
34  import java.util.Map;
35  import java.util.Map.Entry;
36  import java.util.NavigableSet;
37  
38  import com.google.common.collect.ArrayListMultimap;
39  import com.google.common.collect.ListMultimap;
40  import com.google.common.collect.Lists;
41  import com.google.protobuf.ByteString;
42  import com.google.protobuf.InvalidProtocolBufferException;
43  import com.google.protobuf.Message;
44  import com.google.protobuf.RpcChannel;
45  import com.google.protobuf.Service;
46  import com.google.protobuf.ServiceException;
47  import com.google.protobuf.TextFormat;
48  
49  
50  import org.apache.hadoop.hbase.Cell;
51  import org.apache.hadoop.hbase.CellScanner;
52  import org.apache.hadoop.hbase.CellUtil;
53  import org.apache.hadoop.hbase.HConstants;
54  import org.apache.hadoop.hbase.HRegionInfo;
55  import org.apache.hadoop.hbase.HTableDescriptor;
56  import org.apache.hadoop.hbase.KeyValue;
57  import org.apache.hadoop.hbase.KeyValueUtil;
58  import org.apache.hadoop.hbase.MasterAdminProtocol;
59  import org.apache.hadoop.hbase.ServerName;
60  import org.apache.hadoop.hbase.client.AdminProtocol;
61  import org.apache.hadoop.hbase.client.Append;
62  import org.apache.hadoop.hbase.client.ClientProtocol;
63  import org.apache.hadoop.hbase.client.Delete;
64  import org.apache.hadoop.hbase.client.Get;
65  import org.apache.hadoop.hbase.client.Increment;
66  import org.apache.hadoop.hbase.client.Mutation;
67  import org.apache.hadoop.hbase.client.Put;
68  import org.apache.hadoop.hbase.client.Result;
69  import org.apache.hadoop.hbase.client.Scan;
70  import org.apache.hadoop.hbase.client.metrics.ScanMetrics;
71  import org.apache.hadoop.hbase.exceptions.DeserializationException;
72  import org.apache.hadoop.hbase.exceptions.DoNotRetryIOException;
73  import org.apache.hadoop.hbase.filter.ByteArrayComparable;
74  import org.apache.hadoop.hbase.filter.Filter;
75  import org.apache.hadoop.hbase.io.TimeRange;
76  import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos;
77  import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.AccessControlService;
78  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionRequest;
79  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.CloseRegionResponse;
80  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetOnlineRegionRequest;
81  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetOnlineRegionResponse;
82  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoRequest;
83  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetRegionInfoResponse;
84  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetServerInfoRequest;
85  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetServerInfoResponse;
86  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetStoreFileRequest;
87  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.GetStoreFileResponse;
88  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.MergeRegionsRequest;
89  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.OpenRegionRequest;
90  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.ServerInfo;
91  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos.SplitRegionRequest;
92  import org.apache.hadoop.hbase.protobuf.generated.AuthenticationProtos;
93  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
94  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.BulkLoadHFileRequest;
95  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.BulkLoadHFileResponse;
96  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.Column;
97  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceCall;
98  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceRequest;
99  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.CoprocessorServiceResponse;
100 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetRequest;
101 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.GetResponse;
102 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto;
103 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.ColumnValue;
104 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.ColumnValue.QualifierValue;
105 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.DeleteType;
106 import org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.MutationType;
107 import org.apache.hadoop.hbase.protobuf.generated.ComparatorProtos;
108 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos;
109 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.NameBytesPair;
110 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionInfo;
111 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionLoad;
112 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier;
113 import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.RegionSpecifier.RegionSpecifierType;
114 import org.apache.hadoop.hbase.protobuf.generated.MapReduceProtos;
115 import org.apache.hadoop.hbase.protobuf.generated.MasterAdminProtos.CreateTableRequest;
116 import org.apache.hadoop.hbase.protobuf.generated.MasterMonitorProtos.GetTableDescriptorsResponse;
117 import org.apache.hadoop.hbase.security.access.Permission;
118 import org.apache.hadoop.hbase.security.access.TablePermission;
119 import org.apache.hadoop.hbase.security.access.UserPermission;
120 import org.apache.hadoop.hbase.security.token.AuthenticationTokenIdentifier;
121 import org.apache.hadoop.hbase.util.Bytes;
122 import org.apache.hadoop.hbase.util.Methods;
123 import org.apache.hadoop.hbase.util.Pair;
124 import org.apache.hadoop.io.Text;
125 import org.apache.hadoop.security.token.Token;
126 
127 /**
128  * Protobufs utility.
129  */
130 public final class ProtobufUtil {
131 
132   private ProtobufUtil() {
133   }
134 
135   /**
136    * Primitive type to class mapping.
137    */
138   private final static Map<String, Class<?>>
139     PRIMITIVES = new HashMap<String, Class<?>>();
140 
141   static {
142     PRIMITIVES.put(Boolean.TYPE.getName(), Boolean.TYPE);
143     PRIMITIVES.put(Byte.TYPE.getName(), Byte.TYPE);
144     PRIMITIVES.put(Character.TYPE.getName(), Character.TYPE);
145     PRIMITIVES.put(Short.TYPE.getName(), Short.TYPE);
146     PRIMITIVES.put(Integer.TYPE.getName(), Integer.TYPE);
147     PRIMITIVES.put(Long.TYPE.getName(), Long.TYPE);
148     PRIMITIVES.put(Float.TYPE.getName(), Float.TYPE);
149     PRIMITIVES.put(Double.TYPE.getName(), Double.TYPE);
150     PRIMITIVES.put(Void.TYPE.getName(), Void.TYPE);
151   }
152 
153   /**
154    * Magic we put ahead of a serialized protobuf message.
155    * For example, all znode content is protobuf messages with the below magic
156    * for preamble.
157    */
158   public static final byte [] PB_MAGIC = new byte [] {'P', 'B', 'U', 'F'};
159   private static final String PB_MAGIC_STR = Bytes.toString(PB_MAGIC);
160 
161   /**
162    * Prepend the passed bytes with four bytes of magic, {@link #PB_MAGIC}, to flag what
163    * follows as a protobuf in hbase.  Prepend these bytes to all content written to znodes, etc.
164    * @param bytes Bytes to decorate
165    * @return The passed <code>bytes</codes> with magic prepended (Creates a new
166    * byte array that is <code>bytes.length</code> plus {@link #PB_MAGIC}.length.
167    */
168   public static byte [] prependPBMagic(final byte [] bytes) {
169     return Bytes.add(PB_MAGIC, bytes);
170   }
171 
172   /**
173    * @param bytes Bytes to check.
174    * @return True if passed <code>bytes</code> has {@link #PB_MAGIC} for a prefix.
175    */
176   public static boolean isPBMagicPrefix(final byte [] bytes) {
177     if (bytes == null || bytes.length < PB_MAGIC.length) return false;
178     return Bytes.compareTo(PB_MAGIC, 0, PB_MAGIC.length, bytes, 0, PB_MAGIC.length) == 0;
179   }
180 
181   /**
182    * @param bytes
183    * @throws DeserializationException if we are missing the pb magic prefix
184    */
185   public static void expectPBMagicPrefix(final byte [] bytes) throws DeserializationException {
186     if (!isPBMagicPrefix(bytes)) {
187       throw new DeserializationException("Missing pb magic " + PB_MAGIC_STR + " prefix");
188     }
189   }
190 
191   /**
192    * @return Length of {@link #PB_MAGIC}
193    */
194   public static int lengthOfPBMagic() {
195     return PB_MAGIC.length;
196   }
197 
198   /**
199    * Return the IOException thrown by the remote server wrapped in
200    * ServiceException as cause.
201    *
202    * @param se ServiceException that wraps IO exception thrown by the server
203    * @return Exception wrapped in ServiceException or
204    *   a new IOException that wraps the unexpected ServiceException.
205    */
206   public static IOException getRemoteException(ServiceException se) {
207     Throwable e = se.getCause();
208     if (e == null) {
209       return new IOException(se);
210     }
211     return e instanceof IOException ? (IOException) e : new IOException(se);
212   }
213 
214   /**
215    * Convert a ServerName to a protocol buffer ServerName
216    *
217    * @param serverName the ServerName to convert
218    * @return the converted protocol buffer ServerName
219    * @see #toServerName(org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.ServerName)
220    */
221   public static HBaseProtos.ServerName
222       toServerName(final ServerName serverName) {
223     if (serverName == null) return null;
224     HBaseProtos.ServerName.Builder builder =
225       HBaseProtos.ServerName.newBuilder();
226     builder.setHostName(serverName.getHostname());
227     if (serverName.getPort() >= 0) {
228       builder.setPort(serverName.getPort());
229     }
230     if (serverName.getStartcode() >= 0) {
231       builder.setStartCode(serverName.getStartcode());
232     }
233     return builder.build();
234   }
235 
236   /**
237    * Convert a protocol buffer ServerName to a ServerName
238    *
239    * @param proto the protocol buffer ServerName to convert
240    * @return the converted ServerName
241    */
242   public static ServerName toServerName(final HBaseProtos.ServerName proto) {
243     if (proto == null) return null;
244     String hostName = proto.getHostName();
245     long startCode = -1;
246     int port = -1;
247     if (proto.hasPort()) {
248       port = proto.getPort();
249     }
250     if (proto.hasStartCode()) {
251       startCode = proto.getStartCode();
252     }
253     return new ServerName(hostName, port, startCode);
254   }
255 
256   /**
257    * Get HTableDescriptor[] from GetTableDescriptorsResponse protobuf
258    *
259    * @param proto the GetTableDescriptorsResponse
260    * @return HTableDescriptor[]
261    */
262   public static HTableDescriptor[] getHTableDescriptorArray(GetTableDescriptorsResponse proto) {
263     if (proto == null) return null;
264 
265     HTableDescriptor[] ret = new HTableDescriptor[proto.getTableSchemaCount()];
266     for (int i = 0; i < proto.getTableSchemaCount(); ++i) {
267       ret[i] = HTableDescriptor.convert(proto.getTableSchema(i));
268     }
269     return ret;
270   }
271 
272   /**
273    * get the split keys in form "byte [][]" from a CreateTableRequest proto
274    *
275    * @param proto the CreateTableRequest
276    * @return the split keys
277    */
278   public static byte [][] getSplitKeysArray(final CreateTableRequest proto) {
279     byte [][] splitKeys = new byte[proto.getSplitKeysCount()][];
280     for (int i = 0; i < proto.getSplitKeysCount(); ++i) {
281       splitKeys[i] = proto.getSplitKeys(i).toByteArray();
282     }
283     return splitKeys;
284   }
285 
286   /**
287    * Convert a protocol buffer Get to a client Get
288    *
289    * @param proto the protocol buffer Get to convert
290    * @return the converted client Get
291    * @throws IOException
292    */
293   public static Get toGet(
294       final ClientProtos.Get proto) throws IOException {
295     if (proto == null) return null;
296     byte[] row = proto.getRow().toByteArray();
297     Get get = new Get(row);
298     if (proto.hasCacheBlocks()) {
299       get.setCacheBlocks(proto.getCacheBlocks());
300     }
301     if (proto.hasMaxVersions()) {
302       get.setMaxVersions(proto.getMaxVersions());
303     }
304     if (proto.hasStoreLimit()) {
305       get.setMaxResultsPerColumnFamily(proto.getStoreLimit());
306     }
307     if (proto.hasStoreOffset()) {
308       get.setRowOffsetPerColumnFamily(proto.getStoreOffset());
309     }
310     if (proto.hasTimeRange()) {
311       HBaseProtos.TimeRange timeRange = proto.getTimeRange();
312       long minStamp = 0;
313       long maxStamp = Long.MAX_VALUE;
314       if (timeRange.hasFrom()) {
315         minStamp = timeRange.getFrom();
316       }
317       if (timeRange.hasTo()) {
318         maxStamp = timeRange.getTo();
319       }
320       get.setTimeRange(minStamp, maxStamp);
321     }
322     if (proto.hasFilter()) {
323       HBaseProtos.Filter filter = proto.getFilter();
324       get.setFilter(ProtobufUtil.toFilter(filter));
325     }
326     for (NameBytesPair attribute: proto.getAttributeList()) {
327       get.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
328     }
329     if (proto.getColumnCount() > 0) {
330       for (Column column: proto.getColumnList()) {
331         byte[] family = column.getFamily().toByteArray();
332         if (column.getQualifierCount() > 0) {
333           for (ByteString qualifier: column.getQualifierList()) {
334             get.addColumn(family, qualifier.toByteArray());
335           }
336         } else {
337           get.addFamily(family);
338         }
339       }
340     }
341     return get;
342   }
343 
344   /**
345    * Convert a protocol buffer Mutate to a Put.
346    *
347    * @param proto The protocol buffer MutationProto to convert
348    * @return A client Put.
349    * @throws IOException
350    */
351   public static Put toPut(final MutationProto proto)
352   throws IOException {
353     return toPut(proto, null);
354   }
355 
356   /**
357    * Convert a protocol buffer Mutate to a Put.
358    *
359    * @param proto The protocol buffer MutationProto to convert
360    * @param cellScanner If non-null, the Cell data that goes with this proto.
361    * @return A client Put.
362    * @throws IOException
363    */
364   public static Put toPut(final MutationProto proto, final CellScanner cellScanner)
365   throws IOException {
366     // TODO: Server-side at least why do we convert back to the Client types?  Why not just pb it?
367     MutationType type = proto.getMutateType();
368     assert type == MutationType.PUT: type.name();
369     byte [] row = proto.hasRow()? proto.getRow().toByteArray(): null;
370     long timestamp = proto.hasTimestamp()? proto.getTimestamp(): HConstants.LATEST_TIMESTAMP;
371     Put put = null;
372     int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
373     if (cellCount > 0) {
374       // The proto has metadata only and the data is separate to be found in the cellScanner.
375       if (cellScanner == null) {
376         throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
377           TextFormat.shortDebugString(proto));
378       }
379       for (int i = 0; i < cellCount; i++) {
380         if (!cellScanner.advance()) {
381           throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
382             " no cell returned: " + TextFormat.shortDebugString(proto));
383         }
384         Cell cell = cellScanner.current();
385         if (put == null) {
386           put = new Put(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), timestamp);
387         }
388         put.add(KeyValueUtil.ensureKeyValue(cell));
389       }
390     } else {
391       put = new Put(row, timestamp);
392       // The proto has the metadata and the data itself
393       for (ColumnValue column: proto.getColumnValueList()) {
394         byte[] family = column.getFamily().toByteArray();
395         for (QualifierValue qv: column.getQualifierValueList()) {
396           byte[] qualifier = qv.getQualifier().toByteArray();
397           if (!qv.hasValue()) {
398             throw new DoNotRetryIOException(
399                 "Missing required field: qualifer value");
400           }
401           byte[] value = qv.getValue().toByteArray();
402           long ts = timestamp;
403           if (qv.hasTimestamp()) {
404             ts = qv.getTimestamp();
405           }
406           put.add(family, qualifier, ts, value);
407         }
408       }
409     }
410     put.setWriteToWAL(proto.getWriteToWAL());
411     for (NameBytesPair attribute: proto.getAttributeList()) {
412       put.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
413     }
414     return put;
415   }
416 
417   /**
418    * Convert a protocol buffer Mutate to a Delete
419    *
420    * @param proto the protocol buffer Mutate to convert
421    * @return the converted client Delete
422    * @throws IOException
423    */
424   public static Delete toDelete(final MutationProto proto)
425   throws IOException {
426     return toDelete(proto, null);
427   }
428 
429   /**
430    * Convert a protocol buffer Mutate to a Delete
431    *
432    * @param proto the protocol buffer Mutate to convert
433    * @param cellScanner if non-null, the data that goes with this delete.
434    * @return the converted client Delete
435    * @throws IOException
436    */
437   public static Delete toDelete(final MutationProto proto, final CellScanner cellScanner)
438   throws IOException {
439     MutationType type = proto.getMutateType();
440     assert type == MutationType.DELETE : type.name();
441     byte [] row = proto.hasRow()? proto.getRow().toByteArray(): null;
442     long timestamp = HConstants.LATEST_TIMESTAMP;
443     if (proto.hasTimestamp()) {
444       timestamp = proto.getTimestamp();
445     }
446     Delete delete = null;
447     int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
448     if (cellCount > 0) {
449       // The proto has metadata only and the data is separate to be found in the cellScanner.
450       if (cellScanner == null) {
451         throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
452           TextFormat.shortDebugString(proto));
453       }
454       for (int i = 0; i < cellCount; i++) {
455         if (!cellScanner.advance()) {
456           throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
457             " no cell returned: " + TextFormat.shortDebugString(proto));
458         }
459         Cell cell = cellScanner.current();
460         if (delete == null) {
461           delete =
462             new Delete(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), timestamp);
463         }
464         delete.addDeleteMarker(KeyValueUtil.ensureKeyValue(cell));
465       }
466     } else {
467       delete = new Delete(row, timestamp);
468       for (ColumnValue column: proto.getColumnValueList()) {
469         byte[] family = column.getFamily().toByteArray();
470         for (QualifierValue qv: column.getQualifierValueList()) {
471           DeleteType deleteType = qv.getDeleteType();
472           byte[] qualifier = null;
473           if (qv.hasQualifier()) {
474             qualifier = qv.getQualifier().toByteArray();
475           }
476           long ts = HConstants.LATEST_TIMESTAMP;
477           if (qv.hasTimestamp()) {
478             ts = qv.getTimestamp();
479           }
480           if (deleteType == DeleteType.DELETE_ONE_VERSION) {
481             delete.deleteColumn(family, qualifier, ts);
482           } else if (deleteType == DeleteType.DELETE_MULTIPLE_VERSIONS) {
483             delete.deleteColumns(family, qualifier, ts);
484           } else {
485             delete.deleteFamily(family, ts);
486           }
487         }
488       }
489     }
490     delete.setWriteToWAL(proto.getWriteToWAL());
491     for (NameBytesPair attribute: proto.getAttributeList()) {
492       delete.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
493     }
494     return delete;
495   }
496 
497   /**
498    * Convert a protocol buffer Mutate to an Append
499    * @param cellScanner
500    * @param proto the protocol buffer Mutate to convert
501    * @return the converted client Append
502    * @throws DoNotRetryIOException
503    */
504   public static Append toAppend(final MutationProto proto, final CellScanner cellScanner)
505   throws DoNotRetryIOException {
506     MutationType type = proto.getMutateType();
507     assert type == MutationType.APPEND : type.name();
508     byte [] row = proto.hasRow()? proto.getRow().toByteArray(): null;
509     Append append = null;
510     int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
511     if (cellCount > 0) {
512       // The proto has metadata only and the data is separate to be found in the cellScanner.
513       if (cellScanner == null) {
514         throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
515           TextFormat.shortDebugString(proto));
516       }
517       for (int i = 0; i < cellCount; i++) {
518         if (!cellScanner.advance()) {
519           throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
520             " no cell returned: " + TextFormat.shortDebugString(proto));
521         }
522         Cell cell = cellScanner.current();
523         if (append == null) {
524           append = new Append(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
525         }
526         append.add(KeyValueUtil.ensureKeyValue(cell));
527       }
528     } else {
529       append = new Append(row);
530       for (ColumnValue column: proto.getColumnValueList()) {
531         byte[] family = column.getFamily().toByteArray();
532         for (QualifierValue qv: column.getQualifierValueList()) {
533           byte[] qualifier = qv.getQualifier().toByteArray();
534           if (!qv.hasValue()) {
535             throw new DoNotRetryIOException(
536               "Missing required field: qualifer value");
537           }
538           byte[] value = qv.getValue().toByteArray();
539           append.add(family, qualifier, value);
540         }
541       }
542     }
543     append.setWriteToWAL(proto.getWriteToWAL());
544     for (NameBytesPair attribute: proto.getAttributeList()) {
545       append.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
546     }
547     return append;
548   }
549 
550   /**
551    * Convert a MutateRequest to Mutation
552    *
553    * @param proto the protocol buffer Mutate to convert
554    * @return the converted Mutation
555    * @throws IOException
556    */
557   public static Mutation toMutation(final MutationProto proto) throws IOException {
558     MutationType type = proto.getMutateType();
559     if (type == MutationType.APPEND) {
560       return toAppend(proto, null);
561     }
562     if (type == MutationType.DELETE) {
563       return toDelete(proto, null);
564     }
565     if (type == MutationType.PUT) {
566       return toPut(proto, null);
567     }
568     throw new IOException("Unknown mutation type " + type);
569   }
570 
571   /**
572    * Convert a protocol buffer Mutate to an Increment
573    *
574    * @param proto the protocol buffer Mutate to convert
575    * @return the converted client Increment
576    * @throws IOException
577    */
578   public static Increment toIncrement(final MutationProto proto, final CellScanner cellScanner)
579   throws IOException {
580     MutationType type = proto.getMutateType();
581     assert type == MutationType.INCREMENT : type.name();
582     byte [] row = proto.hasRow()? proto.getRow().toByteArray(): null;
583     Increment increment = null;
584     int cellCount = proto.hasAssociatedCellCount()? proto.getAssociatedCellCount(): 0;
585     if (cellCount > 0) {
586       // The proto has metadata only and the data is separate to be found in the cellScanner.
587       if (cellScanner == null) {
588         throw new DoNotRetryIOException("Cell count of " + cellCount + " but no cellScanner: " +
589           TextFormat.shortDebugString(proto));
590       }
591       for (int i = 0; i < cellCount; i++) {
592         if (!cellScanner.advance()) {
593           throw new DoNotRetryIOException("Cell count of " + cellCount + " but at index " + i +
594             " no cell returned: " + TextFormat.shortDebugString(proto));
595         }
596         Cell cell = cellScanner.current();
597         if (increment == null) {
598           increment = new Increment(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
599         }
600         increment.add(KeyValueUtil.ensureKeyValue(cell));
601       }
602     } else {
603       increment = new Increment(row);
604       for (ColumnValue column: proto.getColumnValueList()) {
605         byte[] family = column.getFamily().toByteArray();
606         for (QualifierValue qv: column.getQualifierValueList()) {
607           byte[] qualifier = qv.getQualifier().toByteArray();
608           if (!qv.hasValue()) {
609             throw new DoNotRetryIOException("Missing required field: qualifer value");
610           }
611           long value = Bytes.toLong(qv.getValue().toByteArray());
612           increment.addColumn(family, qualifier, value);
613         }
614       }
615     }
616     if (proto.hasTimeRange()) {
617       HBaseProtos.TimeRange timeRange = proto.getTimeRange();
618       long minStamp = 0;
619       long maxStamp = Long.MAX_VALUE;
620       if (timeRange.hasFrom()) {
621         minStamp = timeRange.getFrom();
622       }
623       if (timeRange.hasTo()) {
624         maxStamp = timeRange.getTo();
625       }
626       increment.setTimeRange(minStamp, maxStamp);
627     }
628     increment.setWriteToWAL(proto.getWriteToWAL());
629     return increment;
630   }
631 
632   /**
633    * Convert a client Scan to a protocol buffer Scan
634    *
635    * @param scan the client Scan to convert
636    * @return the converted protocol buffer Scan
637    * @throws IOException
638    */
639   public static ClientProtos.Scan toScan(
640       final Scan scan) throws IOException {
641     ClientProtos.Scan.Builder scanBuilder =
642       ClientProtos.Scan.newBuilder();
643     scanBuilder.setCacheBlocks(scan.getCacheBlocks());
644     if (scan.getBatch() > 0) {
645       scanBuilder.setBatchSize(scan.getBatch());
646     }
647     if (scan.getMaxResultSize() > 0) {
648       scanBuilder.setMaxResultSize(scan.getMaxResultSize());
649     }
650     Boolean loadColumnFamiliesOnDemand = scan.getLoadColumnFamiliesOnDemandValue();
651     if (loadColumnFamiliesOnDemand != null) {
652       scanBuilder.setLoadColumnFamiliesOnDemand(loadColumnFamiliesOnDemand.booleanValue());
653     }
654     scanBuilder.setMaxVersions(scan.getMaxVersions());
655     TimeRange timeRange = scan.getTimeRange();
656     if (!timeRange.isAllTime()) {
657       HBaseProtos.TimeRange.Builder timeRangeBuilder =
658         HBaseProtos.TimeRange.newBuilder();
659       timeRangeBuilder.setFrom(timeRange.getMin());
660       timeRangeBuilder.setTo(timeRange.getMax());
661       scanBuilder.setTimeRange(timeRangeBuilder.build());
662     }
663     Map<String, byte[]> attributes = scan.getAttributesMap();
664     if (!attributes.isEmpty()) {
665       NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
666       for (Map.Entry<String, byte[]> attribute: attributes.entrySet()) {
667         attributeBuilder.setName(attribute.getKey());
668         attributeBuilder.setValue(ByteString.copyFrom(attribute.getValue()));
669         scanBuilder.addAttribute(attributeBuilder.build());
670       }
671     }
672     byte[] startRow = scan.getStartRow();
673     if (startRow != null && startRow.length > 0) {
674       scanBuilder.setStartRow(ByteString.copyFrom(startRow));
675     }
676     byte[] stopRow = scan.getStopRow();
677     if (stopRow != null && stopRow.length > 0) {
678       scanBuilder.setStopRow(ByteString.copyFrom(stopRow));
679     }
680     if (scan.hasFilter()) {
681       scanBuilder.setFilter(ProtobufUtil.toFilter(scan.getFilter()));
682     }
683     if (scan.hasFamilies()) {
684       Column.Builder columnBuilder = Column.newBuilder();
685       for (Map.Entry<byte[],NavigableSet<byte []>>
686           family: scan.getFamilyMap().entrySet()) {
687         columnBuilder.setFamily(ByteString.copyFrom(family.getKey()));
688         NavigableSet<byte []> qualifiers = family.getValue();
689         columnBuilder.clearQualifier();
690         if (qualifiers != null && qualifiers.size() > 0) {
691           for (byte [] qualifier: qualifiers) {
692             columnBuilder.addQualifier(ByteString.copyFrom(qualifier));
693           }
694         }
695         scanBuilder.addColumn(columnBuilder.build());
696       }
697     }
698     if (scan.getMaxResultsPerColumnFamily() >= 0) {
699       scanBuilder.setStoreLimit(scan.getMaxResultsPerColumnFamily());
700     }
701     if (scan.getRowOffsetPerColumnFamily() > 0) {
702       scanBuilder.setStoreOffset(scan.getRowOffsetPerColumnFamily());
703     }
704     return scanBuilder.build();
705   }
706 
707   /**
708    * Convert a protocol buffer Scan to a client Scan
709    *
710    * @param proto the protocol buffer Scan to convert
711    * @return the converted client Scan
712    * @throws IOException
713    */
714   public static Scan toScan(
715       final ClientProtos.Scan proto) throws IOException {
716     byte [] startRow = HConstants.EMPTY_START_ROW;
717     byte [] stopRow  = HConstants.EMPTY_END_ROW;
718     if (proto.hasStartRow()) {
719       startRow = proto.getStartRow().toByteArray();
720     }
721     if (proto.hasStopRow()) {
722       stopRow = proto.getStopRow().toByteArray();
723     }
724     Scan scan = new Scan(startRow, stopRow);
725     if (proto.hasCacheBlocks()) {
726       scan.setCacheBlocks(proto.getCacheBlocks());
727     }
728     if (proto.hasMaxVersions()) {
729       scan.setMaxVersions(proto.getMaxVersions());
730     }
731     if (proto.hasStoreLimit()) {
732       scan.setMaxResultsPerColumnFamily(proto.getStoreLimit());
733     }
734     if (proto.hasStoreOffset()) {
735       scan.setRowOffsetPerColumnFamily(proto.getStoreOffset());
736     }
737     if (proto.hasLoadColumnFamiliesOnDemand()) {
738       scan.setLoadColumnFamiliesOnDemand(proto.getLoadColumnFamiliesOnDemand());
739     }
740     if (proto.hasTimeRange()) {
741       HBaseProtos.TimeRange timeRange = proto.getTimeRange();
742       long minStamp = 0;
743       long maxStamp = Long.MAX_VALUE;
744       if (timeRange.hasFrom()) {
745         minStamp = timeRange.getFrom();
746       }
747       if (timeRange.hasTo()) {
748         maxStamp = timeRange.getTo();
749       }
750       scan.setTimeRange(minStamp, maxStamp);
751     }
752     if (proto.hasFilter()) {
753       HBaseProtos.Filter filter = proto.getFilter();
754       scan.setFilter(ProtobufUtil.toFilter(filter));
755     }
756     if (proto.hasBatchSize()) {
757       scan.setBatch(proto.getBatchSize());
758     }
759     if (proto.hasMaxResultSize()) {
760       scan.setMaxResultSize(proto.getMaxResultSize());
761     }
762     for (NameBytesPair attribute: proto.getAttributeList()) {
763       scan.setAttribute(attribute.getName(), attribute.getValue().toByteArray());
764     }
765     if (proto.getColumnCount() > 0) {
766       for (Column column: proto.getColumnList()) {
767         byte[] family = column.getFamily().toByteArray();
768         if (column.getQualifierCount() > 0) {
769           for (ByteString qualifier: column.getQualifierList()) {
770             scan.addColumn(family, qualifier.toByteArray());
771           }
772         } else {
773           scan.addFamily(family);
774         }
775       }
776     }
777     return scan;
778   }
779 
780   /**
781    * Create a protocol buffer Get based on a client Get.
782    *
783    * @param get the client Get
784    * @return a protocol buffer Get
785    * @throws IOException
786    */
787   public static ClientProtos.Get toGet(
788       final Get get) throws IOException {
789     ClientProtos.Get.Builder builder =
790       ClientProtos.Get.newBuilder();
791     builder.setRow(ByteString.copyFrom(get.getRow()));
792     builder.setCacheBlocks(get.getCacheBlocks());
793     builder.setMaxVersions(get.getMaxVersions());
794     if (get.getFilter() != null) {
795       builder.setFilter(ProtobufUtil.toFilter(get.getFilter()));
796     }
797     TimeRange timeRange = get.getTimeRange();
798     if (!timeRange.isAllTime()) {
799       HBaseProtos.TimeRange.Builder timeRangeBuilder =
800         HBaseProtos.TimeRange.newBuilder();
801       timeRangeBuilder.setFrom(timeRange.getMin());
802       timeRangeBuilder.setTo(timeRange.getMax());
803       builder.setTimeRange(timeRangeBuilder.build());
804     }
805     Map<String, byte[]> attributes = get.getAttributesMap();
806     if (!attributes.isEmpty()) {
807       NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
808       for (Map.Entry<String, byte[]> attribute: attributes.entrySet()) {
809         attributeBuilder.setName(attribute.getKey());
810         attributeBuilder.setValue(ByteString.copyFrom(attribute.getValue()));
811         builder.addAttribute(attributeBuilder.build());
812       }
813     }
814     if (get.hasFamilies()) {
815       Column.Builder columnBuilder = Column.newBuilder();
816       Map<byte[], NavigableSet<byte[]>> families = get.getFamilyMap();
817       for (Map.Entry<byte[], NavigableSet<byte[]>> family: families.entrySet()) {
818         NavigableSet<byte[]> qualifiers = family.getValue();
819         columnBuilder.setFamily(ByteString.copyFrom(family.getKey()));
820         columnBuilder.clearQualifier();
821         if (qualifiers != null && qualifiers.size() > 0) {
822           for (byte[] qualifier: qualifiers) {
823             columnBuilder.addQualifier(ByteString.copyFrom(qualifier));
824           }
825         }
826         builder.addColumn(columnBuilder.build());
827       }
828     }
829     if (get.getMaxResultsPerColumnFamily() >= 0) {
830       builder.setStoreLimit(get.getMaxResultsPerColumnFamily());
831     }
832     if (get.getRowOffsetPerColumnFamily() > 0) {
833       builder.setStoreOffset(get.getRowOffsetPerColumnFamily());
834     }
835     return builder.build();
836   }
837 
838   /**
839    * Convert a client Increment to a protobuf Mutate.
840    *
841    * @param increment
842    * @return the converted mutate
843    */
844   public static MutationProto toMutation(final Increment increment) {
845     MutationProto.Builder builder = MutationProto.newBuilder();
846     builder.setRow(ByteString.copyFrom(increment.getRow()));
847     builder.setMutateType(MutationType.INCREMENT);
848     builder.setWriteToWAL(increment.getWriteToWAL());
849     TimeRange timeRange = increment.getTimeRange();
850     if (!timeRange.isAllTime()) {
851       HBaseProtos.TimeRange.Builder timeRangeBuilder =
852         HBaseProtos.TimeRange.newBuilder();
853       timeRangeBuilder.setFrom(timeRange.getMin());
854       timeRangeBuilder.setTo(timeRange.getMax());
855       builder.setTimeRange(timeRangeBuilder.build());
856     }
857     ColumnValue.Builder columnBuilder = ColumnValue.newBuilder();
858     QualifierValue.Builder valueBuilder = QualifierValue.newBuilder();
859    for (Map.Entry<byte[], List<? extends Cell>> family: increment.getFamilyMap().entrySet()) {
860       columnBuilder.setFamily(ByteString.copyFrom(family.getKey()));
861       columnBuilder.clearQualifierValue();
862       List<? extends Cell> values = family.getValue();
863       if (values != null && values.size() > 0) {
864         for (Cell cell: values) {
865           KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
866           valueBuilder.setQualifier(ByteString.copyFrom(kv.getQualifier()));
867           valueBuilder.setValue(ByteString.copyFrom(kv.getValue()));
868           columnBuilder.addQualifierValue(valueBuilder.build());
869         }
870       }
871       builder.addColumnValue(columnBuilder.build());
872     }
873     return builder.build();
874   }
875 
876   /**
877    * Create a protocol buffer Mutate based on a client Mutation
878    *
879    * @param type
880    * @param mutation
881    * @return a protobuf'd Mutation
882    * @throws IOException
883    */
884   public static MutationProto toMutation(final MutationType type, final Mutation mutation)
885   throws IOException {
886     MutationProto.Builder builder = getMutationBuilderAndSetCommonFields(type, mutation);
887     ColumnValue.Builder columnBuilder = ColumnValue.newBuilder();
888     QualifierValue.Builder valueBuilder = QualifierValue.newBuilder();
889     for (Map.Entry<byte[],List<? extends Cell>> family: mutation.getFamilyMap().entrySet()) {
890       columnBuilder.setFamily(ByteString.copyFrom(family.getKey()));
891       columnBuilder.clearQualifierValue();
892       for (Cell cell: family.getValue()) {
893         KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
894         valueBuilder.setQualifier(ByteString.copyFrom(kv.getQualifier()));
895         valueBuilder.setValue(ByteString.copyFrom(kv.getValue()));
896         valueBuilder.setTimestamp(kv.getTimestamp());
897         if (type == MutationType.DELETE) {
898           KeyValue.Type keyValueType = KeyValue.Type.codeToType(kv.getType());
899           valueBuilder.setDeleteType(toDeleteType(keyValueType));
900         }
901         columnBuilder.addQualifierValue(valueBuilder.build());
902       }
903       builder.addColumnValue(columnBuilder.build());
904     }
905     return builder.build();
906   }
907 
908   /**
909    * Create a protocol buffer MutationProto based on a client Mutation.  Does NOT include data.
910    * Understanding is that the Cell will be transported other than via protobuf.
911    * @param type
912    * @param mutation
913    * @return a protobuf'd Mutation
914    * @throws IOException
915    */
916   public static MutationProto toMutationNoData(final MutationType type, final Mutation mutation)
917   throws IOException {
918     MutationProto.Builder builder = getMutationBuilderAndSetCommonFields(type, mutation);
919     builder.setAssociatedCellCount(mutation.size());
920     return builder.build();
921   }
922 
923   /**
924    * Code shared by {@link #toMutation(MutationType, Mutation)} and
925    * {@link #toMutationNoData(MutationType, Mutation)}
926    * @param type
927    * @param mutation
928    * @return A partly-filled out protobuf'd Mutation.
929    */
930   private static MutationProto.Builder getMutationBuilderAndSetCommonFields(final MutationType type,
931       final Mutation mutation) {
932     MutationProto.Builder builder = MutationProto.newBuilder();
933     builder.setRow(ByteString.copyFrom(mutation.getRow()));
934     builder.setMutateType(type);
935     builder.setWriteToWAL(mutation.getWriteToWAL());
936     builder.setTimestamp(mutation.getTimeStamp());
937     Map<String, byte[]> attributes = mutation.getAttributesMap();
938     if (!attributes.isEmpty()) {
939       NameBytesPair.Builder attributeBuilder = NameBytesPair.newBuilder();
940       for (Map.Entry<String, byte[]> attribute: attributes.entrySet()) {
941         attributeBuilder.setName(attribute.getKey());
942         attributeBuilder.setValue(ByteString.copyFrom(attribute.getValue()));
943         builder.addAttribute(attributeBuilder.build());
944       }
945     }
946     return builder;
947   }
948 
949   /**
950    * Convert a client Result to a protocol buffer Result
951    *
952    * @param result the client Result to convert
953    * @return the converted protocol buffer Result
954    */
955   public static ClientProtos.Result toResult(final Result result) {
956     ClientProtos.Result.Builder builder = ClientProtos.Result.newBuilder();
957     Cell [] cells = result.raw();
958     if (cells != null) {
959       for (Cell c : cells) {
960         builder.addCell(toCell(c));
961       }
962     }
963     return builder.build();
964   }
965 
966   /**
967    * Convert a client Result to a protocol buffer Result.
968    * The pb Result does not include the Cell data.  That is for transport otherwise.
969    *
970    * @param result the client Result to convert
971    * @return the converted protocol buffer Result
972    */
973   public static ClientProtos.Result toResultNoData(final Result result) {
974     ClientProtos.Result.Builder builder = ClientProtos.Result.newBuilder();
975     builder.setAssociatedCellCount(result.size());
976     return builder.build();
977   }
978 
979   /**
980    * Convert a protocol buffer Result to a client Result
981    *
982    * @param proto the protocol buffer Result to convert
983    * @return the converted client Result
984    */
985   public static Result toResult(final ClientProtos.Result proto) {
986     List<HBaseProtos.Cell> values = proto.getCellList();
987     List<Cell> cells = new ArrayList<Cell>(values.size());
988     for (HBaseProtos.Cell c: values) {
989       cells.add(toCell(c));
990     }
991     return new Result(cells);
992   }
993 
994   /**
995    * Convert a protocol buffer Result to a client Result
996    *
997    * @param proto the protocol buffer Result to convert
998    * @param scanner Optional cell scanner.
999    * @return the converted client Result
1000    * @throws IOException
1001    */
1002   public static Result toResult(final ClientProtos.Result proto, final CellScanner scanner)
1003   throws IOException {
1004     // TODO: Unit test that has some Cells in scanner and some in the proto.
1005     List<Cell> cells = null;
1006     if (proto.hasAssociatedCellCount()) {
1007       int count = proto.getAssociatedCellCount();
1008       cells = new ArrayList<Cell>(count);
1009       for (int i = 0; i < count; i++) {
1010         if (!scanner.advance()) throw new IOException("Failed get " + i + " of " + count);
1011         cells.add(scanner.current());
1012       }
1013     }
1014     List<HBaseProtos.Cell> values = proto.getCellList();
1015     if (cells == null) cells = new ArrayList<Cell>(values.size());
1016     for (HBaseProtos.Cell c: values) {
1017       cells.add(toCell(c));
1018     }
1019     return new Result(cells);
1020   }
1021 
1022   /**
1023    * Convert a ByteArrayComparable to a protocol buffer Comparator
1024    *
1025    * @param comparator the ByteArrayComparable to convert
1026    * @return the converted protocol buffer Comparator
1027    */
1028   public static ComparatorProtos.Comparator toComparator(ByteArrayComparable comparator) {
1029     ComparatorProtos.Comparator.Builder builder = ComparatorProtos.Comparator.newBuilder();
1030     builder.setName(comparator.getClass().getName());
1031     builder.setSerializedComparator(ByteString.copyFrom(comparator.toByteArray()));
1032     return builder.build();
1033   }
1034 
1035   /**
1036    * Convert a protocol buffer Comparator to a ByteArrayComparable
1037    *
1038    * @param proto the protocol buffer Comparator to convert
1039    * @return the converted ByteArrayComparable
1040    */
1041   @SuppressWarnings("unchecked")
1042   public static ByteArrayComparable toComparator(ComparatorProtos.Comparator proto)
1043   throws IOException {
1044     String type = proto.getName();
1045     String funcName = "parseFrom";
1046     byte [] value = proto.getSerializedComparator().toByteArray();
1047     try {
1048       Class<? extends ByteArrayComparable> c =
1049         (Class<? extends ByteArrayComparable>)(Class.forName(type));
1050       Method parseFrom = c.getMethod(funcName, byte[].class);
1051       if (parseFrom == null) {
1052         throw new IOException("Unable to locate function: " + funcName + " in type: " + type);
1053       }
1054       return (ByteArrayComparable)parseFrom.invoke(null, value);
1055     } catch (Exception e) {
1056       throw new IOException(e);
1057     }
1058   }
1059 
1060   /**
1061    * Convert a protocol buffer Filter to a client Filter
1062    *
1063    * @param proto the protocol buffer Filter to convert
1064    * @return the converted Filter
1065    */
1066   @SuppressWarnings("unchecked")
1067   public static Filter toFilter(HBaseProtos.Filter proto) throws IOException {
1068     String type = proto.getName();
1069     final byte [] value = proto.getSerializedFilter().toByteArray();
1070     String funcName = "parseFrom";
1071     try {
1072       Class<? extends Filter> c =
1073         (Class<? extends Filter>)Class.forName(type);
1074       Method parseFrom = c.getMethod(funcName, byte[].class);
1075       if (parseFrom == null) {
1076         throw new IOException("Unable to locate function: " + funcName + " in type: " + type);
1077       }
1078       return (Filter)parseFrom.invoke(c, value);
1079     } catch (Exception e) {
1080       throw new IOException(e);
1081     }
1082   }
1083 
1084   /**
1085    * Convert a client Filter to a protocol buffer Filter
1086    *
1087    * @param filter the Filter to convert
1088    * @return the converted protocol buffer Filter
1089    */
1090   public static HBaseProtos.Filter toFilter(Filter filter) throws IOException {
1091     HBaseProtos.Filter.Builder builder = HBaseProtos.Filter.newBuilder();
1092     builder.setName(filter.getClass().getName());
1093     builder.setSerializedFilter(ByteString.copyFrom(filter.toByteArray()));
1094     return builder.build();
1095   }
1096 
1097   /**
1098    * Convert a delete KeyValue type to protocol buffer DeleteType.
1099    *
1100    * @param type
1101    * @return protocol buffer DeleteType
1102    * @throws IOException
1103    */
1104   public static DeleteType toDeleteType(
1105       KeyValue.Type type) throws IOException {
1106     switch (type) {
1107     case Delete:
1108       return DeleteType.DELETE_ONE_VERSION;
1109     case DeleteColumn:
1110       return DeleteType.DELETE_MULTIPLE_VERSIONS;
1111     case DeleteFamily:
1112       return DeleteType.DELETE_FAMILY;
1113       default:
1114         throw new IOException("Unknown delete type: " + type);
1115     }
1116   }
1117 
1118   /**
1119    * Convert a stringified protocol buffer exception Parameter to a Java Exception
1120    *
1121    * @param parameter the protocol buffer Parameter to convert
1122    * @return the converted Exception
1123    * @throws IOException if failed to deserialize the parameter
1124    */
1125   @SuppressWarnings("unchecked")
1126   public static Throwable toException(
1127       final NameBytesPair parameter) throws IOException {
1128     if (parameter == null || !parameter.hasValue()) return null;
1129     String desc = parameter.getValue().toStringUtf8();
1130     String type = parameter.getName();
1131     try {
1132       Class<? extends Throwable> c =
1133         (Class<? extends Throwable>)Class.forName(type);
1134       Constructor<? extends Throwable> cn =
1135         c.getDeclaredConstructor(String.class);
1136       return cn.newInstance(desc);
1137     } catch (Exception e) {
1138       throw new IOException(e);
1139     }
1140   }
1141 
1142 // Start helpers for Client
1143 
1144   /**
1145    * A helper to invoke a Get using client protocol.
1146    *
1147    * @param client
1148    * @param regionName
1149    * @param get
1150    * @return the result of the Get
1151    * @throws IOException
1152    */
1153   public static Result get(final ClientProtocol client,
1154       final byte[] regionName, final Get get) throws IOException {
1155     GetRequest request =
1156       RequestConverter.buildGetRequest(regionName, get);
1157     try {
1158       GetResponse response = client.get(null, request);
1159       if (response == null) return null;
1160       return toResult(response.getResult());
1161     } catch (ServiceException se) {
1162       throw getRemoteException(se);
1163     }
1164   }
1165 
1166   /**
1167    * A helper to get a row of the closet one before using client protocol.
1168    *
1169    * @param client
1170    * @param regionName
1171    * @param row
1172    * @param family
1173    * @return the row or the closestRowBefore if it doesn't exist
1174    * @throws IOException
1175    */
1176   public static Result getRowOrBefore(final ClientProtocol client,
1177       final byte[] regionName, final byte[] row,
1178       final byte[] family) throws IOException {
1179     GetRequest request =
1180       RequestConverter.buildGetRowOrBeforeRequest(
1181         regionName, row, family);
1182     try {
1183       GetResponse response = client.get(null, request);
1184       if (!response.hasResult()) return null;
1185       return toResult(response.getResult());
1186     } catch (ServiceException se) {
1187       throw getRemoteException(se);
1188     }
1189   }
1190 
1191   /**
1192    * A helper to bulk load a list of HFiles using client protocol.
1193    *
1194    * @param client
1195    * @param familyPaths
1196    * @param regionName
1197    * @param assignSeqNum
1198    * @return true if all are loaded
1199    * @throws IOException
1200    */
1201   public static boolean bulkLoadHFile(final ClientProtocol client,
1202       final List<Pair<byte[], String>> familyPaths,
1203       final byte[] regionName, boolean assignSeqNum) throws IOException {
1204     BulkLoadHFileRequest request =
1205       RequestConverter.buildBulkLoadHFileRequest(familyPaths, regionName, assignSeqNum);
1206     try {
1207       BulkLoadHFileResponse response =
1208         client.bulkLoadHFile(null, request);
1209       return response.getLoaded();
1210     } catch (ServiceException se) {
1211       throw getRemoteException(se);
1212     }
1213   }
1214 
1215   public static CoprocessorServiceResponse execService(final ClientProtocol client,
1216       final CoprocessorServiceCall call, final byte[] regionName) throws IOException {
1217     CoprocessorServiceRequest request = CoprocessorServiceRequest.newBuilder()
1218         .setCall(call).setRegion(
1219             RequestConverter.buildRegionSpecifier(REGION_NAME, regionName)).build();
1220     try {
1221       CoprocessorServiceResponse response =
1222           client.execService(null, request);
1223       return response;
1224     } catch (ServiceException se) {
1225       throw getRemoteException(se);
1226     }
1227   }
1228 
1229   public static CoprocessorServiceResponse execService(final MasterAdminProtocol client,
1230       final CoprocessorServiceCall call) throws IOException {
1231     CoprocessorServiceRequest request = CoprocessorServiceRequest.newBuilder()
1232         .setCall(call).setRegion(
1233             RequestConverter.buildRegionSpecifier(REGION_NAME, HConstants.EMPTY_BYTE_ARRAY)).build();
1234     try {
1235       CoprocessorServiceResponse response =
1236           client.execMasterService(null, request);
1237       return response;
1238     } catch (ServiceException se) {
1239       throw getRemoteException(se);
1240     }
1241   }
1242 
1243   @SuppressWarnings("unchecked")
1244   public static <T extends Service> T newServiceStub(Class<T> service, RpcChannel channel)
1245       throws Exception {
1246     return (T)Methods.call(service, null, "newStub",
1247         new Class[]{ RpcChannel.class }, new Object[]{ channel });
1248   }
1249 
1250 // End helpers for Client
1251 // Start helpers for Admin
1252 
1253   /**
1254    * A helper to retrieve region info given a region name
1255    * using admin protocol.
1256    *
1257    * @param admin
1258    * @param regionName
1259    * @return the retrieved region info
1260    * @throws IOException
1261    */
1262   public static HRegionInfo getRegionInfo(final AdminProtocol admin,
1263       final byte[] regionName) throws IOException {
1264     try {
1265       GetRegionInfoRequest request =
1266         RequestConverter.buildGetRegionInfoRequest(regionName);
1267       GetRegionInfoResponse response =
1268         admin.getRegionInfo(null, request);
1269       return HRegionInfo.convert(response.getRegionInfo());
1270     } catch (ServiceException se) {
1271       throw getRemoteException(se);
1272     }
1273   }
1274 
1275   /**
1276    * A helper to close a region given a region name
1277    * using admin protocol.
1278    *
1279    * @param admin
1280    * @param regionName
1281    * @param transitionInZK
1282    * @throws IOException
1283    */
1284   public static void closeRegion(final AdminProtocol admin,
1285       final byte[] regionName, final boolean transitionInZK) throws IOException {
1286     CloseRegionRequest closeRegionRequest =
1287       RequestConverter.buildCloseRegionRequest(regionName, transitionInZK);
1288     try {
1289       admin.closeRegion(null, closeRegionRequest);
1290     } catch (ServiceException se) {
1291       throw getRemoteException(se);
1292     }
1293   }
1294 
1295   /**
1296    * A helper to close a region given a region name
1297    * using admin protocol.
1298    *
1299    * @param admin
1300    * @param regionName
1301    * @param versionOfClosingNode
1302    * @return true if the region is closed
1303    * @throws IOException
1304    */
1305   public static boolean closeRegion(final AdminProtocol admin, final byte[] regionName,
1306       final int versionOfClosingNode, final ServerName destinationServer,
1307       final boolean transitionInZK) throws IOException {
1308     CloseRegionRequest closeRegionRequest =
1309       RequestConverter.buildCloseRegionRequest(
1310         regionName, versionOfClosingNode, destinationServer, transitionInZK);
1311     try {
1312       CloseRegionResponse response = admin.closeRegion(null, closeRegionRequest);
1313       return ResponseConverter.isClosed(response);
1314     } catch (ServiceException se) {
1315       throw getRemoteException(se);
1316     }
1317   }
1318 
1319 
1320   /**
1321    * A helper to open a region using admin protocol.
1322    * @param admin
1323    * @param region
1324    * @throws IOException
1325    */
1326   public static void openRegion(final AdminProtocol admin,
1327       final HRegionInfo region) throws IOException {
1328     OpenRegionRequest request =
1329       RequestConverter.buildOpenRegionRequest(region, -1);
1330     try {
1331       admin.openRegion(null, request);
1332     } catch (ServiceException se) {
1333       throw ProtobufUtil.getRemoteException(se);
1334     }
1335   }
1336 
1337   /**
1338    * A helper to get the all the online regions on a region
1339    * server using admin protocol.
1340    *
1341    * @param admin
1342    * @return a list of online region info
1343    * @throws IOException
1344    */
1345   public static List<HRegionInfo> getOnlineRegions(final AdminProtocol admin) throws IOException {
1346     GetOnlineRegionRequest request = RequestConverter.buildGetOnlineRegionRequest();
1347     GetOnlineRegionResponse response = null;
1348     try {
1349       response = admin.getOnlineRegion(null, request);
1350     } catch (ServiceException se) {
1351       throw getRemoteException(se);
1352     }
1353     return getRegionInfos(response);
1354   }
1355 
1356   /**
1357    * Get the list of region info from a GetOnlineRegionResponse
1358    *
1359    * @param proto the GetOnlineRegionResponse
1360    * @return the list of region info or null if <code>proto</code> is null
1361    */
1362   static List<HRegionInfo> getRegionInfos(final GetOnlineRegionResponse proto) {
1363     if (proto == null) return null;
1364     List<HRegionInfo> regionInfos = new ArrayList<HRegionInfo>();
1365     for (RegionInfo regionInfo: proto.getRegionInfoList()) {
1366       regionInfos.add(HRegionInfo.convert(regionInfo));
1367     }
1368     return regionInfos;
1369   }
1370 
1371   /**
1372    * A helper to get the info of a region server using admin protocol.
1373    *
1374    * @param admin
1375    * @return the server name
1376    * @throws IOException
1377    */
1378   public static ServerInfo getServerInfo(
1379       final AdminProtocol admin) throws IOException {
1380     GetServerInfoRequest request = RequestConverter.buildGetServerInfoRequest();
1381     try {
1382       GetServerInfoResponse response = admin.getServerInfo(null, request);
1383       return response.getServerInfo();
1384     } catch (ServiceException se) {
1385       throw getRemoteException(se);
1386     }
1387   }
1388 
1389   /**
1390    * A helper to get the list of files of a column family
1391    * on a given region using admin protocol.
1392    *
1393    * @param admin
1394    * @param regionName
1395    * @param family
1396    * @return the list of store files
1397    * @throws IOException
1398    */
1399   public static List<String> getStoreFiles(final AdminProtocol admin,
1400       final byte[] regionName, final byte[] family) throws IOException {
1401     GetStoreFileRequest request =
1402       RequestConverter.buildGetStoreFileRequest(regionName, family);
1403     try {
1404       GetStoreFileResponse response = admin.getStoreFile(null, request);
1405       return response.getStoreFileList();
1406     } catch (ServiceException se) {
1407       throw ProtobufUtil.getRemoteException(se);
1408     }
1409   }
1410 
1411   /**
1412    * A helper to split a region using admin protocol.
1413    *
1414    * @param admin
1415    * @param hri
1416    * @param splitPoint
1417    * @throws IOException
1418    */
1419   public static void split(final AdminProtocol admin,
1420       final HRegionInfo hri, byte[] splitPoint) throws IOException {
1421     SplitRegionRequest request =
1422       RequestConverter.buildSplitRegionRequest(hri.getRegionName(), splitPoint);
1423     try {
1424       admin.splitRegion(null, request);
1425     } catch (ServiceException se) {
1426       throw ProtobufUtil.getRemoteException(se);
1427     }
1428   }
1429 
1430   /**
1431    * A helper to merge regions using admin protocol. Send request to
1432    * regionserver.
1433    * @param admin
1434    * @param region_a
1435    * @param region_b
1436    * @param forcible true if do a compulsory merge, otherwise we will only merge
1437    *          two adjacent regions
1438    * @throws IOException
1439    */
1440   public static void mergeRegions(final AdminProtocol admin,
1441       final HRegionInfo region_a, final HRegionInfo region_b,
1442       final boolean forcible) throws IOException {
1443     MergeRegionsRequest request = RequestConverter.buildMergeRegionsRequest(
1444         region_a.getRegionName(), region_b.getRegionName(),forcible);
1445     try {
1446       admin.mergeRegions(null, request);
1447     } catch (ServiceException se) {
1448       throw ProtobufUtil.getRemoteException(se);
1449     }
1450   }
1451 
1452 // End helpers for Admin
1453 
1454   /*
1455    * Get the total (read + write) requests from a RegionLoad pb
1456    * @param rl - RegionLoad pb
1457    * @return total (read + write) requests
1458    */
1459   public static long getTotalRequestsCount(RegionLoad rl) {
1460     if (rl == null) {
1461       return 0;
1462     }
1463 
1464     return rl.getReadRequestsCount() + rl.getWriteRequestsCount();
1465   }
1466 
1467 
1468   /**
1469    * @param m Message to get delimited pb serialization of (with pb magic prefix)
1470    */
1471   public static byte [] toDelimitedByteArray(final Message m) throws IOException {
1472     // Allocate arbitrary big size so we avoid resizing.
1473     ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
1474     m.writeDelimitedTo(baos);
1475     baos.close();
1476     return ProtobufUtil.prependPBMagic(baos.toByteArray());
1477   }
1478 
1479   /**
1480    * Converts a Permission proto to a client Permission object.
1481    *
1482    * @param proto the protobuf Permission
1483    * @return the converted Permission
1484    */
1485   public static Permission toPermission(AccessControlProtos.Permission proto) {
1486     if (proto.hasTable()) {
1487       return toTablePermission(proto);
1488     } else {
1489       List<Permission.Action> actions = toPermissionActions(proto.getActionList());
1490       return new Permission(actions.toArray(new Permission.Action[actions.size()]));
1491     }
1492   }
1493 
1494   /**
1495    * Converts a Permission proto to a client TablePermission object.
1496    *
1497    * @param proto the protobuf Permission
1498    * @return the converted TablePermission
1499    */
1500   public static TablePermission toTablePermission(AccessControlProtos.Permission proto) {
1501     List<Permission.Action> actions = toPermissionActions(proto.getActionList());
1502 
1503     byte[] qualifier = null;
1504     byte[] family = null;
1505     byte[] table = null;
1506 
1507     if (proto.hasTable()) table = proto.getTable().toByteArray();
1508     if (proto.hasFamily()) family = proto.getFamily().toByteArray();
1509     if (proto.hasQualifier()) qualifier = proto.getQualifier().toByteArray();
1510 
1511     return new TablePermission(table, family, qualifier,
1512         actions.toArray(new Permission.Action[actions.size()]));
1513   }
1514 
1515   /**
1516    * Convert a client Permission to a Permission proto
1517    *
1518    * @param perm the client Permission
1519    * @return the protobuf Permission
1520    */
1521   public static AccessControlProtos.Permission toPermission(Permission perm) {
1522     AccessControlProtos.Permission.Builder builder = AccessControlProtos.Permission.newBuilder();
1523     if (perm instanceof TablePermission) {
1524       TablePermission tablePerm = (TablePermission)perm;
1525       if (tablePerm.hasTable()) {
1526         builder.setTable(ByteString.copyFrom(tablePerm.getTable()));
1527       }
1528       if (tablePerm.hasFamily()) {
1529         builder.setFamily(ByteString.copyFrom(tablePerm.getFamily()));
1530       }
1531       if (tablePerm.hasQualifier()) {
1532         builder.setQualifier(ByteString.copyFrom(tablePerm.getQualifier()));
1533       }
1534     }
1535     for (Permission.Action a : perm.getActions()) {
1536       builder.addAction(toPermissionAction(a));
1537     }
1538     return builder.build();
1539   }
1540 
1541   /**
1542    * Converts a list of Permission.Action proto to a list of client Permission.Action objects.
1543    *
1544    * @param protoActions the list of protobuf Actions
1545    * @return the converted list of Actions
1546    */
1547   public static List<Permission.Action> toPermissionActions(
1548       List<AccessControlProtos.Permission.Action> protoActions) {
1549     List<Permission.Action> actions = new ArrayList<Permission.Action>(protoActions.size());
1550     for (AccessControlProtos.Permission.Action a : protoActions) {
1551       actions.add(toPermissionAction(a));
1552     }
1553     return actions;
1554   }
1555 
1556   /**
1557    * Converts a Permission.Action proto to a client Permission.Action object.
1558    *
1559    * @param action the protobuf Action
1560    * @return the converted Action
1561    */
1562   public static Permission.Action toPermissionAction(
1563       AccessControlProtos.Permission.Action action) {
1564     switch (action) {
1565       case READ:
1566         return Permission.Action.READ;
1567       case WRITE:
1568         return Permission.Action.WRITE;
1569       case EXEC:
1570         return Permission.Action.EXEC;
1571       case CREATE:
1572         return Permission.Action.CREATE;
1573       case ADMIN:
1574         return Permission.Action.ADMIN;
1575     }
1576     throw new IllegalArgumentException("Unknown action value "+action.name());
1577   }
1578 
1579   /**
1580    * Convert a client Permission.Action to a Permission.Action proto
1581    *
1582    * @param action the client Action
1583    * @return the protobuf Action
1584    */
1585   public static AccessControlProtos.Permission.Action toPermissionAction(
1586       Permission.Action action) {
1587     switch (action) {
1588       case READ:
1589         return AccessControlProtos.Permission.Action.READ;
1590       case WRITE:
1591         return AccessControlProtos.Permission.Action.WRITE;
1592       case EXEC:
1593         return AccessControlProtos.Permission.Action.EXEC;
1594       case CREATE:
1595         return AccessControlProtos.Permission.Action.CREATE;
1596       case ADMIN:
1597         return AccessControlProtos.Permission.Action.ADMIN;
1598     }
1599     throw new IllegalArgumentException("Unknown action value "+action.name());
1600   }
1601 
1602   /**
1603    * Convert a client user permission to a user permission proto
1604    *
1605    * @param perm the client UserPermission
1606    * @return the protobuf UserPermission
1607    */
1608   public static AccessControlProtos.UserPermission toUserPermission(UserPermission perm) {
1609     AccessControlProtos.Permission.Builder permissionBuilder =
1610         AccessControlProtos.Permission.newBuilder();
1611     for (Permission.Action a : perm.getActions()) {
1612       permissionBuilder.addAction(toPermissionAction(a));
1613     }
1614     if (perm.hasTable()) {
1615       permissionBuilder.setTable(ByteString.copyFrom(perm.getTable()));
1616     }
1617     if (perm.hasFamily()) {
1618       permissionBuilder.setFamily(ByteString.copyFrom(perm.getFamily()));
1619     }
1620     if (perm.hasQualifier()) {
1621       permissionBuilder.setQualifier(ByteString.copyFrom(perm.getQualifier()));
1622     }
1623 
1624     return AccessControlProtos.UserPermission.newBuilder()
1625         .setUser(ByteString.copyFrom(perm.getUser()))
1626         .setPermission(permissionBuilder)
1627         .build();
1628   }
1629 
1630   /**
1631    * Converts a user permission proto to a client user permission object.
1632    *
1633    * @param proto the protobuf UserPermission
1634    * @return the converted UserPermission
1635    */
1636   public static UserPermission toUserPermission(AccessControlProtos.UserPermission proto) {
1637     AccessControlProtos.Permission permission = proto.getPermission();
1638     List<Permission.Action> actions = toPermissionActions(permission.getActionList());
1639 
1640     byte[] qualifier = null;
1641     byte[] family = null;
1642     byte[] table = null;
1643 
1644     if (permission.hasTable()) table = permission.getTable().toByteArray();
1645     if (permission.hasFamily()) family = permission.getFamily().toByteArray();
1646     if (permission.hasQualifier()) qualifier = permission.getQualifier().toByteArray();
1647 
1648     return new UserPermission(proto.getUser().toByteArray(),
1649         table, family, qualifier,
1650         actions.toArray(new Permission.Action[actions.size()]));
1651   }
1652 
1653   /**
1654    * Convert a ListMultimap<String, TablePermission> where key is username
1655    * to a protobuf UserPermission
1656    *
1657    * @param perm the list of user and table permissions
1658    * @return the protobuf UserTablePermissions
1659    */
1660   public static AccessControlProtos.UserTablePermissions toUserTablePermissions(
1661       ListMultimap<String, TablePermission> perm) {
1662     AccessControlProtos.UserTablePermissions.Builder builder =
1663                   AccessControlProtos.UserTablePermissions.newBuilder();
1664     for (Map.Entry<String, Collection<TablePermission>> entry : perm.asMap().entrySet()) {
1665       AccessControlProtos.UserTablePermissions.UserPermissions.Builder userPermBuilder =
1666                   AccessControlProtos.UserTablePermissions.UserPermissions.newBuilder();
1667       userPermBuilder.setUser(ByteString.copyFromUtf8(entry.getKey()));
1668       for (TablePermission tablePerm: entry.getValue()) {
1669         userPermBuilder.addPermissions(toPermission(tablePerm));
1670       }
1671       builder.addPermissions(userPermBuilder.build());
1672     }
1673     return builder.build();
1674   }
1675 
1676   /**
1677    * A utility used to grant a user some permissions. The permissions will
1678    * be global if table is not specified.  Otherwise, they are for those
1679    * table/column family/qualifier only.
1680    * <p>
1681    * It's also called by the shell, in case you want to find references.
1682    *
1683    * @param protocol the AccessControlService protocol proxy
1684    * @param userShortName the short name of the user to grant permissions
1685    * @param t optional table name
1686    * @param f optional column family
1687    * @param q optional qualifier
1688    * @param actions the permissions to be granted
1689    * @throws ServiceException
1690    */
1691   public static void grant(AccessControlService.BlockingInterface protocol,
1692       String userShortName, byte[] t, byte[] f, byte[] q,
1693       Permission.Action... actions) throws ServiceException {
1694     List<AccessControlProtos.Permission.Action> permActions =
1695         Lists.newArrayListWithCapacity(actions.length);
1696     for (Permission.Action a : actions) {
1697       permActions.add(ProtobufUtil.toPermissionAction(a));
1698     }
1699     AccessControlProtos.GrantRequest request = RequestConverter.
1700       buildGrantRequest(userShortName, t, f, q, permActions.toArray(
1701         new AccessControlProtos.Permission.Action[actions.length]));
1702     protocol.grant(null, request);
1703   }
1704 
1705   /**
1706    * A utility used to revoke a user some permissions. The permissions will
1707    * be global if table is not specified.  Otherwise, they are for those
1708    * table/column family/qualifier only.
1709    * <p>
1710    * It's also called by the shell, in case you want to find references.
1711    *
1712    * @param protocol the AccessControlService protocol proxy
1713    * @param userShortName the short name of the user to revoke permissions
1714    * @param t optional table name
1715    * @param f optional column family
1716    * @param q optional qualifier
1717    * @param actions the permissions to be revoked
1718    * @throws ServiceException
1719    */
1720   public static void revoke(AccessControlService.BlockingInterface protocol,
1721       String userShortName, byte[] t, byte[] f, byte[] q,
1722       Permission.Action... actions) throws ServiceException {
1723     List<AccessControlProtos.Permission.Action> permActions =
1724         Lists.newArrayListWithCapacity(actions.length);
1725     for (Permission.Action a : actions) {
1726       permActions.add(ProtobufUtil.toPermissionAction(a));
1727     }
1728     AccessControlProtos.RevokeRequest request = RequestConverter.
1729       buildRevokeRequest(userShortName, t, f, q, permActions.toArray(
1730         new AccessControlProtos.Permission.Action[actions.length]));
1731     protocol.revoke(null, request);
1732   }
1733 
1734   /**
1735    * A utility used to get user permissions.
1736    * <p>
1737    * It's also called by the shell, in case you want to find references.
1738    *
1739    * @param protocol the AccessControlService protocol proxy
1740    * @param t optional table name
1741    * @throws ServiceException
1742    */
1743   public static List<UserPermission> getUserPermissions(
1744       AccessControlService.BlockingInterface protocol,
1745       byte[] t) throws ServiceException {
1746     AccessControlProtos.UserPermissionsRequest.Builder builder =
1747       AccessControlProtos.UserPermissionsRequest.newBuilder();
1748     if (t != null) {
1749       builder.setTable(ByteString.copyFrom(t));
1750     }
1751     AccessControlProtos.UserPermissionsRequest request = builder.build();
1752     AccessControlProtos.UserPermissionsResponse response =
1753       protocol.getUserPermissions(null, request);
1754     List<UserPermission> perms = new ArrayList<UserPermission>();
1755     for (AccessControlProtos.UserPermission perm: response.getPermissionList()) {
1756       perms.add(ProtobufUtil.toUserPermission(perm));
1757     }
1758     return perms;
1759   }
1760 
1761   /**
1762    * Convert a protobuf UserTablePermissions to a
1763    * ListMultimap<String, TablePermission> where key is username.
1764    *
1765    * @param proto the protobuf UserPermission
1766    * @return the converted UserPermission
1767    */
1768   public static ListMultimap<String, TablePermission> toUserTablePermissions(
1769       AccessControlProtos.UserTablePermissions proto) {
1770     ListMultimap<String, TablePermission> perms = ArrayListMultimap.create();
1771     AccessControlProtos.UserTablePermissions.UserPermissions userPerm;
1772 
1773     for (int i = 0; i < proto.getPermissionsCount(); i++) {
1774       userPerm = proto.getPermissions(i);
1775       for (int j = 0; j < userPerm.getPermissionsCount(); j++) {
1776         TablePermission tablePerm = toTablePermission(userPerm.getPermissions(j));
1777         perms.put(userPerm.getUser().toStringUtf8(), tablePerm);
1778       }
1779     }
1780 
1781     return perms;
1782   }
1783 
1784   /**
1785    * Converts a Token instance (with embedded identifier) to the protobuf representation.
1786    *
1787    * @param token the Token instance to copy
1788    * @return the protobuf Token message
1789    */
1790   public static AuthenticationProtos.Token toToken(Token<AuthenticationTokenIdentifier> token) {
1791     AuthenticationProtos.Token.Builder builder = AuthenticationProtos.Token.newBuilder();
1792     builder.setIdentifier(ByteString.copyFrom(token.getIdentifier()));
1793     builder.setPassword(ByteString.copyFrom(token.getPassword()));
1794     if (token.getService() != null) {
1795       builder.setService(ByteString.copyFromUtf8(token.getService().toString()));
1796     }
1797     return builder.build();
1798   }
1799 
1800   /**
1801    * Converts a protobuf Token message back into a Token instance.
1802    *
1803    * @param proto the protobuf Token message
1804    * @return the Token instance
1805    */
1806   public static Token<AuthenticationTokenIdentifier> toToken(AuthenticationProtos.Token proto) {
1807     return new Token<AuthenticationTokenIdentifier>(
1808         proto.hasIdentifier() ? proto.getIdentifier().toByteArray() : null,
1809         proto.hasPassword() ? proto.getPassword().toByteArray() : null,
1810         AuthenticationTokenIdentifier.AUTH_TOKEN_TYPE,
1811         proto.hasService() ? new Text(proto.getService().toStringUtf8()) : null);
1812   }
1813 
1814   /**
1815    * Find the HRegion encoded name based on a region specifier
1816    *
1817    * @param regionSpecifier the region specifier
1818    * @return the corresponding region's encoded name
1819    * @throws DoNotRetryIOException if the specifier type is unsupported
1820    */
1821   public static String getRegionEncodedName(
1822       final RegionSpecifier regionSpecifier) throws DoNotRetryIOException {
1823     byte[] value = regionSpecifier.getValue().toByteArray();
1824     RegionSpecifierType type = regionSpecifier.getType();
1825     switch (type) {
1826       case REGION_NAME:
1827         return HRegionInfo.encodeRegionName(value);
1828       case ENCODED_REGION_NAME:
1829         return Bytes.toString(value);
1830       default:
1831         throw new DoNotRetryIOException(
1832           "Unsupported region specifier type: " + type);
1833     }
1834   }
1835 
1836   public static ScanMetrics toScanMetrics(final byte[] bytes) {
1837     MapReduceProtos.ScanMetrics.Builder builder = MapReduceProtos.ScanMetrics.newBuilder();
1838     try {
1839       builder.mergeFrom(bytes);
1840     } catch (InvalidProtocolBufferException e) {
1841       //Ignored there are just no key values to add.
1842     }
1843     MapReduceProtos.ScanMetrics pScanMetrics = builder.build();
1844     ScanMetrics scanMetrics = new ScanMetrics();
1845     for (HBaseProtos.NameInt64Pair pair : pScanMetrics.getMetricsList()) {
1846       if (pair.hasName() && pair.hasValue()) {
1847         scanMetrics.setCounter(pair.getName(), pair.getValue());
1848       }
1849     }
1850     return scanMetrics;
1851   }
1852 
1853   public static MapReduceProtos.ScanMetrics toScanMetrics(ScanMetrics scanMetrics) {
1854     MapReduceProtos.ScanMetrics.Builder builder = MapReduceProtos.ScanMetrics.newBuilder();
1855     Map<String, Long> metrics = scanMetrics.getMetricsMap();
1856     for (Entry<String, Long> e : metrics.entrySet()) {
1857       HBaseProtos.NameInt64Pair nameInt64Pair =
1858           HBaseProtos.NameInt64Pair.newBuilder()
1859               .setName(e.getKey())
1860               .setValue(e.getValue())
1861               .build();
1862       builder.addMetrics(nameInt64Pair);
1863     }
1864     return builder.build();
1865   }
1866 
1867   /**
1868    * Unwraps an exception from a protobuf service into the underlying (expected) IOException.
1869    * This method will <strong>always</strong> throw an exception.
1870    * @param se the {@code ServiceException} instance to convert into an {@code IOException}
1871    */
1872   public static void toIOException(ServiceException se) throws IOException {
1873     if (se == null) {
1874       throw new NullPointerException("Null service exception passed!");
1875     }
1876 
1877     Throwable cause = se.getCause();
1878     if (cause != null && cause instanceof IOException) {
1879       throw (IOException)cause;
1880     }
1881     throw new IOException(se);
1882   }
1883 
1884   public static HBaseProtos.Cell toCell(final Cell kv) {
1885     // Doing this is going to kill us if we do it for all data passed.
1886     // St.Ack 20121205
1887     HBaseProtos.Cell.Builder kvbuilder = HBaseProtos.Cell.newBuilder();
1888     kvbuilder.setRow(ByteString.copyFrom(kv.getRowArray(), kv.getRowOffset(),
1889       kv.getRowLength()));
1890     kvbuilder.setFamily(ByteString.copyFrom(kv.getFamilyArray(),
1891       kv.getFamilyOffset(), kv.getFamilyLength()));
1892     kvbuilder.setQualifier(ByteString.copyFrom(kv.getQualifierArray(),
1893       kv.getQualifierOffset(), kv.getQualifierLength()));
1894     kvbuilder.setCellType(HBaseProtos.CellType.valueOf(kv.getTypeByte()));
1895     kvbuilder.setTimestamp(kv.getTimestamp());
1896     kvbuilder.setValue(ByteString.copyFrom(kv.getValueArray(), kv.getValueOffset(), kv.getValueLength()));
1897     return kvbuilder.build();
1898   }
1899 
1900   public static Cell toCell(final HBaseProtos.Cell cell) {
1901     // Doing this is going to kill us if we do it for all data passed.
1902     // St.Ack 20121205
1903     return CellUtil.createCell(cell.getRow().toByteArray(),
1904       cell.getFamily().toByteArray(),
1905       cell.getQualifier().toByteArray(),
1906       cell.getTimestamp(),
1907       (byte)cell.getCellType().getNumber(),
1908       cell.getValue().toByteArray());
1909   }
1910 
1911   /**
1912    * Get an instance of the argument type declared in a class's signature. The
1913    * argument type is assumed to be a PB Message subclass, and the instance is
1914    * created using parseFrom method on the passed ByteString.
1915    * @param runtimeClass the runtime type of the class
1916    * @param position the position of the argument in the class declaration
1917    * @param b the ByteString which should be parsed to get the instance created
1918    * @return the instance
1919    * @throws IOException
1920    */
1921   @SuppressWarnings("unchecked")
1922   public static <T extends Message>
1923   T getParsedGenericInstance(Class<?> runtimeClass, int position, ByteString b)
1924       throws IOException {
1925     Type type = runtimeClass.getGenericSuperclass();
1926     Type argType = ((ParameterizedType)type).getActualTypeArguments()[position];
1927     Class<T> classType = (Class<T>)argType;
1928     T inst;
1929     try {
1930       Method m = classType.getMethod("parseFrom", ByteString.class);
1931       inst = (T)m.invoke(null, b);
1932       return inst;
1933     } catch (SecurityException e) {
1934       throw new IOException(e);
1935     } catch (NoSuchMethodException e) {
1936       throw new IOException(e);
1937     } catch (IllegalArgumentException e) {
1938       throw new IOException(e);
1939     } catch (InvocationTargetException e) {
1940       throw new IOException(e);
1941     } catch (IllegalAccessException e) {
1942       throw new IOException(e);
1943     }
1944   }
1945 }