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