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