Java Code Examples for com.google.rpc.Code

The following examples show how to use com.google.rpc.Code. 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
@Before
public void setUp() throws Exception {
  googleVideosImporter = new GoogleVideosImporter(null, null, null);

  photosLibraryClient = mock(PhotosLibraryClient.class);

  final NewMediaItemResult newMediaItemResult =
      NewMediaItemResult.newBuilder()
          .setStatus(Status.newBuilder().setCode(Code.OK_VALUE).build())
          .setMediaItem(MediaItem.newBuilder().setId(RESULT_ID).build())
          .build();
  BatchCreateMediaItemsResponse response =
      BatchCreateMediaItemsResponse.newBuilder()
          .addNewMediaItemResults(newMediaItemResult)
          .build();
  when(photosLibraryClient.batchCreateMediaItems(ArgumentMatchers.anyList()))
      .thenReturn(response);
}
 
Example 2
Source Project: spanner-jdbc   Source File: DDLStatement.java    License: MIT License 6 votes vote down vote up
private static List<String> getTokens(String sql, int maxTokens) throws SQLException {
  List<String> res = new ArrayList<>(maxTokens);
  int tokenNumber = 0;
  StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(sql));
  tokenizer.eolIsSignificant(false);
  tokenizer.wordChars('_', '_');
  tokenizer.wordChars('"', '"');
  tokenizer.wordChars('\'', '\'');
  tokenizer.quoteChar('`');
  try {
    while (tokenizer.nextToken() != StreamTokenizer.TT_EOF
        && (tokenizer.ttype == StreamTokenizer.TT_WORD || tokenizer.ttype == '`')
        && tokenNumber < maxTokens) {
      res.add(tokenizer.sval);
      tokenNumber++;
    }
  } catch (IOException e) {
    throw new CloudSpannerSQLException(
        "Could not parse DDL statement '" + sql + "'. Error: " + e.getMessage(),
        Code.INVALID_ARGUMENT, e);
  }
  return res;
}
 
Example 3
Source Project: bazel-buildfarm   Source File: BuildFarmServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void actionWithExcessiveTimeoutFailsValidation()
    throws IOException, InterruptedException, InvalidProtocolBufferException {
  Digest actionDigestWithExcessiveTimeout =
      createAction(Action.newBuilder().setTimeout(Duration.newBuilder().setSeconds(9000)));

  Operation failedOperation = executeAction(actionDigestWithExcessiveTimeout);
  assertThat(failedOperation.getDone()).isTrue();
  assertThat(failedOperation.getMetadata().unpack(ExecuteOperationMetadata.class).getStage())
      .isEqualTo(COMPLETED);
  ExecuteResponse executeResponse = failedOperation.getResponse().unpack(ExecuteResponse.class);
  com.google.rpc.Status status = executeResponse.getStatus();
  assertThat(status.getCode()).isEqualTo(Code.FAILED_PRECONDITION.getNumber());
  assertThat(status.getDetailsCount()).isEqualTo(1);
  PreconditionFailure preconditionFailure =
      status.getDetailsList().get(0).unpack(PreconditionFailure.class);
  assertThat(preconditionFailure.getViolationsCount()).isEqualTo(1);
  Violation violation = preconditionFailure.getViolationsList().get(0);
  assertThat(violation.getType()).isEqualTo(VIOLATION_TYPE_INVALID);
}
 
Example 4
Source Project: modeldb   Source File: ModelDBUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static String getMd5String(String inputString) {
  try {
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] messageDigest = md.digest(inputString.getBytes());
    BigInteger no = new BigInteger(1, messageDigest);
    String hashtext = no.toString(16);
    StringBuilder outputStringBuilder = new StringBuilder(hashtext);
    while (outputStringBuilder.toString().length() < 32) {
      outputStringBuilder.append("0").append(outputStringBuilder.toString());
    }
    return outputStringBuilder.toString();
  }

  // For specifying wrong message digest algorithms
  catch (NoSuchAlgorithmException e) {
    Status status =
        Status.newBuilder().setCode(Code.INTERNAL_VALUE).setMessage(e.getMessage()).build();
    throw StatusProto.toStatusRuntimeException(status);
  }
}
 
Example 5
Source Project: beam   Source File: DatastoreV1Test.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testTranslateGqlQueryWithLimit() throws Exception {
  String gql = "SELECT * from DummyKind LIMIT 10";
  String gqlWithZeroLimit = gql + " LIMIT 0";
  GqlQuery gqlQuery = GqlQuery.newBuilder().setQueryString(gql).setAllowLiterals(true).build();
  GqlQuery gqlQueryWithZeroLimit =
      GqlQuery.newBuilder().setQueryString(gqlWithZeroLimit).setAllowLiterals(true).build();
  RunQueryRequest gqlRequest = makeRequest(gqlQuery, V_1_OPTIONS.getNamespace());
  RunQueryRequest gqlRequestWithZeroLimit =
      makeRequest(gqlQueryWithZeroLimit, V_1_OPTIONS.getNamespace());
  when(mockDatastore.runQuery(gqlRequestWithZeroLimit))
      .thenThrow(
          new DatastoreException(
              "runQuery",
              Code.INVALID_ARGUMENT,
              "invalid query",
              // dummy
              new RuntimeException()));
  when(mockDatastore.runQuery(gqlRequest))
      .thenReturn(RunQueryResponse.newBuilder().setQuery(QUERY).build());
  assertEquals(
      translateGqlQueryWithLimitCheck(gql, mockDatastore, V_1_OPTIONS.getNamespace()), QUERY);
  verify(mockDatastore, times(1)).runQuery(gqlRequest);
  verify(mockDatastore, times(1)).runQuery(gqlRequestWithZeroLimit);
}
 
Example 6
Source Project: modeldb   Source File: ExperimentRunDAORdbImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public List<Artifact> getExperimentRunDatasets(String experimentRunId)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    ExperimentRunEntity experimentRunObj =
        session.get(ExperimentRunEntity.class, experimentRunId);
    if (experimentRunObj == null) {
      LOGGER.info(ModelDBMessages.EXP_RUN_NOT_FOUND_ERROR_MSG);
      Status status =
          Status.newBuilder()
              .setCode(Code.NOT_FOUND_VALUE)
              .setMessage(ModelDBMessages.EXP_RUN_NOT_FOUND_ERROR_MSG)
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }
    LOGGER.debug("Got ExperimentRun Datasets");
    return experimentRunObj.getProtoObject().getDatasetsList();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getExperimentRunDatasets(experimentRunId);
    } else {
      throw ex;
    }
  }
}
 
Example 7
Source Project: modeldb   Source File: AuthServiceChannel.java    License: Apache License 2.0 6 votes vote down vote up
public AuthServiceChannel() {
  App app = App.getInstance();
  String host = app.getAuthServerHost();
  Integer port = app.getAuthServerPort();
  LOGGER.trace(ModelDBMessages.HOST_PORT_INFO_STR, host, port);
  if (host != null && port != null) { // AuthService not available.
    authServiceChannel =
        ManagedChannelBuilder.forTarget(host + ModelDBConstants.STRING_COLON + port)
            .usePlaintext()
            .build();

    this.serviceUserEmail = app.getServiceUserEmail();
    this.serviceUserDevKey = app.getServiceUserDevKey();
  } else {
    Status status =
        Status.newBuilder()
            .setCode(Code.UNAVAILABLE_VALUE)
            .setMessage("Host OR Port not found for contacting authentication service")
            .build();
    throw StatusProto.toStatusRuntimeException(status);
  }
}
 
Example 8
Source Project: spanner-jdbc   Source File: CloudSpannerXAConnection.java    License: MIT License 6 votes vote down vote up
@Override
public void commit(Xid xid, boolean onePhase) throws XAException {
  if (logger.logDebug()) {
    debug("committing xid = " + xid + (onePhase ? " (one phase) " : " (two phase)"));
  }

  if (xid == null) {
    throw new CloudSpannerXAException(CloudSpannerXAException.XID_NOT_NULL, Code.INVALID_ARGUMENT,
        XAException.XAER_INVAL);
  }

  if (onePhase) {
    commitOnePhase(xid);
  } else {
    commitPrepared(xid);
  }
}
 
Example 9
Source Project: modeldb   Source File: ExperimentRunDAORdbImpl.java    License: Apache License 2.0 6 votes vote down vote up
private Optional<ArtifactEntity> getExperimentRunArtifact(
    Session session, String experimentRunId, String key) {
  ExperimentRunEntity experimentRunObj = session.get(ExperimentRunEntity.class, experimentRunId);
  if (experimentRunObj == null) {
    LOGGER.info(ModelDBMessages.EXP_RUN_NOT_FOUND_ERROR_MSG);
    Status status =
        Status.newBuilder()
            .setCode(Code.NOT_FOUND_VALUE)
            .setMessage(ModelDBMessages.EXP_RUN_NOT_FOUND_ERROR_MSG)
            .build();
    throw StatusProto.toStatusRuntimeException(status);
  }

  Map<String, List<ArtifactEntity>> artifactEntityMap = experimentRunObj.getArtifactEntityMap();

  List<ArtifactEntity> result =
      (artifactEntityMap != null && artifactEntityMap.containsKey(ModelDBConstants.ARTIFACTS))
          ? artifactEntityMap.get(ModelDBConstants.ARTIFACTS)
          : Collections.emptyList();
  return result.stream()
      .filter(artifactEntity -> artifactEntity.getKey().equals(key))
      .findFirst();
}
 
Example 10
Source Project: modeldb   Source File: PublicRoleServiceUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Checks permissions of the user wrt the Entity
 *
 * @param modelDBServiceResourceTypes : modelDBServiceResourceTypes
 * @param resourceId --> value of key like project.id, dataset.id etc.
 * @param modelDBServiceActions --> ModelDBServiceActions.UPDATE, ModelDBServiceActions.DELETE,
 */
@Override
public void validateEntityUserWithUserInfo(
    ModelDBServiceResourceTypes modelDBServiceResourceTypes,
    String resourceId,
    ModelDBServiceActions modelDBServiceActions)
    throws InvalidProtocolBufferException {
  if (resourceId != null && !resourceId.isEmpty()) {
    if (modelDBServiceResourceTypes.equals(ModelDBServiceResourceTypes.PROJECT)) {
      if (!projectDAO.projectExistsInDB(resourceId)) {
        String errorMessage = ModelDBMessages.PROJECT_NOT_FOUND_FOR_ID;
        Status status =
            Status.newBuilder().setCode(Code.NOT_FOUND_VALUE).setMessage(errorMessage).build();
        throw StatusProto.toStatusRuntimeException(status);
      }
    } else if (modelDBServiceResourceTypes.equals(ModelDBServiceResourceTypes.DATASET)) {
      datasetDAO.getDatasetById(resourceId);
    }
  }
}
 
Example 11
Source Project: modeldb   Source File: AuthServiceUtils.java    License: Apache License 2.0 6 votes vote down vote up
private UserInfo getCurrentLoginUserInfo(boolean retry) {
  try (AuthServiceChannel authServiceChannel = new AuthServiceChannel()) {
    LOGGER.info(ModelDBMessages.AUTH_SERVICE_REQ_SENT_MSG);
    UserInfo userInfo =
        authServiceChannel.getUacServiceBlockingStub().getCurrentUser(Empty.newBuilder().build());
    LOGGER.info(ModelDBMessages.AUTH_SERVICE_RES_RECEIVED_MSG);

    if (userInfo == null || userInfo.getVertaInfo() == null) {
      LOGGER.info("user not found {}", userInfo);
      Status status =
          Status.newBuilder()
              .setCode(Code.NOT_FOUND_VALUE)
              .setMessage("Current user could not be resolved.")
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    } else {
      return userInfo;
    }
  } catch (StatusRuntimeException ex) {
    return (UserInfo)
        ModelDBUtils.retryOrThrowException(
            ex, retry, (ModelDBUtils.RetryCallInterface<UserInfo>) this::getCurrentLoginUserInfo);
  }
}
 
Example 12
Source Project: modeldb   Source File: ExperimentRunServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void getVersionedInputs(
    GetVersionedInput request, StreamObserver<GetVersionedInput.Response> responseObserver) {
  QPSCountResource.inc();
  try (RequestLatencyResource latencyResource =
      new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) {
    String errorMessage = null;
    if (request.getId().isEmpty()) {
      errorMessage = "ExperimentRun ID not found in GetVersionedInput request";
    }

    if (errorMessage != null) {
      throw new ModelDBException(errorMessage, io.grpc.Status.Code.INVALID_ARGUMENT);
    }

    GetVersionedInput.Response response = experimentRunDAO.getVersionedInputs(request);
    responseObserver.onNext(response);
    responseObserver.onCompleted();
  } catch (Exception e) {
    ModelDBUtils.observeError(
        responseObserver, e, GetVersionedInput.Response.getDefaultInstance());
  }
}
 
Example 13
Source Project: bazel-buildfarm   Source File: OperationQueueService.java    License: Apache License 2.0 6 votes vote down vote up
private InterruptingPredicate<QueueEntry> createOnMatch(
    Instance instance, StreamObserver<QueueEntry> responseObserver) {
  return (queueEntry) -> {
    try {
      responseObserver.onNext(queueEntry);
      responseObserver.onCompleted();
      return true;
    } catch (StatusRuntimeException e) {
      Status status = Status.fromThrowable(e);
      if (status.getCode() != Status.Code.CANCELLED) {
        responseObserver.onError(e);
      }
    }
    instance.putOperation(instance.getOperation(queueEntry.getExecuteEntry().getOperationName()));
    return false;
  };
}
 
Example 14
Source Project: modeldb   Source File: AuthServiceUtils.java    License: Apache License 2.0 6 votes vote down vote up
private UserInfo getUnsignedUser(boolean retry) {
  try (AuthServiceChannel authServiceChannel = new AuthServiceChannel()) {
    LOGGER.info(ModelDBMessages.AUTH_SERVICE_REQ_SENT_MSG);
    GetUser getUserRequest =
        GetUser.newBuilder().setUsername(ModelDBConstants.UNSIGNED_USER).build();
    // Get the user info by vertaId form the AuthService
    UserInfo userInfo = authServiceChannel.getUacServiceBlockingStub().getUser(getUserRequest);
    LOGGER.info(ModelDBMessages.AUTH_SERVICE_RES_RECEIVED_MSG);

    if (userInfo == null || userInfo.getVertaInfo() == null) {
      LOGGER.warn("unsigned user not found {}", userInfo);
      Status status =
          Status.newBuilder()
              .setCode(Code.NOT_FOUND_VALUE)
              .setMessage("Unsigned user not found with the provided metadata")
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    } else {
      return userInfo;
    }
  } catch (StatusRuntimeException ex) {
    return (UserInfo)
        ModelDBUtils.retryOrThrowException(
            ex, retry, (ModelDBUtils.RetryCallInterface<UserInfo>) this::getUnsignedUser);
  }
}
 
Example 15
Source Project: modeldb   Source File: ProjectDAORdbImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Project getProjectByID(String id) throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Query query = session.createQuery(GET_PROJECT_BY_ID_HQL);
    query.setParameter("id", id);
    ProjectEntity projectEntity = (ProjectEntity) query.uniqueResult();
    if (projectEntity == null) {
      String errorMessage = ModelDBMessages.PROJECT_NOT_FOUND_FOR_ID;
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder().setCode(Code.NOT_FOUND_VALUE).setMessage(errorMessage).build();
      throw StatusProto.toStatusRuntimeException(status);
    }
    LOGGER.debug(ModelDBMessages.GETTING_PROJECT_BY_ID_MSG_STR);
    return projectEntity.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getProjectByID(id);
    } else {
      throw ex;
    }
  }
}
 
Example 16
Source Project: spanner-jdbc   Source File: CloudSpannerPreparedStatement.java    License: MIT License 6 votes vote down vote up
private void visitDeleteWhereClause(Expression where, DeleteKeyBuilder keyBuilder,
    boolean generateParameterMetaData) throws SQLException {
  if (where != null) {
    DMLWhereClauseVisitor whereClauseVisitor = new DMLWhereClauseVisitor(getParameterStore()) {

      @Override
      protected void visitExpression(Column col, Expression expression) {
        String columnName = unquoteIdentifier(col.getFullyQualifiedName());
        keyBuilder.set(columnName);
        expression.accept(
            new KeyBuilderExpressionVisitorAdapter(getParameterStore(), columnName, keyBuilder));
      }

    };
    where.accept(whereClauseVisitor);
    if (!generateParameterMetaData && !whereClauseVisitor.isValid()) {
      throw new CloudSpannerSQLException(INVALID_WHERE_CLAUSE_DELETE_MESSAGE,
          Code.INVALID_ARGUMENT);
    }
  }
}
 
Example 17
Source Project: beam   Source File: DatastoreV1Test.java    License: Apache License 2.0 6 votes vote down vote up
/** Tests that {@link ReadFn} retries after an error. */
@Test
public void testReadFnRetriesErrors() throws Exception {
  // An empty query to read entities.
  Query query = Query.newBuilder().setLimit(Int32Value.newBuilder().setValue(1)).build();

  // Use mockResponseForQuery to generate results.
  when(mockDatastore.runQuery(any(RunQueryRequest.class)))
      .thenThrow(new DatastoreException("RunQuery", Code.DEADLINE_EXCEEDED, "", null))
      .thenAnswer(
          invocationOnMock -> {
            Query q = ((RunQueryRequest) invocationOnMock.getArguments()[0]).getQuery();
            return mockResponseForQuery(q);
          });

  ReadFn readFn = new ReadFn(V_1_OPTIONS, mockDatastoreFactory);
  DoFnTester<Query, Entity> doFnTester = DoFnTester.of(readFn);
  doFnTester.setCloningBehavior(CloningBehavior.DO_NOT_CLONE);
  doFnTester.processBundle(query);
}
 
Example 18
Source Project: modeldb   Source File: ExperimentRunDAORdbImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ExperimentRun getExperimentRun(String experimentRunId)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    ExperimentRunEntity experimentRunEntity =
        session.get(ExperimentRunEntity.class, experimentRunId);
    if (experimentRunEntity == null) {
      LOGGER.info(ModelDBMessages.EXP_RUN_NOT_FOUND_ERROR_MSG);
      Status status =
          Status.newBuilder()
              .setCode(Code.NOT_FOUND_VALUE)
              .setMessage(ModelDBMessages.EXP_RUN_NOT_FOUND_ERROR_MSG)
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }
    LOGGER.debug("Got ExperimentRun successfully");
    return experimentRunEntity.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return getExperimentRun(experimentRunId);
    } else {
      throw ex;
    }
  }
}
 
Example 19
Source Project: modeldb   Source File: ExperimentServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void deleteExperiment(
    DeleteExperiment request, StreamObserver<DeleteExperiment.Response> responseObserver) {
  QPSCountResource.inc();
  try (RequestLatencyResource latencyResource =
      new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) {

    if (request.getId().isEmpty()) {
      String errorMessage = "Experiment ID not found in DeleteExperiment request";
      LOGGER.warn(errorMessage);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(errorMessage)
              .addDetails(Any.pack(DeleteExperiment.Response.getDefaultInstance()))
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    boolean deleteStatus =
        experimentDAO.deleteExperiments(Collections.singletonList(request.getId()));
    responseObserver.onNext(
        DeleteExperiment.Response.newBuilder().setStatus(deleteStatus).build());
    responseObserver.onCompleted();

  } catch (Exception e) {
    ModelDBUtils.observeError(
        responseObserver, e, DeleteExperiment.Response.getDefaultInstance());
  }
}
 
Example 20
Source Project: modeldb   Source File: ProjectServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get ProjectId from DeleteProject request and delete it from database.
 *
 * @param DeleteProject request, DeleteProject.Response response
 * @return void
 */
@Override
public void deleteProject(
    DeleteProject request, StreamObserver<DeleteProject.Response> responseObserver) {
  QPSCountResource.inc();

  try (RequestLatencyResource latencyResource =
      new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) {
    // Request Parameter Validation
    if (request.getId().isEmpty()) {
      String errorMessage = "Project ID not found in DeleteProject request";
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(errorMessage)
              .addDetails(Any.pack(DeleteProject.Response.getDefaultInstance()))
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    boolean deletedStatus = projectDAO.deleteProjects(Collections.singletonList(request.getId()));
    responseObserver.onNext(DeleteProject.Response.newBuilder().setStatus(deletedStatus).build());
    responseObserver.onCompleted();

  } catch (Exception e) {
    ModelDBUtils.observeError(responseObserver, e, DeleteProject.Response.getDefaultInstance());
  }
}
 
Example 21
Source Project: modeldb   Source File: ModelDBHibernateUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static SessionFactory getSessionFactory() {
  try {
    return createOrGetSessionFactory();
  } catch (Exception e) {
    Status status =
        Status.newBuilder().setCode(Code.INTERNAL_VALUE).setMessage(e.getMessage()).build();
    throw StatusProto.toStatusRuntimeException(status);
  }
}
 
Example 22
Source Project: spanner-jdbc   Source File: XATransaction.java    License: MIT License 5 votes vote down vote up
@VisibleForTesting
static String serializeMutation(Mutation mutation) throws SQLException {
  try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
      ObjectOutputStream stream = new ObjectOutputStream(bos)) {
    stream.writeObject(mutation);
    return Base64.getEncoder().encodeToString(bos.toByteArray());
  } catch (IOException e) {
    throw new CloudSpannerSQLException("Could not serialize mutation", Code.INTERNAL, e);
  }
}
 
Example 23
Source Project: spanner-jdbc   Source File: XATransaction.java    License: MIT License 5 votes vote down vote up
@VisibleForTesting
static Mutation deserializeMutation(String mutation) throws SQLException {
  try (ByteArrayInputStream bis = new ByteArrayInputStream(Base64.getDecoder().decode(mutation));
      ObjectInputStream input = new ObjectInputStream(bis)) {
    return (Mutation) input.readObject();
  } catch (IOException | ClassNotFoundException e) {
    throw new CloudSpannerSQLException("Could not deserialize mutation", Code.INTERNAL, e);
  }
}
 
Example 24
Source Project: modeldb   Source File: AdvancedServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void getHydratedProjectById(
    GetHydratedProjectById request,
    StreamObserver<GetHydratedProjectById.Response> responseObserver) {
  QPSCountResource.inc();
  try (RequestLatencyResource latencyResource =
      new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) {
    if (request.getId().isEmpty()) {
      String errorMessage = "Project ID not found in GetHydratedProjectById request";
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(errorMessage)
              .addDetails(Any.pack(GetHydratedProjectById.Response.getDefaultInstance()))
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }
    // Validate if current user has access to the entity or not
    roleService.validateEntityUserWithUserInfo(
        ModelDBServiceResourceTypes.PROJECT, request.getId(), ModelDBServiceActions.READ);

    Project project = projectDAO.getProjectByID(request.getId());
    responseObserver.onNext(
        GetHydratedProjectById.Response.newBuilder()
            .setHydratedProject(getHydratedProjects(Collections.singletonList(project)).get(0))
            .build());
    responseObserver.onCompleted();

  } catch (Exception e) {
    ModelDBUtils.observeError(
        responseObserver, e, GetHydratedProjectById.Response.getDefaultInstance());
  }
}
 
Example 25
Source Project: spanner-jdbc   Source File: CloudSpannerTransaction.java    License: MIT License 5 votes vote down vote up
public void rollbackSavepoint(Savepoint savepoint) throws SQLException {
  Preconditions.checkNotNull(savepoint);
  checkTransaction();
  if (transactionThread == null)
    throw new CloudSpannerSQLException(SAVEPOINTS_NOT_IN_READ_ONLY, Code.FAILED_PRECONDITION);
  transactionThread.rollbackSavepoint(savepoint);
}
 
Example 26
Source Project: spanner-jdbc   Source File: CloudSpannerTransaction.java    License: MIT License 5 votes vote down vote up
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
  Preconditions.checkNotNull(savepoint);
  checkTransaction();
  if (transactionThread == null)
    throw new CloudSpannerSQLException(SAVEPOINTS_NOT_IN_READ_ONLY, Code.FAILED_PRECONDITION);
  transactionThread.releaseSavepoint(savepoint);
}
 
Example 27
Source Project: spanner-jdbc   Source File: CloudSpannerTransaction.java    License: MIT License 5 votes vote down vote up
private void preparedTransactionAction(String xid, TransactionAction action) throws SQLException {
  try {
    if (connection.isReadOnly()) {
      throw new CloudSpannerSQLException(
          "Connection is in read-only mode and cannot be used for prepared transactions",
          Code.FAILED_PRECONDITION);
    } else {
      action.apply(xid);
    }
  } finally {
    transactionThread = null;
    readOnlyTransaction = null;
    batchReadOnlyTransaction = null;
  }
}
 
Example 28
Source Project: bazel-buildfarm   Source File: Cat.java    License: Apache License 2.0 5 votes vote down vote up
private static void printStatus(com.google.rpc.Status status)
    throws InvalidProtocolBufferException {
  System.out.println("  Code: " + Code.forNumber(status.getCode()));
  if (!status.getMessage().isEmpty()) {
    System.out.println("  Message: " + status.getMessage());
  }
  if (status.getDetailsCount() > 0) {
    System.out.println("  Details:");
    for (Any detail : status.getDetailsList()) {
      if (detail.is(RetryInfo.class)) {
        RetryInfo retryInfo = detail.unpack(RetryInfo.class);
        System.out.println(
            "    RetryDelay: "
                + (retryInfo.getRetryDelay().getSeconds()
                    + retryInfo.getRetryDelay().getNanos() / 1000000000.0f));
      } else if (detail.is(PreconditionFailure.class)) {
        PreconditionFailure preconditionFailure = detail.unpack(PreconditionFailure.class);
        System.out.println("    PreconditionFailure:");
        for (PreconditionFailure.Violation violation : preconditionFailure.getViolationsList()) {
          System.out.println("      Violation: " + violation.getType());
          System.out.println("        Subject: " + violation.getSubject());
          System.out.println("        Description: " + violation.getDescription());
        }
      } else {
        System.out.println("    Unknown Detail: " + detail.getTypeUrl());
      }
    }
  }
}
 
Example 29
Source Project: spanner-jdbc   Source File: TransactionThread.java    License: MIT License 5 votes vote down vote up
void releaseSavepoint(Savepoint savepoint) throws CloudSpannerSQLException {
  Preconditions.checkNotNull(savepoint);
  Integer index = savepoints.get(savepoint);
  if (index == null) {
    throw new CloudSpannerSQLException("Unknown savepoint: " + savepoint.toString(),
        Code.INVALID_ARGUMENT);
  }
  removeSavepointsAfter(index.intValue());
}
 
Example 30
Source Project: modeldb   Source File: VersioningModeldbEntityMapping.java    License: Apache License 2.0 5 votes vote down vote up
public VersioningModeldbEntityMapping(
    Long repositoryId,
    String commit,
    String versioningKey,
    String versioningLocation,
    Integer versioningBlobType,
    String blobHash,
    Object entity) {
  this.repository_id = repositoryId;
  this.commit = commit;
  this.versioning_key = versioningKey;
  this.versioning_location = versioningLocation;
  this.entity_type = entity.getClass().getSimpleName();
  this.versioning_blob_type = versioningBlobType;

  if (entity instanceof ExperimentRunEntity) {
    this.experimentRunEntity = (ExperimentRunEntity) entity;
  } else {
    LOGGER.warn("ExperimentRunEntity Expected : found {}", entity.getClass());
    Status status =
        Status.newBuilder()
            .setCode(Code.INTERNAL_VALUE)
            .setMessage("Invalid ModelDB entity found")
            .build();
    throw StatusProto.toStatusRuntimeException(status);
  }

  if (blobHash != null) {
    this.blob_hash = blobHash;
  }
}