com.google.protobuf.ByteString Java Examples
The following examples show how to use
com.google.protobuf.ByteString.
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: InvocationStubImpl.java From fabric-chaincode-java with Apache License 2.0 | 6 votes |
@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 #2
Source File: AccountPermissionUpdateOperatorTest.java From gsc-core with GNU Lesser General Public License v3.0 | 6 votes |
@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 #3
Source File: KeyBagManager.java From LiquidDonkey with MIT License | 6 votes |
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 #4
Source File: AndroidListenerIntents.java From android-chromium with BSD 2-Clause "Simplified" License | 6 votes |
/** 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 #5
Source File: Handler.java From julongchain with Apache License 2.0 | 6 votes |
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 #6
Source File: PerformanceBenchmarks.java From j2objc with Apache License 2.0 | 6 votes |
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 #7
Source File: KVMockServer.java From client-java with Apache License 2.0 | 6 votes |
/** */ 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 #8
Source File: PDClient.java From client-java with Apache License 2.0 | 6 votes |
@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 #9
Source File: TestUnorderedPartitionedKVOutput2.java From tez with Apache License 2.0 | 6 votes |
@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 #10
Source File: SmartContractStubTest.java From julongchain with Apache License 2.0 | 6 votes |
@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 #11
Source File: MatrixUtil.java From swellrt with Apache License 2.0 | 6 votes |
/** * 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 #12
Source File: StorageUtil.java From chain33-sdk-java with BSD 2-Clause "Simplified" License | 6 votes |
/** * * @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 #13
Source File: UnfreezeAssetOperatorTest.java From gsc-core with GNU Lesser General Public License v3.0 | 6 votes |
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 #14
Source File: CASFileCacheTest.java From bazel-buildfarm with Apache License 2.0 | 6 votes |
@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 #15
Source File: GroupChangeUtil.java From mollyim-android with GNU General Public License v3.0 | 5 votes |
private static void resolveField8DeletePendingMembers(DecryptedGroupChange conflictingChange, GroupChange.Actions.Builder result, HashMap<ByteString, DecryptedPendingMember> pendingMembersByUuid) { List<DecryptedPendingMemberRemoval> deletePendingMembersList = conflictingChange.getDeletePendingMembersList(); for (int i = deletePendingMembersList.size() - 1; i >= 0; i--) { DecryptedPendingMemberRemoval member = deletePendingMembersList.get(i); if (!pendingMembersByUuid.containsKey(member.getUuid())) { result.removeDeletePendingMembers(i); } } }
Example #16
Source File: UpdateAccount2Test.java From gsc-core with GNU Lesser General Public License v3.0 | 5 votes |
/** * 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 File: ProtocolBuilder.java From dremio-oss with Apache License 2.0 | 5 votes |
@Override public void handle(PhysicalConnection connection, int rpcType, ByteString pBody, ByteBuf dBody, ResponseSender sender) throws RpcException { MessageLite defaultInstance = defaultRequestInstances[rpcType]; try{ MessageLite value = defaultInstance.getParserForType().parseFrom(pBody); ArrowBuf dBody1 = dBody != null ? ((NettyArrowBuf) dBody).arrowBuf() : null; SentResponseMessage<MessageLite> response = handlers[rpcType].handle(value, dBody1); sender.send(new Response(new PseudoEnum(rpcType), response.getBody(), response.getBuffers())); } catch(Exception e){ final String fail = String.format("Failure consuming message for protocol[%d], request[%d] in the %s rpc layer.", getProtocolId(), rpcType, getConfig().getName()); throw new UserRpcException(NodeEndpoint.getDefaultInstance(), fail, e); } }
Example #18
Source File: GetAssetIssueByNameServlet.java From gsc-core with GNU Lesser General Public License v3.0 | 5 votes |
protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { String input = request.getReader().lines() .collect(Collectors.joining(System.lineSeparator())); Util.checkBodySize(input); boolean visible = Util.getVisiblePost(input); JSONObject jsonObject = JSON.parseObject(input); String value = jsonObject.getString("value"); if (visible) { value = Util.getHexString(value); } AssetIssueContract reply = wallet.getAssetIssueByName(ByteString.copyFrom(ByteArray.fromHexString(value))); if (reply != null) { response.getWriter().println(JsonFormat.printToString(reply, visible)); } else { response.getWriter().println("{}"); } } catch (Exception e) { logger.debug("Exception: {}", e.getMessage()); try { response.getWriter().println(Util.printErrorMsg(e)); } catch (IOException ioe) { logger.debug("IOException: {}", ioe.getMessage()); } } }
Example #19
Source File: KeyValueImplTest.java From fabric-chaincode-java with Apache License 2.0 | 5 votes |
@Test public void testKeyValueImpl() { new KeyValueImpl(KV.newBuilder() .setKey("key") .setValue(ByteString.copyFromUtf8("value")) .build()); }
Example #20
Source File: UnionCursorContinuation.java From fdb-record-layer with Apache License 2.0 | 5 votes |
@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 #21
Source File: MongoDbDeltaStoreUtil.java From swellrt with Apache License 2.0 | 5 votes |
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 #22
Source File: NcStreamDataCol.java From netcdf-java with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static ByteString copyArrayToByteString(Array data) { int nbytes = (int) data.getSizeBytes(); if (nbytes < 0) { logger.error("copyArrayToByteString neg byte size {} dataType = {} data size {} shape = {}", nbytes, data.getDataType().getSize(), data.getSize(), Arrays.toString(data.getShape())); } ByteBuffer bb = ByteBuffer.allocate(nbytes); bb.order(ByteOrder.nativeOrder()); copyArrayToBB(data, false, bb); bb.flip(); return ByteString.copyFrom(bb); }
Example #23
Source File: ProposalApproveOperatorTest.java From gsc-core with GNU Lesser General Public License v3.0 | 5 votes |
private Any getContract(String address, HashMap<Long, Long> paras) { return Any.pack( Contract.ProposalCreateContract.newBuilder() .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(address))) .putAllParameters(paras) .build()); }
Example #24
Source File: StartRawTest.java From ocraft-s2client with MIT License | 5 votes |
@Test void fulfillsEqualsContract() throws UnsupportedEncodingException { EqualsVerifier .forClass(StartRaw.class) .withPrefabValues( ByteString.class, ByteString.copyFrom("test", "UTF-8"), ByteString.copyFrom("test2", "UTF-8")) .withNonnullFields("mapSize", "pathingGrid", "terrainHeight", "placementGrid", "playableArea", "startLocations") .verify(); }
Example #25
Source File: PublicMethedForMutiSign.java From gsc-core with GNU Lesser General Public License v3.0 | 5 votes |
private static Permission json2Permission(JSONObject json) { Permission.Builder permissionBuilder = Permission.newBuilder(); if (json.containsKey("type")) { int type = json.getInteger("type"); permissionBuilder.setTypeValue(type); } if (json.containsKey("permission_name")) { String permissionName = json.getString("permission_name"); permissionBuilder.setPermissionName(permissionName); } if (json.containsKey("threshold")) { // long threshold = json.getLong("threshold"); long threshold = Long.parseLong(json.getString("threshold")); permissionBuilder.setThreshold(threshold); } if (json.containsKey("parent_id")) { int parentId = json.getInteger("parent_id"); permissionBuilder.setParentId(parentId); } if (json.containsKey("operations")) { byte[] operations = ByteArray.fromHexString(json.getString("operations")); permissionBuilder.setOperations(ByteString.copyFrom(operations)); } if (json.containsKey("keys")) { JSONArray keys = json.getJSONArray("keys"); List<Key> keyList = new ArrayList<>(); for (int i = 0; i < keys.size(); i++) { Key.Builder keyBuilder = Key.newBuilder(); JSONObject key = keys.getJSONObject(i); String address = key.getString("address"); // long weight = key.getLong("weight"); long weight = Long.parseLong(key.getString("weight")); keyBuilder.setAddress(ByteString.copyFrom(WalletClient.decodeFromBase58Check(address))); keyBuilder.setWeight(weight); keyList.add(keyBuilder.build()); } permissionBuilder.addAllKeys(keyList); } return permissionBuilder.build(); }
Example #26
Source File: CloudPayloadProtoBufEncoderImpl.java From Sparkplug with Eclipse Public License 1.0 | 5 votes |
private static void setProtoKuraMetricValue(KuraPayloadProto.KuraPayload.KuraMetric.Builder metric, Object o) throws KuraInvalidMetricTypeException { if (o instanceof String){ metric.setType(KuraPayloadProto.KuraPayload.KuraMetric.ValueType.STRING); metric.setStringValue((String)o); } else if (o instanceof Double){ metric.setType(KuraPayloadProto.KuraPayload.KuraMetric.ValueType.DOUBLE); metric.setDoubleValue((Double)o); } else if (o instanceof Integer){ metric.setType(KuraPayloadProto.KuraPayload.KuraMetric.ValueType.INT32); metric.setIntValue((Integer)o); } else if (o instanceof Float){ metric.setType(KuraPayloadProto.KuraPayload.KuraMetric.ValueType.FLOAT); metric.setFloatValue((Float)o); } else if (o instanceof Long){ metric.setType(KuraPayloadProto.KuraPayload.KuraMetric.ValueType.INT64); metric.setLongValue((Long)o); } else if (o instanceof Boolean){ metric.setType(KuraPayloadProto.KuraPayload.KuraMetric.ValueType.BOOL); metric.setBoolValue((Boolean)o); } else if (o instanceof byte[]) { metric.setType(KuraPayloadProto.KuraPayload.KuraMetric.ValueType.BYTES); metric.setBytesValue(ByteString.copyFrom((byte[])o)); } else if (o == null) { throw new KuraInvalidMetricTypeException("null value"); } else { throw new KuraInvalidMetricTypeException(o.getClass().getName()); } }
Example #27
Source File: LogInfo.java From gsc-core with GNU Lesser General Public License v3.0 | 5 votes |
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 #28
Source File: AbstractInteropTest.java From grpc-java with Apache License 2.0 | 5 votes |
@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); } }
Example #29
Source File: Mediator.java From bisq with GNU Affero General Public License v3.0 | 5 votes |
@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 #30
Source File: DataStoreV1Table.java From beam with Apache License 2.0 | 5 votes |
/** * Converts a {@code Row} value to an appropriate DataStore {@code Value} object. * * @param value {@code Row} value to convert. * @throws IllegalStateException when no mapping function for object of given type exists. * @return resulting {@code Value}. */ private Value mapObjectToValue(Object value) { if (value == null) { return Value.newBuilder().build(); } if (Boolean.class.equals(value.getClass())) { return makeValue((Boolean) value).build(); } else if (Byte.class.equals(value.getClass())) { return makeValue((Byte) value).build(); } else if (Long.class.equals(value.getClass())) { return makeValue((Long) value).build(); } else if (Short.class.equals(value.getClass())) { return makeValue((Short) value).build(); } else if (Integer.class.equals(value.getClass())) { return makeValue((Integer) value).build(); } else if (Double.class.equals(value.getClass())) { return makeValue((Double) value).build(); } else if (Float.class.equals(value.getClass())) { return makeValue((Float) value).build(); } else if (String.class.equals(value.getClass())) { return makeValue((String) value).build(); } else if (Instant.class.equals(value.getClass())) { return makeValue(((Instant) value).toDate()).build(); } else if (byte[].class.equals(value.getClass())) { return makeValue(ByteString.copyFrom((byte[]) value)).build(); } else if (value instanceof Row) { // Recursive conversion to handle nested rows. Row row = (Row) value; return makeValue(constructEntityFromRow(row.getSchema(), row)).build(); } else if (value instanceof Collection) { // Recursive to handle nested collections. Collection<Object> collection = (Collection<Object>) value; List<Value> arrayValues = collection.stream().map(this::mapObjectToValue).collect(Collectors.toList()); return makeValue(arrayValues).build(); } throw new IllegalStateException( "No conversion exists from type: " + value.getClass() + " to DataStove Value."); }