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