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