Java Code Examples for com.google.protobuf.ByteString#EMPTY

The following examples show how to use com.google.protobuf.ByteString#EMPTY . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestServiceImpl.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a payload of desired type and size. Reads compressableBuffer or
 * uncompressableBuffer as a circular buffer.
 */
private ByteString generatePayload(ByteString dataBuffer, int offset, int size) {
  ByteString payload = ByteString.EMPTY;
  // This offset would never pass the array boundary.
  int begin = offset;
  int end = 0;
  int bytesLeft = size;
  while (bytesLeft > 0) {
    end = Math.min(begin + bytesLeft, dataBuffer.size());
    // ByteString.substring returns the substring from begin, inclusive, to end, exclusive.
    payload = payload.concat(dataBuffer.substring(begin, end));
    bytesLeft -= (end - begin);
    begin = end % dataBuffer.size();
  }
  return payload;
}
 
Example 2
Source File: AuthenticationOutcomeListener.java    From Bats with Apache License 2.0 6 votes vote down vote up
public void initiate(final String mechanismName) {
  logger.trace("Initiating SASL exchange.");
  try {
    final ByteString responseData;
    final SaslClient saslClient = connection.getSaslClient();
    if (saslClient.hasInitialResponse()) {
      responseData = ByteString.copyFrom(evaluateChallenge(ugi, saslClient, new byte[0]));
    } else {
      responseData = ByteString.EMPTY;
    }
    client.send(new AuthenticationOutcomeListener<>(client, connection, saslRpcType, ugi, completionListener),
        connection,
        saslRpcType,
        SaslMessage.newBuilder()
            .setMechanism(mechanismName)
            .setStatus(SaslStatus.SASL_START)
            .setData(responseData)
            .build(),
        SaslMessage.class,
        true /* the connection will not be backed up at this point */);
    logger.trace("Initiated SASL exchange.");
  } catch (final Exception e) {
    completionListener.failed(RpcException.mapException(e));
  }
}
 
Example 3
Source File: TestServiceImpl.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a payload of desired type and size. Reads compressableBuffer or
 * uncompressableBuffer as a circular buffer.
 */
private ByteString generatePayload(ByteString dataBuffer, int offset, int size) {
  ByteString payload = ByteString.EMPTY;
  // This offset would never pass the array boundary.
  int begin = offset;
  int end = 0;
  int bytesLeft = size;
  while (bytesLeft > 0) {
    end = Math.min(begin + bytesLeft, dataBuffer.size());
    // ByteString.substring returns the substring from begin, inclusive, to end, exclusive.
    payload = payload.concat(dataBuffer.substring(begin, end));
    bytesLeft -= (end - begin);
    begin = end % dataBuffer.size();
  }
  return payload;
}
 
Example 4
Source File: TransactionUtil.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static String getHash(TransactionProtoBuf.Transaction transaction, String to) {
	TransactionProtoBuf.Transaction.Builder builder = TransactionProtoBuf.Transaction.newBuilder();
	if (transaction.getPayload() != ByteString.EMPTY) {
		builder.setPayload(transaction.getPayload());
	}
	builder.setExecer(transaction.getExecer());
	builder.setFee(transaction.getFee());
	builder.setExpire(0L);
	builder.setNonce(transaction.getNonce());
	if (!StringUtil.isEmpty(to)) {
		builder.setTo(to);
	} else {
		builder.setTo(transaction.getTo());
	}

	builder.setGroupCount(transaction.getGroupCount());
	if (transaction.getNext() != ByteString.EMPTY) {
		builder.setNext(transaction.getNext());
	}
	TransactionProtoBuf.Transaction build = builder.build();
	byte[] byteArray = build.toByteArray();
	return HexUtil.toHexString(Sha256(byteArray));
}
 
Example 5
Source File: AssistantClient.java    From google-assistant-java-demo with GNU General Public License v3.0 6 votes vote down vote up
public AssistantClient(OAuthCredentials oAuthCredentials, AssistantConf assistantConf, DeviceModel deviceModel,
                       Device device, IoConf ioConf) {

    this.assistantConf = assistantConf;
    this.deviceModel = deviceModel;
    this.device = device;
    this.currentConversationState = ByteString.EMPTY;
    this.ioConf = ioConf;

    // Create a channel to the test service.
    ManagedChannel channel = ManagedChannelBuilder.forAddress(assistantConf.getAssistantApiEndpoint(), 443)
            .build();

    // Create a stub with credential
    embeddedAssistantStub = EmbeddedAssistantGrpc.newStub(channel);

    updateCredentials(oAuthCredentials);
}
 
Example 6
Source File: RpcServerProcessServiceImpl.java    From redtorch with MIT License 5 votes vote down vote up
public boolean sendLz4CoreRpc(int targetNodeId, ByteString content, String reqId, RpcId rpcId) {

		ByteString contentByteString = ByteString.EMPTY;
		long beginTime = System.currentTimeMillis();
		try (InputStream in = new ByteArrayInputStream(content.toByteArray()); ByteArrayOutputStream bOut = new ByteArrayOutputStream(); LZ4FrameOutputStream lzOut = new LZ4FrameOutputStream(bOut);) {
			final byte[] buffer = new byte[10240];
			int n = 0;
			while (-1 != (n = in.read(buffer))) {
				lzOut.write(buffer, 0, n);
			}
			lzOut.close();
			in.close();
			contentByteString = ByteString.copyFrom(bOut.toByteArray());
			logger.info("发送RPC记录,目标节点ID:{},请求ID:{},RPC:{},压缩耗时{}ms,原始数据大小{},压缩后数据大小{},压缩率{}", targetNodeId, reqId, rpcId.getValueDescriptor().getName(), System.currentTimeMillis() - beginTime,
					content.size(), contentByteString.size(), contentByteString.size() / (double) content.size());
		} catch (Exception e) {
			logger.error("发送RPC错误,压缩异常,目标节点ID:{},请求ID:{},RPC:{}", targetNodeId, reqId, rpcId.getValueDescriptor().getName(), e);
			return false;
		}

		DataExchangeProtocol.Builder depBuilder = DataExchangeProtocol.newBuilder() //
				.setRpcId(rpcId.getNumber()) //
				.setReqId(reqId) //
				.setContentType(ContentType.COMPRESSED_LZ4) //
				.setSourceNodeId(0) //
				.setTargetNodeId(targetNodeId) //
				.setTimestamp(System.currentTimeMillis()) //
				.setContentBytes(contentByteString);

		if (!webSocketServerHandler.sendDataByNodeId(targetNodeId, depBuilder.build().toByteArray())) {
			logger.error("发送RPC错误,目标节点ID:{},请求ID:{},RPC:{}", targetNodeId, reqId, rpcId.getValueDescriptor().getName());
			return false;
		}
		return true;
	}
 
Example 7
Source File: ByteArrayToByteStringConverter.java    From esj with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public final ByteString convert(final byte[] obj) {
    if (obj == null) {
        return ByteString.EMPTY;
    }
    return ByteString.copyFrom(obj);
}
 
Example 8
Source File: ProtobufUtils.java    From tracing-framework with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/** Serialize a BaggageMessage to a byte string, returning an empty bytestring if the provided message is null or
 * invalid */
public static ByteString toByteString(BaggageMessage message) {
    if (message != null) {
        try {
            return message.toByteString();
        } catch (Throwable t) {}
    }
    return ByteString.EMPTY;
}
 
Example 9
Source File: KeyUtils.java    From etcd-java with Apache License 2.0 5 votes vote down vote up
public static ByteString fromHexString(CharSequence seq) {
    int len = seq.length();
    if (len == 0) {
        return ByteString.EMPTY;
    }
    if (len % 2 != 0) {
        throw new IllegalArgumentException("must be even number of chars");
    }
    int blen = len >> 1;
    byte[] bytes = new byte[blen];
    for (int i = 0, j = 0; i < blen; i ++, j += 2) {
        bytes[i] = (byte) ((digitFor(seq.charAt(j)) << 4) | digitFor(seq.charAt(j + 1)));
    }
    return UnsafeByteOperations.unsafeWrap(bytes);
}
 
Example 10
Source File: WorkerSpawnRunner.java    From bazel with Apache License 2.0 5 votes vote down vote up
private WorkRequest createWorkRequest(
    Spawn spawn,
    SpawnExecutionContext context,
    List<String> flagfiles,
    MetadataProvider inputFileCache,
    int workerId)
    throws IOException {
  WorkRequest.Builder requestBuilder = WorkRequest.newBuilder();
  for (String flagfile : flagfiles) {
    expandArgument(execRoot, flagfile, requestBuilder);
  }

  List<ActionInput> inputs =
      ActionInputHelper.expandArtifacts(spawn.getInputFiles(), context.getArtifactExpander());

  for (ActionInput input : inputs) {
    byte[] digestBytes = inputFileCache.getMetadata(input).getDigest();
    ByteString digest;
    if (digestBytes == null) {
      digest = ByteString.EMPTY;
    } else {
      digest = ByteString.copyFromUtf8(HashCode.fromBytes(digestBytes).toString());
    }

    requestBuilder
        .addInputsBuilder()
        .setPath(input.getExecPathString())
        .setDigest(digest)
        .build();
  }
  return requestBuilder.setRequestId(workerId).build();
}
 
Example 11
Source File: KeyRangeUtils.java    From tikv-client-lib-java with Apache License 2.0 4 votes vote down vote up
public static List<Coprocessor.KeyRange> split(Coprocessor.KeyRange range, int splitFactor) {
  if (splitFactor > 32 || splitFactor <= 0 || (splitFactor & (splitFactor - 1)) != 0) {
    throw new TiClientInternalException(
        "splitFactor must be positive integer power of 2 and no greater than 16");
  }

  ByteString startKey = range.getStart();
  ByteString endKey = range.getEnd();
  // we don't cut infinite
  if (startKey.isEmpty() || endKey.isEmpty()) {
    return ImmutableList.of(range);
  }

  ImmutableList.Builder<Coprocessor.KeyRange> resultList = ImmutableList.builder();
  int maxSize = Math.max(startKey.size(), endKey.size());
  int i;

  for (i = 0; i < maxSize; i++) {
    byte sb = i < startKey.size() ? startKey.byteAt(i) : 0;
    byte eb = i < endKey.size() ? endKey.byteAt(i) : 0;
    if (sb != eb) {
      break;
    }
  }

  ByteString sRemaining = i < startKey.size() ? startKey.substring(i) : ByteString.EMPTY;
  ByteString eRemaining = i < endKey.size() ? endKey.substring(i) : ByteString.EMPTY;

  CodecDataInput cdi = new CodecDataInput(sRemaining);
  int uss = cdi.readPartialUnsignedShort();

  cdi = new CodecDataInput(eRemaining);
  int ues = cdi.readPartialUnsignedShort();

  int delta = (ues - uss) / splitFactor;
  if (delta <= 0) {
    return ImmutableList.of(range);
  }

  ByteString prefix = startKey.size() > endKey.size() ?
                      startKey.substring(0, i) : endKey.substring(0, i);
  ByteString newStartKey = startKey;
  ByteString newEndKey;
  for (int j = 0; j < splitFactor; j++) {
    uss += delta;
    if (j == splitFactor - 1) {
      newEndKey = endKey;
    } else {
      CodecDataOutput cdo = new CodecDataOutput();
      cdo.writeShort(uss);
      newEndKey = prefix.concat(cdo.toByteString());
    }
    resultList.add(makeCoprocRange(newStartKey, newEndKey));
    newStartKey = newEndKey;
  }

  return resultList.build();
}
 
Example 12
Source File: RecordFileSource.java    From dataflow-opinion-analysis with Apache License 2.0 4 votes vote down vote up
private RecordFileReader(RecordFileSource<T> source) {
  super(source);
  buffer = ByteString.EMPTY;
  coder = source.coder;
  separator = source.separator;
}
 
Example 13
Source File: TransactionStoreTest.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void GetTransactionTest() throws BadItemException, ItemNotFoundException {
  final BlockStore blockStore = dbManager.getBlockStore();
  final TransactionStore trxStore = dbManager.getTransactionStore();
  String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62";

  BlockWrapper blockWrapper =
      new BlockWrapper(
          1,
          Sha256Hash.wrap(dbManager.getGenesisBlockId().getByteString()),
          1,ByteString.EMPTY,
              ByteString.copyFrom(
              ECKey.fromPrivate(
                  ByteArray.fromHexString(key)).getAddress()));

  // save in database with block number
  TransferContract tc =
      TransferContract.newBuilder()
          .setAmount(10)
          .setOwnerAddress(ByteString.copyFromUtf8("aaa"))
          .setToAddress(ByteString.copyFromUtf8("bbb"))
          .build();
  TransactionWrapper trx = new TransactionWrapper(tc, ContractType.TransferContract);
  blockWrapper.addTransaction(trx);
  trx.setBlockNum(blockWrapper.getNum());
  blockStore.put(blockWrapper.getBlockId().getBytes(), blockWrapper);
  trxStore.put(trx.getTransactionId().getBytes(), trx);
  Assert.assertEquals("Get transaction is error",
      trxStore.get(trx.getTransactionId().getBytes()).getInstance(), trx.getInstance());

  // no found in transaction store database
  tc =
      TransferContract.newBuilder()
          .setAmount(1000)
          .setOwnerAddress(ByteString.copyFromUtf8("aaa"))
          .setToAddress(ByteString.copyFromUtf8("bbb"))
          .build();
  trx = new TransactionWrapper(tc, ContractType.TransferContract);
  Assert.assertNull(trxStore.get(trx.getTransactionId().getBytes()));

  // no block number, directly save in database
  tc =
      TransferContract.newBuilder()
          .setAmount(10000)
          .setOwnerAddress(ByteString.copyFromUtf8("aaa"))
          .setToAddress(ByteString.copyFromUtf8("bbb"))
          .build();
  trx = new TransactionWrapper(tc, ContractType.TransferContract);
  trxStore.put(trx.getTransactionId().getBytes(), trx);
  Assert.assertEquals("Get transaction is error",
      trxStore.get(trx.getTransactionId().getBytes()).getInstance(), trx.getInstance());
}
 
Example 14
Source File: TransactionStoreTest.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test
public void GetUncheckedTransactionTest() {
  final BlockStore blockStore = dbManager.getBlockStore();
  final TransactionStore trxStore = dbManager.getTransactionStore();
  String key = "f31db24bfbd1a2ef19beddca0a0fa37632eded9ac666a05d3bd925f01dde1f62";

  BlockWrapper blockWrapper =
      new BlockWrapper(
          1,
          Sha256Hash.wrap(dbManager.getGenesisBlockId().getByteString()),
          1,ByteString.EMPTY,
              ByteString.copyFrom(
              ECKey.fromPrivate(
                  ByteArray.fromHexString(key)).getAddress()));

  // save in database with block number
  TransferContract tc =
      TransferContract.newBuilder()
          .setAmount(10)
          .setOwnerAddress(ByteString.copyFromUtf8("aaa"))
          .setToAddress(ByteString.copyFromUtf8("bbb"))
          .build();
  TransactionWrapper trx = new TransactionWrapper(tc, ContractType.TransferContract);
  blockWrapper.addTransaction(trx);
  trx.setBlockNum(blockWrapper.getNum());
  blockStore.put(blockWrapper.getBlockId().getBytes(), blockWrapper);
  trxStore.put(trx.getTransactionId().getBytes(), trx);
  Assert.assertEquals("Get transaction is error",
      trxStore.getUnchecked(trx.getTransactionId().getBytes()).getInstance(), trx.getInstance());

  // no found in transaction store database
  tc =
      TransferContract.newBuilder()
          .setAmount(1000)
          .setOwnerAddress(ByteString.copyFromUtf8("aaa"))
          .setToAddress(ByteString.copyFromUtf8("bbb"))
          .build();
  trx = new TransactionWrapper(tc, ContractType.TransferContract);
  Assert.assertNull(trxStore.getUnchecked(trx.getTransactionId().getBytes()));

  // no block number, directly save in database
  tc =
      TransferContract.newBuilder()
          .setAmount(10000)
          .setOwnerAddress(ByteString.copyFromUtf8("aaa"))
          .setToAddress(ByteString.copyFromUtf8("bbb"))
          .build();
  trx = new TransactionWrapper(tc, ContractType.TransferContract);
  trxStore.put(trx.getTransactionId().getBytes(), trx);
  Assert.assertEquals("Get transaction is error",
      trxStore.getUnchecked(trx.getTransactionId().getBytes()).getInstance(), trx.getInstance());
}
 
Example 15
Source File: CompatibilityTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void testEmptyByteString() throws Exception {
  ByteString empty = ByteString.EMPTY;
  assertTrue(empty instanceof ByteString);
  assertEquals(0, empty.size());
  assertTrue(empty.isEmpty());
}
 
Example 16
Source File: Chunker.java    From bazel-buildfarm with Apache License 2.0 4 votes vote down vote up
Chunker(Supplier<InputStream> dataSupplier, long size, int chunkSize) {
  this.dataSupplier = checkNotNull(dataSupplier);
  this.size = size;
  this.chunkSize = chunkSize;
  this.emptyChunk = new Chunk(ByteString.EMPTY, 0);
}
 
Example 17
Source File: TextSource.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
private TextBasedReader(TextSource source, byte[] delimiter) {
  super(source);
  buffer = ByteString.EMPTY;
  this.delimiter = delimiter;
}
 
Example 18
Source File: VirtualActionInput.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public ByteString getBytes() throws IOException {
  return ByteString.EMPTY;
}
 
Example 19
Source File: ConcreteScanIterator.java    From client-java with Apache License 2.0 4 votes vote down vote up
public ConcreteScanIterator(
    TiConfiguration conf, RegionStoreClientBuilder builder, ByteString startKey, long version) {
  // Passing endKey as ByteString.EMPTY means that endKey is +INF by default,
  super(conf, builder, startKey, ByteString.EMPTY, Integer.MAX_VALUE);
  this.version = version;
}
 
Example 20
Source File: FuseCAS.java    From bazel-buildfarm with Apache License 2.0 4 votes vote down vote up
WriteFileEntry(boolean executable) {
  this.executable = executable;
  content = ByteString.EMPTY;
}