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