com.google.protobuf.ByteString#isEmpty ( )源码实例Demo

下面列出了com.google.protobuf.ByteString#isEmpty ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: client-java   文件: ScanIterator.java
ScanIterator(
    TiConfiguration conf,
    RegionStoreClientBuilder builder,
    ByteString startKey,
    ByteString endKey,
    int limit) {
  this.startKey = requireNonNull(startKey, "start key is null");
  if (startKey.isEmpty()) {
    throw new IllegalArgumentException("start key cannot be empty");
  }
  this.endKey = Key.toRawKey(requireNonNull(endKey, "end key is null"));
  this.hasEndKey = !endKey.equals(ByteString.EMPTY);
  this.limit = limit;
  this.conf = conf;
  this.builder = builder;
}
 
源代码2 项目: gsc-core   文件: AccountStateCallBack.java
public void executePushFinish() throws BadBlockException {
    if (!exe()) {
        return;
    }
    ByteString oldRoot = blockWrapper.getInstance().getBlockHeader().getRawData()
            .getAccountStateRoot();
    execute = false;
    //
    byte[] newRoot = trie.getRootHash();
    if (ArrayUtils.isEmpty(newRoot)) {
        newRoot = Hash.EMPTY_TRIE_HASH;
    }
    if (!oldRoot.isEmpty() && !Arrays.equals(oldRoot.toByteArray(), newRoot)) {
        logger.error("the accountStateRoot hash is error. {}, oldRoot: {}, newRoot: {}",
                blockWrapper.getBlockId().getString(), ByteUtil.toHexString(oldRoot.toByteArray()),
                ByteUtil.toHexString(newRoot));
        printErrorLog(trie);
        throw new BadBlockException("the accountStateRoot hash is error");
    }
}
 
源代码3 项目: gsc-core   文件: Wallet.java
public AssetIssueList getAssetIssueByAccount(ByteString accountAddress) {
    if (accountAddress == null || accountAddress.isEmpty()) {
        return null;
    }

    List<AssetIssueWrapper> assetIssueWrapperList =
            dbManager.getAssetIssueStoreFinal().getAllAssetIssues();

    AssetIssueList.Builder builder = AssetIssueList.newBuilder();
    assetIssueWrapperList.stream()
            .filter(assetIssueWrapper -> assetIssueWrapper.getOwnerAddress().equals(accountAddress))
            .forEach(issueWrapper -> {
                builder.addAssetIssue(issueWrapper.getInstance());
            });

    return builder.build();
}
 
源代码4 项目: gsc-core   文件: Wallet.java
public AssetIssueList getAssetIssueListByName(ByteString assetName) {
    if (assetName == null || assetName.isEmpty()) {
        return null;
    }

    List<AssetIssueWrapper> assetIssueWrapperList =
            dbManager.getAssetIssueStoreFinal().getAllAssetIssues();

    AssetIssueList.Builder builder = AssetIssueList.newBuilder();
    assetIssueWrapperList.stream()
            .filter(assetIssueWrapper -> assetIssueWrapper.getName().equals(assetName))
            .forEach(issueWrapper -> {
                builder.addAssetIssue(issueWrapper.getInstance());
            });

    return builder.build();
}
 
源代码5 项目: bazel-buildfarm   文件: ByteStreamServiceWriter.java
@Override
public void onNext(WriteRequest request) {
  checkState(
      (hasSeenResourceName && request.getResourceName().isEmpty())
          || request.getResourceName().equals(resourceName));
  hasSeenResourceName = true;
  checkState(!finished);
  ByteString data = request.getData();
  if (data.isEmpty() || request.getWriteOffset() == out.size()) {
    try {
      request.getData().writeTo(out);
      finished = request.getFinishWrite();
      if (finished) {
        long committedSize = out.size();
        content.set(out.toByteString());
        responseObserver.onNext(
            WriteResponse.newBuilder().setCommittedSize(committedSize).build());
      }
    } catch (IOException e) {
      responseObserver.onError(Status.fromThrowable(e).asException());
    }
  } else {
    responseObserver.onError(Status.INVALID_ARGUMENT.asException());
  }
}
 
源代码6 项目: tikv-client-lib-java   文件: RangeSplitter.java
private static int rightCompareTo(ByteString lhs, ByteString rhs) {
  requireNonNull(lhs, "lhs is null");
  requireNonNull(rhs, "rhs is null");

  // both infinite
  if (lhs.isEmpty() && rhs.isEmpty()) {
    return 0;
  }
  if (lhs.isEmpty()) {
    return 1;
  }
  if (rhs.isEmpty()) {
    return -1;
  }

  return Comparables.wrap(lhs).compareTo(Comparables.wrap(rhs));
}
 
源代码7 项目: glowroot   文件: LazyHistogram.java
public void merge(Aggregate.Histogram toBeMergedHistogram) {
    ByteString encodedBytes = toBeMergedHistogram.getEncodedBytes();
    if (encodedBytes.isEmpty()) {
        for (long rawValue : toBeMergedHistogram.getOrderedRawValueList()) {
            add(rawValue);
        }
    } else {
        if (histogram == null) {
            convertValuesToHistogram();
        }
        histogram.add(Histogram.decodeFromByteBuffer(encodedBytes.asReadOnlyByteBuffer(), 0));
    }
}
 
源代码8 项目: firebase-android-sdk   文件: TargetState.java
/**
 * Applies the resume token to the TargetChange, but only when it has a new value. Empty
 * resumeTokens are discarded.
 */
void updateResumeToken(ByteString resumeToken) {
  if (!resumeToken.isEmpty()) {
    hasChanges = true;
    this.resumeToken = resumeToken;
  }
}
 
源代码9 项目: glowroot   文件: LazyHistogram.java
public LazyHistogram(Aggregate.Histogram hist) {
    ByteString encodedBytes = hist.getEncodedBytes();
    if (encodedBytes.isEmpty()) {
        List<Long> orderedRawValues = hist.getOrderedRawValueList();
        values = new long[orderedRawValues.size()];
        for (int i = 0; i < values.length; i++) {
            values[i] = orderedRawValues.get(i);
        }
        size = values.length;
    } else {
        histogram = Histogram.decodeFromByteBuffer(encodedBytes.asReadOnlyByteBuffer(), 0);
    }
}
 
ChaincodeEvent getEvent() {
    ProposalPackage.ChaincodeAction ca = getChaincodeAction();
    ByteString eventsBytes = ca.getEvents();
    if (eventsBytes == null || eventsBytes.isEmpty()) {
        return null;
    }

    return new ChaincodeEvent(eventsBytes);
}
 
源代码11 项目: tikv-client-lib-java   文件: KeyRangeUtils.java
public static Range makeRange(ByteString startKey, ByteString endKey) {
  if (startKey.isEmpty() && endKey.isEmpty()) {
    return Range.all();
  }
  if (startKey.isEmpty()) {
    return Range.lessThan(Comparables.wrap(endKey));
  } else if (endKey.isEmpty()) {
    return Range.atLeast(Comparables.wrap(startKey));
  }
  return Range.closedOpen(Comparables.wrap(startKey), Comparables.wrap(endKey));
}
 
源代码12 项目: bazel-buildfarm   文件: ByteStreamService.java
ServerCallStreamObserver<ByteString> newChunkObserver(
    ServerCallStreamObserver<ReadResponse> responseObserver) {
  return new DelegateServerCallStreamObserver<ByteString, ReadResponse>(responseObserver) {
    @Override
    public void onNext(ByteString data) {
      while (!data.isEmpty()) {
        ByteString slice;
        if (data.size() > CHUNK_SIZE) {
          slice = data.substring(0, CHUNK_SIZE);
          data = data.substring(CHUNK_SIZE);
        } else {
          slice = data;
          data = ByteString.EMPTY;
        }
        responseObserver.onNext(ReadResponse.newBuilder().setData(slice).build());
      }
    }

    @Override
    public void onError(Throwable t) {
      responseObserver.onError(t);
    }

    @Override
    public void onCompleted() {
      responseObserver.onCompleted();
    }
  };
}
 
源代码13 项目: spliceengine   文件: V2TxnDecoder.java
public org.apache.hadoop.hbase.client.Put encodeForPut(TxnMessage.TxnInfo txnInfo,byte[] rowKey) throws IOException{
    org.apache.hadoop.hbase.client.Put put=new org.apache.hadoop.hbase.client.Put(rowKey);
    MultiFieldEncoder metaFieldEncoder=MultiFieldEncoder.create(5);
    metaFieldEncoder.encodeNext(txnInfo.getBeginTs()).encodeNext(txnInfo.getParentTxnid());

    if(txnInfo.hasIsAdditive())
        metaFieldEncoder.encodeNext(txnInfo.getIsAdditive());
    else
        metaFieldEncoder.encodeEmpty();

    Txn.IsolationLevel level=Txn.IsolationLevel.fromInt(txnInfo.getIsolationLevel());
    if(level!=null)
        metaFieldEncoder.encodeNext(level.encode());
    else
        metaFieldEncoder.encodeEmpty();

    Txn.State state=Txn.State.ACTIVE;

    put.addColumn(FAMILY,DATA_QUALIFIER_BYTES,metaFieldEncoder.build());
    put.addColumn(FAMILY,KEEP_ALIVE_QUALIFIER_BYTES,Encoding.encode(System.currentTimeMillis()));
    put.addColumn(FAMILY,STATE_QUALIFIER_BYTES,state.encode());
    ByteString destTableBuffer=txnInfo.getDestinationTables();
    if(destTableBuffer!=null && !destTableBuffer.isEmpty())
        put.addColumn(FAMILY,DESTINATION_TABLE_QUALIFIER_BYTES,destTableBuffer.toByteArray());
    if (txnInfo.hasTaskId()) {
        TxnMessage.TaskId taskId = txnInfo.getTaskId();
        MultiFieldEncoder taskIdEncoder=MultiFieldEncoder.create(5);
        taskIdEncoder.encodeNext("").encodeNext(0)
                .encodeNext(taskId.getStageId()).encodeNext(taskId.getPartitionId()).encodeNext(taskId.getTaskAttemptNumber());
        put.addColumn(FAMILY,TASK_QUALIFIER_BYTES,taskIdEncoder.build());
    }
    return put;
}
 
源代码14 项目: julongchain   文件: HistoryLevelDB.java
@Override
  public void commit(Common.Block block) throws LedgerException {
      long blockNo = block.getHeader().getNumber();
      int tranNo = 0;
      UpdateBatch dbBatch = new UpdateBatch();
      log.debug(String.format("Group [%s]: Updating historyDB for groupNo [%s] with [%d] transactions"
              , dbName, blockNo, block.getData().getDataCount()));
//读取metadata中的transaction filter,构建顾虑器
ByteString metadata = block.getMetadata().getMetadata(Common.BlockMetadataIndex.TRANSACTIONS_FILTER.getNumber());
TxValidationFlags txsFilter;
if (metadata == null || metadata.isEmpty()) {
	txsFilter = new TxValidationFlags(block.getData().getDataCount());
	block = block.toBuilder()
			.setMetadata(block.getMetadata().toBuilder()
					.setMetadata(Common.BlockMetadataIndex.TRANSACTIONS_FILTER.getNumber(), txsFilter.toByteString())
					.build())
			.build();
}
txsFilter = TxValidationFlags.fromByteString(block.getMetadata().getMetadata(Common.BlockMetadataIndex.TRANSACTIONS_FILTER.getNumber()));
      //将每个交易的写集写入HistoryDB
   List<ByteString> list = block.getData().getDataList();
      for (; tranNo < list.size(); tranNo++) {
          ByteString evnByte = list.get(tranNo);
          if(txsFilter.isInValid(tranNo)){
              log.debug(String.format("Group [%s]: Skipping write into historyDB for invalid transaction number %d."
                      , dbName, tranNo));
              continue;
          }
          Common.Envelope env = Util.getEnvelopFromBlock(evnByte);
          Common.Payload payload = Util.getPayload(env);
          Common.GroupHeader header = null;
          if (payload != null) {
              header = Util.getGroupHeader(payload.getHeader().getGroupHeader());
          }
          //经过背书的交易写入HistoryDB
          if (header != null) {
              if(Common.HeaderType.ENDORSER_TRANSACTION.getNumber() == header.getType()){
                  ProposalPackage.SmartContractAction respPayload;
                  TxRwSet txRWSet = new TxRwSet();
                  respPayload = Util.getActionFromEnvelope(evnByte);
                  if(respPayload == null || !respPayload.hasResponse()){
                      log.debug("Got null respPayload from env");
                      continue;
                  }
                  txRWSet.fromProtoBytes(respPayload.getResults());
                  for(NsRwSet nsRwSet : txRWSet.getNsRwSets()){
                      String ns = nsRwSet.getNameSpace();
                      for(KvRwset.KVWrite kvWrite : nsRwSet.getKvRwSet().getWritesList()){
                          String writeKey = kvWrite.getKey();
                          //key:ns~key~blockNo~tranNo
                          byte[] compositeHistoryKey = HistoryDBHelper.constructCompositeHistoryKey(ns, writeKey, blockNo, tranNo);
                       String s = new String(compositeHistoryKey);
                       dbBatch.put(compositeHistoryKey, EMPTY_VALUE);
                      }
                  }
              } else {
                  log.debug(String.format("Group [%s]: Skipping transaction [%d] since it is not an endorsement transaction"
                          , dbName, tranNo));
              }
          }
      }

      //添加保存点
      LedgerHeight height = new LedgerHeight(blockNo,tranNo);
      dbBatch.put(SAVE_POINT_KEY, height.toBytes());

      //同步写入leveldb
      provider.writeBatch(dbBatch, true);

      log.debug(String.format("Group [%s]: Update committed to historydb for blockNo [%d]"
              ,dbName, blockNo));
  }
 
源代码15 项目: gsc-core   文件: AccountPermissionUpdateOperator.java
private boolean checkPermission(Permission permission) throws ContractValidateException {
    if (permission.getKeysCount() > dbManager.getDynamicPropertiesStore().getTotalSignNum()) {
        throw new ContractValidateException("number of keys in permission should not be greater "
                + "than " + dbManager.getDynamicPropertiesStore().getTotalSignNum());
    }
    if (permission.getKeysCount() == 0) {
        throw new ContractValidateException("key's count should be greater than 0");
    }
    if (permission.getType() == PermissionType.Witness && permission.getKeysCount() != 1) {
        throw new ContractValidateException("Witness permission's key count should be 1");
    }
    if (permission.getThreshold() <= 0) {
        throw new ContractValidateException("permission's threshold should be greater than 0");
    }
    String name = permission.getPermissionName();
    if (!StringUtils.isEmpty(name) && name.length() > 32) {
        throw new ContractValidateException("permission's name is too long");
    }
    //check owner name ?
    if (permission.getParentId() != 0) {
        throw new ContractValidateException("permission's parent should be owner");
    }

    long weightSum = 0;
    List<ByteString> addressList = permission.getKeysList()
            .stream()
            .map(x -> x.getAddress())
            .distinct()
            .collect(toList());
    if (addressList.size() != permission.getKeysList().size()) {
        throw new ContractValidateException(
                "address should be distinct in permission " + permission.getType());
    }
    for (Key key : permission.getKeysList()) {
        if (!Wallet.addressValid(key.getAddress().toByteArray())) {
            throw new ContractValidateException("key is not a validate address");
        }
        if (key.getWeight() <= 0) {
            throw new ContractValidateException("key's weight should be greater than 0");
        }
        try {
            weightSum = Math.addExact(weightSum, key.getWeight());
        } catch (ArithmeticException e) {
            throw new ContractValidateException(e.getMessage());
        }
    }
    if (weightSum < permission.getThreshold()) {
        throw new ContractValidateException(
                "sum of all key's weight should not be less than threshold in permission " + permission
                        .getType());
    }

    ByteString operations = permission.getOperations();
    if (permission.getType() != PermissionType.Active) {
        if (!operations.isEmpty()) {
            throw new ContractValidateException(
                    permission.getType() + " permission needn't operations");
        }
        return true;
    }
    //check operations
    if (operations.isEmpty() || operations.size() != 32) {
        throw new ContractValidateException("operations size must 32");
    }

    byte[] types1 = dbManager.getDynamicPropertiesStore().getAvailableContractType();
    for (int i = 0; i < 256; i++) {
        boolean b = (operations.byteAt(i / 8) & (1 << (i % 8))) != 0;
        boolean t = ((types1[(i / 8)] & 0xff) & (1 << (i % 8))) != 0;
        if (b && !t) {
            throw new ContractValidateException(i + " isn't a validate ContractType");
        }
    }
    return true;
}
 
源代码16 项目: WavesJ   文件: PBTransactions.java
public static String toVanillaAssetId(final ByteString assetId) {
    if (assetId.isEmpty()) return Asset.WAVES;
    else return Asset.normalize(Base58.encode(assetId.toByteArray()));
}
 
源代码17 项目: tikv-client-lib-java   文件: KeyRangeUtils.java
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();
}
 
源代码18 项目: bazel-buildfarm   文件: WriteStreamObserver.java
private void handleWrite(String resourceName, long offset, ByteString data, boolean finishWrite) {
  long committedSize = write.getCommittedSize();
  if (offset != 0 && offset != committedSize) {
    // we are synchronized here for delivery, but not for asynchronous completion
    // of the write - if it has completed already, and that is the source of the
    // offset mismatch, perform nothing further and release sync to allow the
    // callback to complete the write
    //
    // ABORTED response is specific to encourage the client to retry
    if (!write.isComplete()) {
      responseObserver.onError(
          ABORTED
              .withDescription(
                  format("offset %d does not match committed size %d", offset, committedSize))
              .asException());
    }
  } else if (!resourceName.equals(name)) {
    responseObserver.onError(
        INVALID_ARGUMENT
            .withDescription(
                format(
                    "request resource_name %s does not match previous resource_name %s",
                    resourceName, name))
            .asException());
  } else {
    if (offset == 0 && offset != committedSize) {
      write.reset();
    }
    if (earliestOffset < 0 || offset < earliestOffset) {
      earliestOffset = offset;
    }

    logger.log(
        Level.FINER,
        format(
            "writing %d to %s at %d%s",
            data.size(), name, offset, finishWrite ? " with finish_write" : ""));
    if (!data.isEmpty()) {
      writeData(data);
      requestCount++;
      requestBytes += data.size();
    }
    if (finishWrite) {
      close();
    }
  }
}
 
源代码19 项目: cloud-spanner-r2dbc   文件: Assert.java
/**
 * Checks that a specified object reference is not {@code null} or an empty string, and throws a
 * customized {@link IllegalArgumentException} if it is.
 *
 * @param s string to check
 * @param message informative message to be used in the event that an
 * {@link IllegalArgumentException} is thrown
 * @return the original string {@code s}
 * @throws IllegalArgumentException if {@code o} is {@code null}
 */
public static ByteString requireNonEmpty(@Nullable ByteString s, String message) {
  if (s == null || s.isEmpty()) {
    throw new IllegalArgumentException(message);
  }

  return s;
}
 
源代码20 项目: reef   文件: GRPCUtils.java
/**
 * Converts ByteString to byte array.
 * @param bs ByteString
 * @return byte array or null if not present
 */
public static byte[] toByteArray(final ByteString bs) {
  return bs == null || bs.isEmpty() ? null : bs.toByteArray();
}