Java Code Examples for com.google.protobuf.ByteString

The following examples show how to use com.google.protobuf.ByteString. These examples are extracted from open source projects. 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
/** 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);
}
 
Example 2
Source Project: LiquidDonkey   Source File: KeyBagManager.java    License: MIT License 6 votes vote down vote up
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);
    }
}
 
Example 3
@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");
}
 
Example 4
Source Project: julongchain   Source File: Handler.java    License: Apache License 2.0 6 votes vote down vote up
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;
    }
}
 
Example 5
Source Project: j2objc   Source File: PerformanceBenchmarks.java    License: Apache License 2.0 6 votes vote down vote up
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));
      }
    }
  }
}
 
Example 6
Source Project: client-java   Source File: KVMockServer.java    License: Apache License 2.0 6 votes vote down vote up
/** */
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());
  }
}
 
Example 7
Source Project: client-java   Source File: PDClient.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 8
Source Project: tez   Source File: TestUnorderedPartitionedKVOutput2.java    License: Apache License 2.0 6 votes vote down vote up
@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));
  }
}
 
Example 9
Source Project: julongchain   Source File: SmartContractStubTest.java    License: Apache License 2.0 6 votes vote down vote up
@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()));
}
 
Example 10
Source Project: swellrt   Source File: MatrixUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
  }
}
 
Example 11
/**
 * 
 * @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;
}
 
Example 12
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);
}
 
Example 13
Source Project: bazel-buildfarm   Source File: CASFileCacheTest.java    License: Apache License 2.0 6 votes vote down vote up
@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
}
 
Example 14
Source Project: fabric-chaincode-java   Source File: InvocationStubImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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));

}
 
Example 15
Source Project: fdb-record-layer   Source File: UnionCursorContinuation.java    License: Apache License 2.0 5 votes vote down vote up
@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));
        }
    }
}
 
Example 16
/**
 * 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;
  }
}
 
Example 17
Source Project: swellrt   Source File: MongoDbDeltaStoreUtil.java    License: Apache License 2.0 5 votes vote down vote up
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);
  }
}
 
Example 18
Source Project: gsc-core   Source File: LogInfo.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
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();
}
 
Example 19
@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();
}
 
Example 20
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();
}
 
Example 21
Source Project: tez   Source File: ShuffleVertexManager.java    License: Apache License 2.0 5 votes vote down vote up
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());

}
 
Example 22
Source Project: j2objc   Source File: ByteStringTest.java    License: Apache License 2.0 5 votes vote down vote up
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));
}
 
Example 23
Source Project: reef   Source File: ClientService.java    License: Apache License 2.0 5 votes vote down vote up
@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());
  }
}
 
Example 24
Source Project: jelectrum   Source File: Util.java    License: MIT License 5 votes vote down vote up
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);
}
 
Example 25
Source Project: bazel-buildfarm   Source File: CASFileCacheTest.java    License: Apache License 2.0 5 votes vote down vote up
@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");
    }
  }
}
 
Example 26
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;
}
 
Example 27
Source Project: pulsar   Source File: SchemaRegistryServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@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);

        });

    }));
}
 
Example 28
Source Project: bisq   Source File: Mediator.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@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();
}
 
Example 29
Source Project: DBus   Source File: LogEventConvert_old.java    License: Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 30
Source Project: grpc-java   Source File: AbstractInteropTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
  }
}