com.google.protobuf.Any Java Examples

The following examples show how to use com.google.protobuf.Any. 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: JsonMapperProvider.java    From conductor with Apache License 2.0 6 votes vote down vote up
@Override
public Any deserialize(JsonParser p, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    JsonNode root = p.getCodec().readTree(p);
    JsonNode type = root.get(JSON_TYPE);
    JsonNode value = root.get(JSON_VALUE);

    if (type == null || !type.isTextual()) {
        ctxt.reportMappingException("invalid '@type' field when deserializing ProtoBuf Any object");
    }

    if (value == null || !value.isTextual()) {
        ctxt.reportMappingException("invalid '@value' field when deserializing ProtoBuf Any object");
    }

    return Any.newBuilder()
            .setTypeUrl(type.textValue())
            .setValue(ByteString.copyFrom(value.binaryValue()))
            .build();
}
 
Example #2
Source File: ChannelzProtoUtil.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
static SocketOption toSocketOptionLinger(int lingerSeconds) {
  final SocketOptionLinger lingerOpt;
  if (lingerSeconds >= 0) {
    lingerOpt = SocketOptionLinger
        .newBuilder()
        .setActive(true)
        .setDuration(Durations.fromSeconds(lingerSeconds))
        .build();
  } else {
    lingerOpt = SocketOptionLinger.getDefaultInstance();
  }
  return SocketOption
      .newBuilder()
      .setName(SO_LINGER)
      .setAdditional(Any.pack(lingerOpt))
      .build();
}
 
Example #3
Source File: RequestReplyFunctionTest.java    From flink-statefun with Apache License 2.0 6 votes vote down vote up
@Test
public void stateIsModified() {
  functionUnderTest.invoke(context, Any.getDefaultInstance());

  // A message returned from the function
  // that asks to put "hello" into the session state.
  FromFunction response =
      FromFunction.newBuilder()
          .setInvocationResult(
              InvocationResponse.newBuilder()
                  .addStateMutations(
                      PersistedValueMutation.newBuilder()
                          .setStateValue(ByteString.copyFromUtf8("hello"))
                          .setMutationType(MutationType.MODIFY)
                          .setStateName("session")))
          .build();

  functionUnderTest.invoke(context, successfulAsyncOperation(response));

  functionUnderTest.invoke(context, Any.getDefaultInstance());
  assertThat(client.capturedState(0), is(ByteString.copyFromUtf8("hello")));
}
 
Example #4
Source File: ClientRPCStoreTest.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Test 
public void testRequestToJSON() throws JsonParseException, IOException, NoSuchMethodException, SecurityException
{
	mockClientConfigHandler.addListener((ClientConfigUpdateListener) EasyMock.anyObject());
	EasyMock.expectLastCall().once();
	replay(mockClientConfigHandler);
	final String client = "test";
	ClientRpcStore store = new ClientRpcStore(mockClientConfigHandler);
	CustomPredictRequest customRequest =  CustomPredictRequest.newBuilder().addData(1.0f).build();
	store.add(client, customRequest.getClass(), null,customRequest.getClass().getMethod("newBuilder"),null);
	Any anyMsg = Any.pack(customRequest);
	ClassificationRequestMeta meta = ClassificationRequestMeta.newBuilder().setPuid("1234").build();
	ClassificationRequest request = ClassificationRequest.newBuilder().setMeta(meta).setData(anyMsg).build();
	JsonNode json = store.getJSONForRequest(client, request);
	Assert.assertNotNull(json);
	System.out.println(json);
	ObjectMapper mapper = new ObjectMapper();
    JsonFactory factory = mapper.getFactory();
    JsonParser parser = factory.createParser(json.toString());
    JsonNode actualObj = mapper.readTree(parser);
    ClassificationRequest req = store.getPredictRequestFromJson(client, actualObj);
    Assert.assertNotNull(req);
}
 
Example #5
Source File: DistkvNewSqlListener.java    From distkv with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void enterSlistTop(DistkvNewSQLParser.SlistTopContext ctx) {
  Preconditions.checkState(parsedResult == null);
  Preconditions.checkState(ctx.children.size() == 3);

  SlistProtocol.SlistTopRequest.Builder slistTopRequestBuilder =
      SlistProtocol.SlistTopRequest.newBuilder();
  slistTopRequestBuilder.setCount(Integer.parseInt(ctx.children.get(2).getText()));
  DistkvRequest request = DistkvRequest.newBuilder()
      .setKey(ctx.children.get(1).getText())
      .setRequestType(SLIST_TOP)
      .setRequest(Any.pack(slistTopRequestBuilder.build()))
      .build();
  parsedResult = new DistkvParsedResult(
      SLIST_TOP, request);
}
 
Example #6
Source File: RemoteMessageDeserializer.java    From android-test with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public Object fromProto(@NonNull MessageLite messageLite) {
  checkNotNull(messageLite, "messageLite cannot be null!");
  try {
    RemoteDescriptor remoteDescriptor =
        messageLite instanceof Any
            // For Any protos get the remote through the type url
            ? remoteDescriptorRegistry.argForRemoteTypeUrl(((Any) messageLite).getTypeUrl())
            // For All other msg types get remote type descriptor for proto message "runtime" type
            : remoteDescriptorRegistry.argForMsgType(messageLite.getClass());
    return fromProtoInternal(messageLite, remoteDescriptor);
  } catch (Exception e) {
    if (e.getCause() instanceof RemoteProtocolException) {
      throw (RemoteProtocolException) e;
    }
    throw new RemoteProtocolException("Error: " + e.getMessage(), e);
  }
}
 
Example #7
Source File: SetRpcTest.java    From distkv with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static void testRemoveItem(int rpcServerPort) {
  try (ProxyOnClient<DistkvService> setProxy = new ProxyOnClient<>(
      DistkvService.class, rpcServerPort)) {
    DistkvService setService = setProxy.getService();
    SetProtocol.SetRemoveItemRequest.Builder setRemoveRequestBuilder =
        SetProtocol.SetRemoveItemRequest.newBuilder();
    setRemoveRequestBuilder.setItemValue("v1");
    DistkvRequest request = DistkvRequest.newBuilder()
        .setKey("k1")
        .setRequestType(RequestType.SET_REMOVE_ITEM)
        .setRequest(Any.pack(setRemoveRequestBuilder.build()))
        .build();
    DistkvResponse setDeleteResponse = FutureUtils.get(
        setService.call(request));
    Assert.assertEquals(CommonProtocol.Status.OK, setDeleteResponse.getStatus());
  }
}
 
Example #8
Source File: TransactionWrapper.java    From gsc-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static byte[] getToAddress(Transaction.Contract contract) {
    ByteString to;
    try {
        Any contractParameter = contract.getParameter();
        switch (contract.getType()) {
            case TransferAssetContract:
                to = contractParameter.unpack(TransferAssetContract.class).getToAddress();
                break;
            case TransferContract:
                to = contractParameter.unpack(TransferContract.class).getToAddress();
                break;
            case ParticipateAssetIssueContract:
                to = contractParameter.unpack(ParticipateAssetIssueContract.class).getToAddress();
                break;
            // todo add other contract

            default:
                return null;
        }
        return to.toByteArray();
    } catch (Exception ex) {
        logger.error(ex.getMessage());
        return null;
    }
}
 
Example #9
Source File: DistkvNewSqlListener.java    From distkv with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void enterListLput(DistkvNewSQLParser.ListLputContext ctx) {
  Preconditions.checkState(parsedResult == null);
  Preconditions.checkState(ctx.children.size() == 3);
  ListProtocol.ListLPutRequest.Builder builder = ListProtocol.ListLPutRequest.newBuilder();
  final int valueSize = ctx.children.get(2).getChildCount();
  for (int i = 0; i < valueSize; ++i) {
    builder.addValues(ctx.children.get(2).getChild(i).getText());
  }
  DistkvRequest request = DistkvRequest.newBuilder()
      .setKey(ctx.children.get(1).getText())
      .setRequestType(LIST_LPUT)
      .setRequest(Any.pack(builder.build()))
      .build();
  parsedResult = new DistkvParsedResult(LIST_LPUT, request);
}
 
Example #10
Source File: ModelDBUtils.java    From modeldb with Apache License 2.0 6 votes vote down vote up
/**
 * If so throws an error if the workspace type is USER and the workspaceId and userID do not
 * match. Is a NO-OP if userinfo is null.
 */
public static void checkPersonalWorkspace(
    UserInfo userInfo,
    WorkspaceType workspaceType,
    String workspaceId,
    String resourceNameString) {
  if (userInfo != null
      && workspaceType == WorkspaceType.USER
      && !workspaceId.equals(userInfo.getVertaInfo().getUserId())) {
    Status status =
        Status.newBuilder()
            .setCode(Code.PERMISSION_DENIED_VALUE)
            .setMessage(
                "Creation of "
                    + resourceNameString
                    + " in other user's workspace is not permitted")
            .addDetails(Any.pack(UpdateProjectName.Response.getDefaultInstance()))
            .build();
    throw StatusProto.toStatusRuntimeException(status);
  }
}
 
Example #11
Source File: DistkvNewSqlListener.java    From distkv with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void enterDictPut(DistkvNewSQLParser.DictPutContext ctx) {
  Preconditions.checkState(parsedResult == null);
  Preconditions.checkState(ctx.children.size() == 3);
  DictProtocol.DictPutRequest.Builder builder = DictProtocol.DictPutRequest.newBuilder();
  final ParseTree keyValuePairsParseTree = ctx.children.get(2);
  final int numKeyValuePairs = keyValuePairsParseTree.getChildCount();
  DictProtocol.DistKVDict.Builder distKVDictBuilder = DictProtocol.DistKVDict.newBuilder();
  for (int i = 0; i < numKeyValuePairs; ++i) {
    final ParseTree keyValuePairParseTree = keyValuePairsParseTree.getChild(i);
    Preconditions.checkState(keyValuePairParseTree.getChildCount() == 2);
    distKVDictBuilder.addKeys(keyValuePairParseTree.getChild(0).getText());
    distKVDictBuilder.addValues(keyValuePairParseTree.getChild(1).getText());
  }
  builder.setDict(distKVDictBuilder.build());
  DistkvRequest request = DistkvRequest.newBuilder()
      .setKey(ctx.children.get(1).getText())
      .setRequestType(DICT_PUT)
      .setRequest(Any.pack(builder.build()))
      .build();
  parsedResult = new DistkvParsedResult(DICT_PUT, request);
}
 
Example #12
Source File: DaprClientGrpc.java    From java-sdk with MIT License 6 votes vote down vote up
/**
 * Builds the object io.dapr.{@link DaprProtos.InvokeServiceRequest} to be send based on the parameters.
 *
 * @param verb    String that must match HTTP Methods
 * @param appId   The application id to be invoked
 * @param method  The application method to be invoked
 * @param request The body of the request to be send as part of the invokation
 * @param <K>     The Type of the Body
 * @return The object to be sent as part of the invokation.
 * @throws IOException If there's an issue serializing the request.
 */
private <K> DaprProtos.InvokeServiceRequest buildInvokeServiceRequest(
    String verb, String appId, String method, K request) throws IOException {
  CommonProtos.InvokeRequest.Builder requestBuilder = CommonProtos.InvokeRequest.newBuilder();
  requestBuilder.setMethod(method);
  if (request != null) {
    byte[] byteRequest = objectSerializer.serialize(request);
    Any data = Any.newBuilder().setValue(ByteString.copyFrom(byteRequest)).build();
    requestBuilder.setData(data);
  } else {
    requestBuilder.setData(Any.newBuilder().build());
  }

  CommonProtos.HTTPExtension.Builder httpExtensionBuilder = CommonProtos.HTTPExtension.newBuilder();
  if ((verb != null) && !verb.isEmpty()) {
    httpExtensionBuilder.setVerb(CommonProtos.HTTPExtension.Verb.valueOf(verb.toUpperCase()));
  } else {
    httpExtensionBuilder.setVerb(CommonProtos.HTTPExtension.Verb.NONE);
  }
  requestBuilder.setHttpExtension(httpExtensionBuilder.build());

  DaprProtos.InvokeServiceRequest.Builder envelopeBuilder = DaprProtos.InvokeServiceRequest.newBuilder()
      .setId(appId)
      .setMessage(requestBuilder.build());
  return envelopeBuilder.build();
}
 
Example #13
Source File: DistkvAsyncListProxy.java    From distkv with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CompletableFuture<DistkvProtocol.DistkvResponse> mremove(
    String key, List<Integer> indexes) {
  ListProtocol.ListMRemoveRequest listMRemoveRequest = ListProtocol.ListMRemoveRequest
      .newBuilder()
      .addAllIndexes(indexes)
      .build();

  DistkvProtocol.DistkvRequest request = DistkvProtocol.DistkvRequest.newBuilder()
      .setKey(key)
      .setRequestType(RequestType.LIST_MREMOVE)
      .setRequest(Any.pack(listMRemoveRequest))
      .build();
  return call(request);
}
 
Example #14
Source File: GrpcBurstNodeService.java    From burstkit4j with Apache License 2.0 5 votes vote down vote up
private BrsApi.BasicTransaction.Builder basicTransaction(byte[] senderPublicKey, BurstValue amount, BurstValue fee, int deadline, Any attachment) {
    BurstCrypto burstCrypto = BurstCrypto.getInstance();
    return BrsApi.BasicTransaction.newBuilder()
            .setSenderPublicKey(ByteString.copyFrom(senderPublicKey))
            .setSenderId(burstCrypto.getBurstAddressFromPublic(senderPublicKey).getSignedLongId())
            .setAmount(amount.toPlanck().longValueExact())
            .setFee(fee.toPlanck().longValueExact())
            .setDeadline(deadline)
            .setAttachment(attachment);
}
 
Example #15
Source File: DistkvAsyncListProxy.java    From distkv with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CompletableFuture<DistkvProtocol.DistkvResponse> remove(
    String key, Integer from, Integer end) {
  ListProtocol.ListRemoveRequest listRemoveRequest = ListProtocol.ListRemoveRequest.newBuilder()
      .setType(ListProtocol.RemoveType.RemoveRange)
      .setFrom(from)
      .setEnd(end)
      .build();

  DistkvProtocol.DistkvRequest request = DistkvProtocol.DistkvRequest.newBuilder()
      .setKey(key)
      .setRequestType(RequestType.LIST_REMOVE)
      .setRequest(Any.pack(listRemoveRequest))
      .build();
  return call(request);
}
 
Example #16
Source File: TransferAssetOperatorTest.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Any getContract(long sendCoin, String assetName) {
  return Any.pack(
      Contract.TransferAssetContract.newBuilder()
          .setAssetName(ByteString.copyFrom(ByteArray.fromString(assetName)))
          .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)))
          .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(TO_ADDRESS)))
          .setAmount(sendCoin)
          .build());
}
 
Example #17
Source File: ShardInstanceTest.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@Test
public void watchOperationFutureIsErrorForObserveException()
    throws IOException, InterruptedException {
  RuntimeException observeException = new RuntimeException();
  Watcher watcher = mock(Watcher.class);
  doAnswer(
          (invocation) -> {
            throw observeException;
          })
      .when(watcher)
      .observe(any(Operation.class));
  Operation errorObserveOperation =
      Operation.newBuilder()
          .setName("error-observe-operation")
          .setMetadata(Any.pack(ExecuteOperationMetadata.newBuilder().build()))
          .build();
  when(mockBackplane.getOperation(errorObserveOperation.getName()))
      .thenReturn(errorObserveOperation);
  ListenableFuture<Void> future =
      instance.watchOperation(errorObserveOperation.getName(), watcher);
  boolean caughtException = false;
  try {
    future.get();
  } catch (ExecutionException e) {
    assertThat(e.getCause()).isEqualTo(observeException);
    caughtException = true;
  }
  assertThat(caughtException).isTrue();
}
 
Example #18
Source File: DatasetVersionServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteDatasetVersions(
    DeleteDatasetVersions request,
    StreamObserver<DeleteDatasetVersions.Response> responseObserver) {
  QPSCountResource.inc();
  LOGGER.trace("Deleting dataset version.");
  try (RequestLatencyResource latencyResource =
      new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) {
    /*Parameter validation*/
    if (request.getIdsList().isEmpty()) {
      logAndThrowError(
          ModelDBMessages.DATASET_VERSION_ID_NOT_FOUND_IN_REQUEST,
          Code.INVALID_ARGUMENT_VALUE,
          Any.pack(DeleteDatasetVersion.Response.getDefaultInstance()));
    }

    boolean deleteStatus = datasetVersionDAO.deleteDatasetVersions(request.getIdsList());

    responseObserver.onNext(
        DeleteDatasetVersions.Response.newBuilder().setStatus(deleteStatus).build());
    responseObserver.onCompleted();

  } catch (Exception e) {
    ModelDBUtils.observeError(
        responseObserver, e, DeleteDatasetVersions.Response.getDefaultInstance());
  }
}
 
Example #19
Source File: CommentServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
private Comment getUpdatedCommentFromRequest(UpdateComment request, UserInfo userInfo) {

    String errorMessage = null;
    if (request.getEntityId().isEmpty()
        && request.getMessage().isEmpty()
        && request.getId().isEmpty()) {
      errorMessage =
          "Entity ID and Comment message and Comment ID not found in UpdateComment request";
    } else if (request.getEntityId().isEmpty()) {
      errorMessage = "Entity ID not found in UpdateComment request";
    } else if (request.getMessage().isEmpty()) {
      errorMessage = "Comment message not found in UpdateComment request";
    } else if (request.getId().isEmpty()) {
      errorMessage = "Comment ID is not found in UpdateComment request";
    }

    if (errorMessage != null) {
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(errorMessage)
              .addDetails(Any.pack(UpdateComment.Response.getDefaultInstance()))
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    return Comment.newBuilder()
        .setId(request.getId())
        .setUserId(userInfo != null ? userInfo.getUserId() : "")
        .setVertaId(authService.getVertaIdFromUserInfo(userInfo))
        .setDateTime(Calendar.getInstance().getTimeInMillis())
        .setMessage(request.getMessage())
        .build();
  }
 
Example #20
Source File: TransactionTraceTest.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void testUseFee()
    throws InvalidProtocolBufferException, VMIllegalException, BalanceInsufficientException, ContractExeException, ContractValidateException {
  String contractName = "tracetestContract";
  String code = "608060405234801561001057600080fd5b5060005b6103e8811015610037576000818152602081905260409020819055600a01610014565b5061010f806100476000396000f30060806040526004361060525763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416634903b0d181146057578063da31158814607e578063fe4ba936146093575b600080fd5b348015606257600080fd5b50606c60043560ad565b60408051918252519081900360200190f35b348015608957600080fd5b50606c60043560bf565b348015609e57600080fd5b5060ab60043560243560d1565b005b60006020819052908152604090205481565b60009081526020819052604090205490565b600091825260208290526040909120555600a165627a7a723058200596e6c0a5371c2c533eb97ba4c1c19b0521750a5624cb5d2e93249c8b7219d20029";
  String abi = "[{\"constant\":true,\"inputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"name\":\"balances\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"account\",\"type\":\"uint256\"}],\"name\":\"getCoin\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"stateMutability\":\"view\",\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"receiver\",\"type\":\"uint256\"},{\"name\":\"amount\",\"type\":\"uint256\"}],\"name\":\"setCoin\",\"outputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"function\"},{\"inputs\":[],\"payable\":false,\"stateMutability\":\"nonpayable\",\"type\":\"constructor\"}]";
  CreateSmartContract smartContract = GVMTestUtils.createSmartContract(
      Wallet.decodeFromBase58Check(OwnerAddress), contractName, abi, code, 0, 100);
  Transaction transaction = Transaction.newBuilder().setRawData(raw.newBuilder().addContract(
      Contract.newBuilder().setParameter(Any.pack(smartContract))
          .setType(ContractType.CreateSmartContract)).setFeeLimit(1000000000)).build();

  deployInit(transaction);
}
 
Example #21
Source File: DistkvAsyncSetProxy.java    From distkv with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CompletableFuture<DistkvProtocol.DistkvResponse> exists(String key, String entity) {
  SetProtocol.SetExistsRequest setExistsRequest = SetProtocol.SetExistsRequest.newBuilder()
      .setEntity(entity)
      .build();
  DistkvProtocol.DistkvRequest request = DistkvProtocol.DistkvRequest.newBuilder()
      .setKey(key)
      .setRequestType(RequestType.SET_EXISTS)
      .setRequest(Any.pack(setExistsRequest))
      .build();
  return call(request);
}
 
Example #22
Source File: DistkvAsyncSetProxy.java    From distkv with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CompletableFuture<DistkvProtocol.DistkvResponse> putItem(String key, String entity) {
  SetProtocol.SetPutItemRequest setPutItemRequest = SetProtocol.SetPutItemRequest.newBuilder()
      .setItemValue(entity)
      .build();

  DistkvProtocol.DistkvRequest request = DistkvProtocol.DistkvRequest.newBuilder()
      .setKey(key)
      .setRequestType(RequestType.SET_PUT_ITEM)
      .setRequest(Any.pack(setPutItemRequest))
      .build();
  return call(request);
}
 
Example #23
Source File: ExperimentRunServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public void logMetric(LogMetric request, StreamObserver<LogMetric.Response> responseObserver) {
  QPSCountResource.inc();
  try (RequestLatencyResource latencyResource =
      new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) {
    String errorMessage = null;
    if (request.getId().isEmpty()
        && (request.getMetric().getKey() == null || request.getMetric().getValue() == null)) {
      errorMessage =
          "ExperimentRun ID and New KeyValue for Metric not found in LogMetric request";
    } else if (request.getId().isEmpty()) {
      errorMessage = "ExperimentRun ID not found in LogMetric request";
    } else if (request.getMetric().getKey() == null || request.getMetric().getValue() == null) {
      errorMessage = "New KeyValue for Metric not found in LogMetric request";
    }

    if (errorMessage != null) {
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(errorMessage)
              .addDetails(Any.pack(LogMetric.Response.getDefaultInstance()))
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    String projectId = experimentRunDAO.getProjectIdByExperimentRunId(request.getId());
    // Validate if current user has access to the entity or not
    roleService.validateEntityUserWithUserInfo(
        ModelDBServiceResourceTypes.PROJECT, projectId, ModelDBServiceActions.UPDATE);

    experimentRunDAO.logMetrics(request.getId(), Collections.singletonList(request.getMetric()));
    responseObserver.onNext(LogMetric.Response.newBuilder().build());
    responseObserver.onCompleted();

  } catch (Exception e) {
    ModelDBUtils.observeError(responseObserver, e, LogMetric.Response.getDefaultInstance());
  }
}
 
Example #24
Source File: DistkvAsyncDictProxy.java    From distkv with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CompletableFuture<DistkvProtocol.DistkvResponse> putItem(
    String key, String itemKey, String itemValue) {
  DictProtocol.DictPutItemRequest dictPutItemRequest = DictProtocol.DictPutItemRequest
      .newBuilder()
      .setItemKey(itemKey)
      .setItemValue(itemValue)
      .build();
  DistkvProtocol.DistkvRequest request = DistkvProtocol.DistkvRequest.newBuilder()
      .setKey(key)
      .setRequestType(RequestType.DICT_PUT_ITEM)
      .setRequest(Any.pack(dictPutItemRequest))
      .build();
  return call(request);
}
 
Example #25
Source File: DistkvAsyncIntProxy.java    From distkv with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public CompletableFuture<DistkvResponse> put(
    String key, int value) {
  IntProtocol.IntPutRequest intPutRequest = IntProtocol.IntPutRequest
      .newBuilder()
      .setValue(value)
      .build();
  return put(key, RequestType.INT_PUT, Any.pack(intPutRequest));
}
 
Example #26
Source File: GenericKinesisSinkProvider.java    From flink-statefun with Apache License 2.0 5 votes vote down vote up
private static void validateConsumedType(EgressIdentifier<?> id) {
  Class<?> consumedType = id.consumedType();
  if (Any.class != consumedType) {
    throw new IllegalArgumentException(
        "Generic Kinesis egress is only able to consume messages types of "
            + Any.class.getName()
            + " but "
            + consumedType.getName()
            + " is provided.");
  }
}
 
Example #27
Source File: WitnessUpdateOperatorTest.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Any getContract(String address, String url) {
  return Any.pack(
      Contract.WitnessUpdateContract.newBuilder()
          .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(address)))
          .setUpdateUrl(ByteString.copyFrom(ByteArray.fromString(url)))
          .build());
}
 
Example #28
Source File: WitnessCreateOperatorTest.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Any getContract(String address, ByteString url) {
  return Any.pack(
      Contract.WitnessCreateContract.newBuilder()
          .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(address)))
          .setUrl(url)
          .build());
}
 
Example #29
Source File: TransferAssetOperatorTest.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Any getContract(long sendCoin, ByteString assetName) {
  return Any.pack(
      Contract.TransferAssetContract.newBuilder()
          .setAssetName(assetName)
          .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)))
          .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(TO_ADDRESS)))
          .setAmount(sendCoin)
          .build());
}
 
Example #30
Source File: ParticipateAssetIssueOperatorTest.java    From gsc-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Any getContractWithTo(long count, String toAddress) {
  String assertName = ASSET_NAME;
  if (dbManager.getDynamicPropertiesStore().getAllowSameTokenName() == 1) {
    long tokenIdNum = dbManager.getDynamicPropertiesStore().getTokenIdNum();
    assertName = String.valueOf(tokenIdNum);
  }
  return Any.pack(
      Contract.ParticipateAssetIssueContract.newBuilder()
          .setOwnerAddress(ByteString.copyFrom(ByteArray.fromHexString(OWNER_ADDRESS)))
          .setToAddress(ByteString.copyFrom(ByteArray.fromHexString(toAddress)))
          .setAssetName(ByteString.copyFrom(ByteArray.fromString(assertName)))
          .setAmount(count)
          .build());
}