Java Code Examples for com.google.protobuf.ByteString#isEmpty()

The following examples show how to use com.google.protobuf.ByteString#isEmpty() . 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: ScanIterator.java    From client-java with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 2
Source File: RangeSplitter.java    From tikv-client-lib-java with Apache License 2.0 6 votes vote down vote up
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));
}
 
Example 3
Source File: AccountStateCallBack.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
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");
    }
}
 
Example 4
Source File: Wallet.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
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();
}
 
Example 5
Source File: Wallet.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
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();
}
 
Example 6
Source File: ByteStreamServiceWriter.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
@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());
  }
}
 
Example 7
Source File: V2TxnDecoder.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 8
Source File: LazyHistogram.java    From glowroot with Apache License 2.0 5 votes vote down vote up
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));
    }
}
 
Example 9
Source File: ByteStreamService.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
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();
    }
  };
}
 
Example 10
Source File: KeyRangeUtils.java    From tikv-client-lib-java with Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 11
Source File: ChaincodeActionDeserializer.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
ChaincodeEvent getEvent() {
    ProposalPackage.ChaincodeAction ca = getChaincodeAction();
    ByteString eventsBytes = ca.getEvents();
    if (eventsBytes == null || eventsBytes.isEmpty()) {
        return null;
    }

    return new ChaincodeEvent(eventsBytes);
}
 
Example 12
Source File: LazyHistogram.java    From glowroot with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 13
Source File: TargetState.java    From firebase-android-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
  }
}
 
Example 14
Source File: PBTransactions.java    From WavesJ with MIT License 4 votes vote down vote up
public static String toVanillaAssetId(final ByteString assetId) {
    if (assetId.isEmpty()) return Asset.WAVES;
    else return Asset.normalize(Base58.encode(assetId.toByteArray()));
}
 
Example 15
Source File: AccountPermissionUpdateOperator.java    From gsc-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
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;
}
 
Example 16
Source File: HistoryLevelDB.java    From julongchain with Apache License 2.0 4 votes vote down vote up
@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));
  }
 
Example 17
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 18
Source File: WriteStreamObserver.java    From bazel-buildfarm with Apache License 2.0 4 votes vote down vote up
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();
    }
  }
}
 
Example 19
Source File: Assert.java    From cloud-spanner-r2dbc with Apache License 2.0 3 votes vote down vote up
/**
 * 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;
}
 
Example 20
Source File: GRPCUtils.java    From reef with Apache License 2.0 2 votes vote down vote up
/**
 * 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();
}