类com.google.protobuf.ByteString源码实例Demo

下面列出了怎么用com.google.protobuf.ByteString的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: android-chromium   文件: AndroidListenerIntents.java
/** Issues a registration retry with delay. */
static void issueDelayedRegistrationIntent(Context context, AndroidClock clock,
    ByteString clientId, ObjectId objectId, boolean isRegister, int delayMs, int requestCode) {
  RegistrationCommand command = isRegister ?
      AndroidListenerProtos.newDelayedRegisterCommand(clientId, objectId) :
          AndroidListenerProtos.newDelayedUnregisterCommand(clientId, objectId);
  Intent intent = new Intent()
      .putExtra(EXTRA_REGISTRATION, command.toByteArray())
      .setClass(context, AlarmReceiver.class);

  // Create a pending intent that will cause the AlarmManager to fire the above intent.
  PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent,
      PendingIntent.FLAG_ONE_SHOT);

  // Schedule the pending intent after the appropriate delay.
  AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
  long executeMs = clock.nowMs() + delayMs;
  alarmManager.set(AlarmManager.RTC, executeMs, pendingIntent);
}
 
源代码2 项目: LiquidDonkey   文件: KeyBagManager.java
public ByteString fileKey(ICloud.MBSFile file) {
    ICloud.MBSFileAttributes fileAttributes = file.getAttributes();

    if (!fileAttributes.hasEncryptionKey()) {
        logger.warn("-- fileKey() > no encryption key: {}", file.getRelativePath());
        return null;
    }

    ByteString uuid = fileAttributes.getEncryptionKey().substring(0, 0x10);

    KeyBag keyBag = uuidToKeyBag.get(uuid);

    if (keyBag == null) {
        logger.warn("-- fileKey() > no key bag for uuid: {}", Bytes.hex(uuid));
        return null;
    } else {
        return fileKeyFactory.fileKey(keyBag, file);
    }
}
 
@Test
public void witnessNeedless() {
  ByteString address = ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS));
  Permission ownerPermission = AccountWrapper.createDefaultOwnerPermission(address);
  Permission witnessPermission = AccountWrapper.createDefaultWitnessPermission(address);
  Permission activePermission = AccountWrapper.createDefaultActivePermission(address, dbManager);

  List<Permission> activeList = new ArrayList<>();
  activeList.add(activePermission);

  AccountPermissionUpdateOperator operator =
      new AccountPermissionUpdateOperator(
          getContract(address, ownerPermission, witnessPermission, activeList), dbManager);
  TransactionResultWrapper ret = new TransactionResultWrapper();

  processAndCheckInvalid(
      operator, ret, "account isn't witness can't set witness permission",
      "account isn't witness can't set witness permission");
}
 
源代码4 项目: julongchain   文件: Handler.java
public void add(PendingQueryResult pendingQueryResult, QueryResult queryResult) {
    try{
        ByteString queryResultsBytes = ((Message)queryResult).toByteString();
        SmartContractShim.QueryResultBytes[] arr = pendingQueryResult.getBatch();
        arr = Arrays.copyOf(arr, arr.length + 1);
        arr[arr.length - 1] = SmartContractShim.QueryResultBytes.newBuilder()
                .setResultBytes(queryResultsBytes)
                .build();
        pendingQueryResult.setBatch(arr);
        pendingQueryResult.setCount(arr.length);
    } catch (ClassCastException | ArrayIndexOutOfBoundsException e) {
        final RuntimeException error = new RuntimeException("No chaincode message found in event", e);
        log.error("Failed to get encode query result as bytes");
        throw error;
    }
}
 
源代码5 项目: j2objc   文件: PerformanceBenchmarks.java
private static void testAddRepeatedFieldsWithDescriptors() {
  List<FieldDescriptor> fields = getRepeatedFieldDescriptors();
  List<Object> values = new ArrayList<Object>();
  values.add(Integer.valueOf(1));
  values.add(Long.valueOf(2));
  values.add(Integer.valueOf(3));
  values.add(Long.valueOf(4));
  values.add(Boolean.TRUE);
  values.add(Float.valueOf(5.6f));
  values.add(Double.valueOf(7.8));
  values.add("foo");
  values.add(ByteString.copyFrom("bar".getBytes()));
  values.add(TypicalData.EnumType.VALUE1.getValueDescriptor());
  for (int i = 0; i < 150; i++) {
    TypicalData.Builder builder = TypicalData.newBuilder();
    for (int j = 0; j < 25; j++) {
      for (int k = 0; k < 10; k++) {
        builder.addRepeatedField(fields.get(k), values.get(k));
      }
    }
  }
}
 
源代码6 项目: client-java   文件: KVMockServer.java
/** */
public void rawPut(
    org.tikv.kvproto.Kvrpcpb.RawPutRequest request,
    io.grpc.stub.StreamObserver<org.tikv.kvproto.Kvrpcpb.RawPutResponse> responseObserver) {
  try {
    verifyContext(request.getContext());
    ByteString key = request.getKey();

    Kvrpcpb.RawPutResponse.Builder builder = Kvrpcpb.RawPutResponse.newBuilder();
    Integer errorCode = errorMap.remove(key);
    Errorpb.Error.Builder errBuilder = Errorpb.Error.newBuilder();
    if (errorCode != null) {
      setErrorInfo(errorCode, errBuilder);
      builder.setRegionError(errBuilder.build());
      // builder.setError("");
    }
    responseObserver.onNext(builder.build());
    responseObserver.onCompleted();
  } catch (Exception e) {
    responseObserver.onError(Status.INTERNAL.asRuntimeException());
  }
}
 
源代码7 项目: client-java   文件: PDClient.java
@Override
public TiRegion getRegionByKey(BackOffer backOffer, ByteString key) {
  Supplier<GetRegionRequest> request;
  if (conf.getKvMode() == KVMode.RAW) {
    request = () -> GetRegionRequest.newBuilder().setHeader(header).setRegionKey(key).build();
  } else {
    CodecDataOutput cdo = new CodecDataOutput();
    BytesCodec.writeBytes(cdo, key.toByteArray());
    ByteString encodedKey = cdo.toByteString();
    request =
        () -> GetRegionRequest.newBuilder().setHeader(header).setRegionKey(encodedKey).build();
  }

  PDErrorHandler<GetRegionResponse> handler =
      new PDErrorHandler<>(getRegionResponseErrorExtractor, this);

  GetRegionResponse resp = callWithRetry(backOffer, PDGrpc.METHOD_GET_REGION, request, handler);
  return new TiRegion(
      resp.getRegion(),
      resp.getLeader(),
      conf.getIsolationLevel(),
      conf.getCommandPriority(),
      conf.getKvMode());
}
 
源代码8 项目: tez   文件: TestUnorderedPartitionedKVOutput2.java
@Test(timeout = 5000)
public void testNonStartedOutput() throws Exception {
  OutputContext outputContext = OutputTestHelpers.createOutputContext();
  int numPartitions = 1;
  UnorderedPartitionedKVOutput output =
      new UnorderedPartitionedKVOutput(outputContext, numPartitions);
  output.initialize();
  List<Event> events = output.close();
  assertEquals(1, events.size());
  Event event1 = events.get(0);
  assertTrue(event1 instanceof CompositeDataMovementEvent);
  CompositeDataMovementEvent dme = (CompositeDataMovementEvent) event1;
  ByteBuffer bb = dme.getUserPayload();
  ShuffleUserPayloads.DataMovementEventPayloadProto shufflePayload =
      ShuffleUserPayloads.DataMovementEventPayloadProto.parseFrom(ByteString.copyFrom(bb));
  assertTrue(shufflePayload.hasEmptyPartitions());

  byte[] emptyPartitions = TezCommonUtils.decompressByteStringToByteArray(shufflePayload
      .getEmptyPartitions());
  BitSet emptyPartionsBitSet = TezUtilsInternal.fromByteArray(emptyPartitions);
  assertEquals(numPartitions, emptyPartionsBitSet.cardinality());
  for (int i = 0; i < numPartitions; i++) {
    assertTrue(emptyPartionsBitSet.get(i));
  }
}
 
源代码9 项目: julongchain   文件: SmartContractStubTest.java
@Test
public void getStateByRange() {
    final SmartContractStub stub = new SmartContractStub("myc", "txId", handler, Collections.emptyList(), null);
    final String startKey = "START";
    final String endKey = "END";
    final KvQueryResult.KV[] keyValues = new KvQueryResult.KV[]{
            KvQueryResult.KV.newBuilder()
                    .setKey("A")
                    .setValue(ByteString.copyFromUtf8("Value of A"))
                    .build(),
            KvQueryResult.KV.newBuilder()
                    .setKey("B")
                    .setValue(ByteString.copyFromUtf8("Value of B"))
                    .build()
    };
    final SmartContractShim.QueryResponse value = SmartContractShim.QueryResponse.newBuilder()
            .setHasMore(false)
            .addResults(SmartContractShim.QueryResultBytes.newBuilder().setResultBytes(keyValues[0].toByteString()))
            .addResults(SmartContractShim.QueryResultBytes.newBuilder().setResultBytes(keyValues[1].toByteString()))
            .build();
    when(handler.getStateByRange("myc", "txId", startKey, endKey)).thenReturn(value);
    assertThat(stub.getStateByRange(startKey, endKey), contains(Arrays.stream(keyValues).map(KeyValue::new).toArray()));
}
 
源代码10 项目: swellrt   文件: MatrixUtil.java
/**
 * Convert the signer information to JSON and place the result within the
 * passed JSONObject. This method should never fail.
 */
public static void protocolSignerInfoToJson(ProtocolSignerInfo signerInfo, JSONObject parent) {
  try {
    JSONObject signature = new JSONObject();
    parent.putOpt("signature", signature);
    signature.putOpt("domain", signerInfo.getDomain());
    ProtocolSignerInfo.HashAlgorithm hashValue = signerInfo.getHashAlgorithm();

    signature.putOpt("algorithm", hashValue.name());
    JSONArray certificate = new JSONArray();
    signature.putOpt("certificate", certificate);
    for (ByteString cert : signerInfo.getCertificateList()) {
      certificate.put(Base64Util.encode(cert));
    }
  } catch (JSONException ex) {
    throw new RuntimeException(ex);
  }
}
 
源代码11 项目: chain33-sdk-java   文件: StorageUtil.java
/**
 * 
 * @description 哈希存证模型,推荐使用sha256哈希,限制256位得摘要值
 * @param hash  长度固定为32字节
 * @return payload
 * 
 */
public static String createHashStorage(byte[] hash, String execer, String privateKey) {
    cn.chain33.javasdk.model.protobuf.StorageProtobuf.HashOnlyNotaryStorage.Builder hashStorageBuilder = StorageProtobuf.HashOnlyNotaryStorage.newBuilder();
    hashStorageBuilder.setHash(ByteString.copyFrom(hash));
    HashOnlyNotaryStorage hashOnlyNotaryStorage = hashStorageBuilder.build();
    cn.chain33.javasdk.model.protobuf.StorageProtobuf.StorageAction.Builder storageActionBuilder = StorageProtobuf.StorageAction.newBuilder();
    storageActionBuilder.setHashStorage(hashOnlyNotaryStorage);
    storageActionBuilder.setTy(StorageEnum.HashOnlyNotaryStorage.getTy());
    StorageAction storageAction = storageActionBuilder.build();
    
    String createTxWithoutSign = TransactionUtil.createTxWithoutSign(execer.getBytes(), storageAction.toByteArray(),
    		TransactionUtil.DEFAULT_FEE, 0);
    byte[] fromHexString = HexUtil.fromHexString(createTxWithoutSign);
    TransactionProtoBuf.Transaction parseFrom = null;
    try {
        parseFrom = TransactionProtoBuf.Transaction.parseFrom(fromHexString);
    } catch (InvalidProtocolBufferException e) {
        e.printStackTrace();
    }
    TransactionProtoBuf.Transaction signProbuf = TransactionUtil.signProbuf(parseFrom, privateKey);
    String hexString = HexUtil.toHexString(signProbuf.toByteArray());
    return hexString;
}
 
源代码12 项目: gsc-core   文件: UnfreezeAssetOperatorTest.java
private void createAssertBeforSameTokenNameActive() {
  dbManager.getDynamicPropertiesStore().saveAllowSameTokenName(0);

  long tokenId = dbManager.getDynamicPropertiesStore().getTokenIdNum();
  AssetIssueContract.Builder builder = AssetIssueContract.newBuilder();
  builder.setName(ByteString.copyFromUtf8(assetName));
  builder.setId(String.valueOf(tokenId));
  AssetIssueWrapper assetIssueWrapper = new AssetIssueWrapper(builder.build());
  dbManager.getAssetIssueStore().put(assetIssueWrapper.createDbKey(), assetIssueWrapper);
  dbManager.getAssetIssueV2Store().put(assetIssueWrapper.createDbV2Key(), assetIssueWrapper);

  AccountWrapper ownerWrapper =
      new AccountWrapper(
          ByteString.copyFromUtf8("owner"),
          StringUtil.hexString2ByteString(OWNER_ADDRESS),
          AccountType.Normal,
          initBalance);
  ownerWrapper.setAssetIssuedName(assetName.getBytes());
  ownerWrapper.setAssetIssuedID(assetIssueWrapper.createDbV2Key());
  dbManager.getAccountStore().put(ownerWrapper.createDbKey(), ownerWrapper);
}
 
源代码13 项目: bazel-buildfarm   文件: CASFileCacheTest.java
@Test
public void asyncWriteCompletionDischargesWriteSize() throws IOException {
  ByteString content = ByteString.copyFromUtf8("Hello, World");
  Digest digest = DIGEST_UTIL.compute(content);

  Write completingWrite = getWrite(digest);
  Write incompleteWrite = getWrite(digest);
  AtomicBoolean notified = new AtomicBoolean(false);
  // both should be size committed
  incompleteWrite.addListener(() -> notified.set(true), directExecutor());
  OutputStream incompleteOut = incompleteWrite.getOutput(1, SECONDS, () -> {});
  try (OutputStream out = completingWrite.getOutput(1, SECONDS, () -> {})) {
    assertThat(fileCache.size()).isEqualTo(digest.getSizeBytes() * 2);
    content.writeTo(out);
  }
  assertThat(notified.get()).isTrue();
  assertThat(fileCache.size()).isEqualTo(digest.getSizeBytes());
  assertThat(incompleteWrite.getCommittedSize()).isEqualTo(digest.getSizeBytes());
  assertThat(incompleteWrite.isComplete()).isTrue();
  incompleteOut.close(); // redundant
}
 
源代码14 项目: fabric-chaincode-java   文件: InvocationStubImpl.java
@Override
public QueryResultsIteratorWithMetadata<KeyValue> getQueryResultWithPagination(final String query,
        final int pageSize, final String bookmark) {

    final ByteString queryMetadataPayload = ChaincodeShim.QueryMetadata.newBuilder().setBookmark(bookmark)
            .setPageSize(pageSize).build().toByteString();
    final ByteString requestPayload = GetQueryResult.newBuilder().setCollection("").setQuery(query)
            .setMetadata(queryMetadataPayload).build().toByteString();
    final ChaincodeMessage requestMessage = ChaincodeMessageFactory.newEventMessage(GET_QUERY_RESULT, channelId,
            txId, requestPayload);
    final ByteString response = handler.invoke(requestMessage);

    return new QueryResultsIteratorWithMetadataImpl<KeyValue>(this.handler, channelId, txId, response,
            queryResultBytesToKv.andThen(KeyValueImpl::new));

}
 
源代码15 项目: fdb-record-layer   文件: UnionCursorContinuation.java
@Override
void setFirstChild(@Nonnull RecordCursorProto.UnionContinuation.Builder builder, @Nonnull RecordCursorContinuation continuation) {
    if (continuation.isEnd()) {
        builder.setFirstExhausted(true);
    } else {
        final byte[] asBytes = continuation.toBytes();
        if (asBytes != null) {
            builder.setFirstContinuation(ByteString.copyFrom(asBytes));
        }
    }
}
 
源代码16 项目: gsc-core   文件: UpdateAccount2Test.java
/**
 * constructor.
 */

public boolean unFreezeBalance(byte[] address, String priKey) {
  ECKey temKey = null;
  try {
    BigInteger priK = new BigInteger(priKey, 16);
    temKey = ECKey.fromPrivate(priK);
  } catch (Exception ex) {
    ex.printStackTrace();
  }
  final ECKey ecKey = temKey;
  Contract.UnfreezeBalanceContract.Builder builder = Contract.UnfreezeBalanceContract
      .newBuilder();
  ByteString byteAddreess = ByteString.copyFrom(address);

  builder.setOwnerAddress(byteAddreess);

  Contract.UnfreezeBalanceContract contract = builder.build();

  Protocol.Transaction transaction = blockingStubFull.unfreezeBalance(contract);

  if (transaction == null || transaction.getRawData().getContractCount() == 0) {
    return false;
  }

  transaction = TransactionUtils.setTimestamp(transaction);
  transaction = TransactionUtils.sign(transaction, ecKey);
  GrpcAPI.Return response = blockingStubFull.broadcastTransaction(transaction);
  if (response.getResult() == false) {
    return false;
  } else {
    return true;
  }
}
 
源代码17 项目: swellrt   文件: MongoDbDeltaStoreUtil.java
public static WaveletDeltaRecord deserializeWaveletDeltaRecord(DBObject dbObject)
    throws PersistenceException {
  try {
    return new WaveletDeltaRecord(
        deserializeHashedVersion((DBObject) dbObject.get(FIELD_APPLIEDATVERSION)),
        ByteStringMessage.parseProtocolAppliedWaveletDelta(ByteString.copyFrom((byte[]) dbObject
            .get(FIELD_APPLIED))),
        deserializeTransformedWaveletDelta((DBObject) dbObject.get(FIELD_TRANSFORMED)));

  } catch (InvalidProtocolBufferException e) {
    throw new PersistenceException(e);
  }
}
 
源代码18 项目: gsc-core   文件: LogInfo.java
public static Log buildLog(LogInfo logInfo) {
    List<ByteString> topics = Lists.newArrayList();
    logInfo.getTopics().forEach(topic -> {
        topics.add(ByteString.copyFrom(topic.getData()));
    });
    ByteString address = ByteString.copyFrom(logInfo.getAddress());
    ByteString data = ByteString.copyFrom(logInfo.getData());
    return Log.newBuilder().setAddress(address).addAllTopics(topics).setData(data).build();
}
 
@Override
public Payload serialize(@Nonnull Object what) {
  final Any any = requireAny(what);
  final String className = any.getTypeUrl();
  final ByteString payloadBytes = any.getValue();
  return Payload.newBuilder().setClassName(className).setPayloadBytes(payloadBytes).build();
}
 
源代码20 项目: gsc-core   文件: AccountWrapper.java
public static Permission createDefaultOwnerPermission(ByteString address) {
    Key.Builder key = Key.newBuilder();
    key.setAddress(address);
    key.setWeight(1);

    Permission.Builder owner = Permission.newBuilder();
    owner.setType(PermissionType.Owner);
    owner.setId(0);
    owner.setPermissionName("owner");
    owner.setThreshold(1);
    owner.setParentId(0);
    owner.addKeys(key);

    return owner.build();
}
 
源代码21 项目: tez   文件: ShuffleVertexManager.java
public static CustomShuffleEdgeManagerConfig fromUserPayload(
    UserPayload payload) throws InvalidProtocolBufferException {
  ShuffleEdgeManagerConfigPayloadProto proto =
      ShuffleEdgeManagerConfigPayloadProto.parseFrom(ByteString.copyFrom(payload.getPayload()));
  return new CustomShuffleEdgeManagerConfig(
      proto.getNumSourceTaskOutputs(),
      proto.getNumDestinationTasks(),
      proto.getBasePartitionRange(),
      proto.getRemainderRangeForLastShuffler());

}
 
源代码22 项目: j2objc   文件: ByteStringTest.java
public void testByteStringIsEqualAndHashCode() throws Exception {
  ByteString s1 = ByteString.copyFrom("foo".getBytes("UTF-8"));
  ByteString s2 = ByteString.copyFrom("foo".getBytes("UTF-8"));
  ByteString s3 = ByteString.copyFrom("bar".getBytes("UTF-8"));
  assertTrue(s1.equals(s2));
  assertTrue(s2.equals(s1));
  assertEquals(s1.hashCode(), s2.hashCode());
  assertFalse(s1.equals(s3));
  assertFalse(s3.equals(s2));
}
 
源代码23 项目: reef   文件: ClientService.java
@Override
public void onNext(final FailedRuntime error) {
  LOG.log(Level.SEVERE, "Received a resource manager error", error.getReason());
  theJob = null;
  setStatusAndNotify(LauncherStatus.failed(error.getReason()));
  if (clientStub != null) {
    clientStub.runtimeErrorHandler(ExceptionInfo.newBuilder()
        .setMessage(error.getMessage())
        .setName(error.getId())
        .setData(error.getReason().isPresent() ?
            getRootCause(error.getReason().get()) : ByteString.EMPTY)
        .build());
  }
}
 
源代码24 项目: jelectrum   文件: Util.java
public static ByteString reverse(ByteString in)
{
  byte b[]=in.toByteArray();
  byte o[]=new byte[b.length];

  for(int i=0; i<b.length; i++)
  {
    o[i]=b[b.length-1-i];
  }
  return ByteString.copyFrom(o);
}
 
源代码25 项目: bazel-buildfarm   文件: CASFileCacheTest.java
@Test
public void expireEntryWaitsForUnreferencedEntry()
    throws ExecutionException, IOException, InterruptedException {
  byte[] bigData = new byte[1023];
  Arrays.fill(bigData, (byte) 1);
  ByteString bigContent = ByteString.copyFrom(bigData);
  Digest bigDigest = DIGEST_UTIL.compute(bigContent);
  blobs.put(bigDigest, bigContent);
  Path bigPath = fileCache.put(bigDigest, /* isExecutable=*/ false);

  AtomicBoolean started = new AtomicBoolean(false);
  ExecutorService service = newSingleThreadExecutor();
  Future<Void> putFuture =
      service.submit(
          new Callable<Void>() {
            @Override
            public Void call() throws IOException, InterruptedException {
              started.set(true);
              ByteString content = ByteString.copyFromUtf8("CAS Would Exceed Max Size");
              Digest digest = DIGEST_UTIL.compute(content);
              blobs.put(digest, content);
              fileCache.put(digest, /* isExecutable=*/ false);
              return null;
            }
          });
  while (!started.get()) {
    MICROSECONDS.sleep(1);
  }
  // minimal test to ensure that we're blocked
  assertThat(putFuture.isDone()).isFalse();
  decrementReference(bigPath);
  try {
    putFuture.get();
  } finally {
    if (!shutdownAndAwaitTermination(service, 1, SECONDS)) {
      throw new RuntimeException("could not shut down service");
    }
  }
}
 
源代码26 项目: GreenBits   文件: DeterministicKeyChain.java
protected List<Protos.Key> serializeMyselfToProtobuf() {
    // Most of the serialization work is delegated to the basic key chain, which will serialize the bulk of the
    // data (handling encryption along the way), and letting us patch it up with the extra data we care about.
    LinkedList<Protos.Key> entries = newLinkedList();
    if (seed != null) {
        Protos.Key.Builder mnemonicEntry = BasicKeyChain.serializeEncryptableItem(seed);
        mnemonicEntry.setType(Protos.Key.Type.DETERMINISTIC_MNEMONIC);
        serializeSeedEncryptableItem(seed, mnemonicEntry);
        entries.add(mnemonicEntry.build());
    }
    Map<ECKey, Protos.Key.Builder> keys = basicKeyChain.serializeToEditableProtobufs();
    for (Map.Entry<ECKey, Protos.Key.Builder> entry : keys.entrySet()) {
        DeterministicKey key = (DeterministicKey) entry.getKey();
        Protos.Key.Builder proto = entry.getValue();
        proto.setType(Protos.Key.Type.DETERMINISTIC_KEY);
        final Protos.DeterministicKey.Builder detKey = proto.getDeterministicKeyBuilder();
        detKey.setChainCode(ByteString.copyFrom(key.getChainCode()));
        for (ChildNumber num : key.getPath())
            detKey.addPath(num.i());
        if (key.equals(externalParentKey)) {
            detKey.setIssuedSubkeys(issuedExternalKeys);
            detKey.setLookaheadSize(lookaheadSize);
            detKey.setSigsRequiredToSpend(getSigsRequiredToSpend());
        } else if (key.equals(internalParentKey)) {
            detKey.setIssuedSubkeys(issuedInternalKeys);
            detKey.setLookaheadSize(lookaheadSize);
            detKey.setSigsRequiredToSpend(getSigsRequiredToSpend());
        }
        // Flag the very first key of following keychain.
        if (entries.isEmpty() && isFollowing()) {
            detKey.setIsFollowing(true);
        }
        if (key.getParent() != null) {
            // HD keys inherit the timestamp of their parent if they have one, so no need to serialize it.
            proto.clearCreationTimestamp();
        }
        entries.add(proto.build());
    }
    return entries;
}
 
源代码27 项目: pulsar   文件: SchemaRegistryServiceImpl.java
@Override
@NotNull
public CompletableFuture<SchemaVersion> putSchemaIfAbsent(String schemaId, SchemaData schema,
                                                          SchemaCompatibilityStrategy strategy) {
    return trimDeletedSchemaAndGetList(schemaId).thenCompose(schemaAndMetadataList ->
            getSchemaVersionBySchemaData(schemaAndMetadataList, schema).thenCompose(schemaVersion -> {
        if (schemaVersion != null) {
            return CompletableFuture.completedFuture(schemaVersion);
        }
        CompletableFuture<Void> checkCompatibilityFurture = new CompletableFuture<>();
        if (schemaAndMetadataList.size() != 0) {
            if (isTransitiveStrategy(strategy)) {
                checkCompatibilityFurture = checkCompatibilityWithAll(schema, strategy, schemaAndMetadataList);
            } else {
                checkCompatibilityFurture = checkCompatibilityWithLatest(schemaId, schema, strategy);
            }
        } else {
            checkCompatibilityFurture.complete(null);
        }
        return checkCompatibilityFurture.thenCompose(v -> {
            byte[] context = hashFunction.hashBytes(schema.getData()).asBytes();
            SchemaRegistryFormat.SchemaInfo info = SchemaRegistryFormat.SchemaInfo.newBuilder()
                    .setType(Functions.convertFromDomainType(schema.getType()))
                    .setSchema(ByteString.copyFrom(schema.getData()))
                    .setSchemaId(schemaId)
                    .setUser(schema.getUser())
                    .setDeleted(false)
                    .setTimestamp(clock.millis())
                    .addAllProps(toPairs(schema.getProps()))
                    .build();
            return schemaStorage.put(schemaId, info.toByteArray(), context);

        });

    }));
}
 
源代码28 项目: bisq   文件: Mediator.java
@Override
public protobuf.StoragePayload toProtoMessage() {
    final protobuf.Mediator.Builder builder = protobuf.Mediator.newBuilder()
            .setNodeAddress(nodeAddress.toProtoMessage())
            .setPubKeyRing(pubKeyRing.toProtoMessage())
            .addAllLanguageCodes(languageCodes)
            .setRegistrationDate(registrationDate)
            .setRegistrationPubKey(ByteString.copyFrom(registrationPubKey))
            .setRegistrationSignature(registrationSignature);
    Optional.ofNullable(emailAddress).ifPresent(builder::setEmailAddress);
    Optional.ofNullable(info).ifPresent(builder::setInfo);
    Optional.ofNullable(extraDataMap).ifPresent(builder::putAllExtraData);
    return protobuf.StoragePayload.newBuilder().setMediator(builder).build();
}
 
源代码29 项目: DBus   文件: LogEventConvert_old.java
public static Entry createEntry(Header header, EntryType entryType, ByteString storeValue) {
    Entry.Builder entryBuilder = Entry.newBuilder();
    entryBuilder.setHeader(header);
    entryBuilder.setEntryType(entryType);
    entryBuilder.setStoreValue(storeValue);
    return entryBuilder.build();
}
 
源代码30 项目: grpc-java   文件: AbstractInteropTest.java
@Test
public void clientStreaming() throws Exception {
  final List<StreamingInputCallRequest> requests = Arrays.asList(
      StreamingInputCallRequest.newBuilder()
          .setPayload(Payload.newBuilder()
              .setBody(ByteString.copyFrom(new byte[27182])))
          .build(),
      StreamingInputCallRequest.newBuilder()
          .setPayload(Payload.newBuilder()
              .setBody(ByteString.copyFrom(new byte[8])))
          .build(),
      StreamingInputCallRequest.newBuilder()
          .setPayload(Payload.newBuilder()
              .setBody(ByteString.copyFrom(new byte[1828])))
          .build(),
      StreamingInputCallRequest.newBuilder()
          .setPayload(Payload.newBuilder()
              .setBody(ByteString.copyFrom(new byte[45904])))
          .build());
  final StreamingInputCallResponse goldenResponse = StreamingInputCallResponse.newBuilder()
      .setAggregatedPayloadSize(74922)
      .build();

  StreamRecorder<StreamingInputCallResponse> responseObserver = StreamRecorder.create();
  StreamObserver<StreamingInputCallRequest> requestObserver =
      asyncStub.streamingInputCall(responseObserver);
  for (StreamingInputCallRequest request : requests) {
    requestObserver.onNext(request);
  }
  requestObserver.onCompleted();

  assertEquals(goldenResponse, responseObserver.firstValue().get());
  responseObserver.awaitCompletion();
  assertThat(responseObserver.getValues()).hasSize(1);
  Throwable t = responseObserver.getError();
  if (t != null) {
    throw new AssertionError(t);
  }
}
 
 类所在包
 同包方法