com.google.rpc.Code Java Examples

The following examples show how to use com.google.rpc.Code. 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: DDLStatement.java    From spanner-jdbc with 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 #2
Source File: OperationQueueService.java    From bazel-buildfarm with 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 #3
Source File: GoogleVideosImporterTest.java    From data-transfer-project with Apache License 2.0 6 votes vote down vote up
@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 #4
Source File: CloudSpannerPreparedStatement.java    From spanner-jdbc with 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 #5
Source File: AuthServiceUtils.java    From modeldb with 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 #6
Source File: ProjectDAORdbImpl.java    From modeldb with 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 #7
Source File: ExperimentRunServiceImpl.java    From modeldb with 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 #8
Source File: AuthServiceUtils.java    From modeldb with 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 #9
Source File: BuildFarmServerTest.java    From bazel-buildfarm with 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 #10
Source File: PublicRoleServiceUtils.java    From modeldb with 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 File: ModelDBUtils.java    From modeldb with 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 #12
Source File: ExperimentRunDAORdbImpl.java    From modeldb with 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 #13
Source File: DatastoreV1Test.java    From beam with 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 #14
Source File: DatastoreV1Test.java    From beam with 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 #15
Source File: ExperimentRunDAORdbImpl.java    From modeldb with 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 #16
Source File: ExperimentRunDAORdbImpl.java    From modeldb with 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 #17
Source File: AuthServiceChannel.java    From modeldb with 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 #18
Source File: CloudSpannerXAConnection.java    From spanner-jdbc with 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 #19
Source File: ExperimentRunDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
public ArtifactEntity getArtifactEntity(Session session, String experimentRunId, String key)
    throws ModelDBException {
  Optional<ArtifactEntity> artifactEntityOptional =
      getExperimentRunArtifact(session, experimentRunId, key);
  return artifactEntityOptional.orElseThrow(
      () -> new ModelDBException("Can't find specified artifact", io.grpc.Status.Code.NOT_FOUND));
}
 
Example #20
Source File: CommentDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public Comment updateComment(String entityType, String entityId, Comment updatedComment) {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    UserCommentEntity userCommentEntity =
        session.load(UserCommentEntity.class, updatedComment.getId());
    if (userCommentEntity == null) {
      Status status =
          Status.newBuilder()
              .setCode(Code.NOT_FOUND_VALUE)
              .setMessage("Comment does not exist in database")
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }
    userCommentEntity.setUser_id(updatedComment.getUserId());
    userCommentEntity.setOwner(updatedComment.getVertaId());
    userCommentEntity.setMessage(updatedComment.getMessage());
    userCommentEntity.setDate_time(updatedComment.getDateTime());
    Transaction transaction = session.beginTransaction();
    session.update(userCommentEntity);
    transaction.commit();
    LOGGER.debug("Comment updated successfully");
    return userCommentEntity.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return updateComment(entityType, entityId, updatedComment);
    } else {
      throw ex;
    }
  }
}
 
Example #21
Source File: ModelDBHibernateUtil.java    From modeldb with Apache License 2.0 5 votes vote down vote up
public static void checkIfEntityAlreadyExists(
    Session session,
    String shortName,
    String command,
    String entityName,
    String fieldName,
    String name,
    String workspaceColumnName,
    String workspaceId,
    WorkspaceType workspaceType,
    Logger logger) {
  Query query =
      getWorkspaceEntityQuery(
          session,
          shortName,
          command,
          fieldName,
          name,
          workspaceColumnName,
          workspaceId,
          workspaceType,
          true,
          null);
  Long count = (Long) query.uniqueResult();

  if (count > 0) {
    // Throw error if it is an insert request and project with same name already exists
    logger.info(entityName + " with name {} already exists", name);
    Status status =
        Status.newBuilder()
            .setCode(Code.ALREADY_EXISTS_VALUE)
            .setMessage(entityName + " already exists in database")
            .build();
    throw StatusProto.toStatusRuntimeException(status);
  }
}
 
Example #22
Source File: ProjectServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
/**
 * Update project name in Project Entity. Create project object with updated data from
 * UpdateProjectName request and update in database.
 *
 * @param UpdateProjectName request, UpdateProjectName.Response response
 * @return void
 */
@Override
public void updateProjectName(
    UpdateProjectName request, StreamObserver<UpdateProjectName.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 UpdateProjectName request";
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(errorMessage)
              .addDetails(Any.pack(UpdateProjectName.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.UPDATE);

    Project updatedProject =
        projectDAO.updateProjectName(
            request.getId(), ModelDBUtils.checkEntityNameLength(request.getName()));
    responseObserver.onNext(
        UpdateProjectName.Response.newBuilder().setProject(updatedProject).build());
    responseObserver.onCompleted();

  } catch (Exception e) {
    ModelDBUtils.observeError(
        responseObserver, e, UpdateProjectName.Response.getDefaultInstance());
  }
}
 
Example #23
Source File: ProjectDAORdbImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public Project setProjectShortName(String projectId, String projectShortName, UserInfo userInfo)
    throws InvalidProtocolBufferException {
  try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) {
    Query query = session.createQuery(GET_PROJECT_BY_SHORT_NAME_AND_OWNER_HQL);
    query.setParameter("projectShortName", projectShortName);
    query.setParameter("vertaId", authService.getVertaIdFromUserInfo(userInfo));
    ProjectEntity projectEntity = (ProjectEntity) query.uniqueResult();
    if (projectEntity != null) {
      Status status =
          Status.newBuilder()
              .setCode(Code.ALREADY_EXISTS_VALUE)
              .setMessage("Project already exist with given short name")
              .build();
      throw StatusProto.toStatusRuntimeException(status);
    }

    query = session.createQuery(GET_PROJECT_BY_ID_HQL);
    query.setParameter("id", projectId);
    projectEntity = (ProjectEntity) query.uniqueResult();
    projectEntity.setShort_name(projectShortName);
    projectEntity.setDate_updated(Calendar.getInstance().getTimeInMillis());
    Transaction transaction = session.beginTransaction();
    session.update(projectEntity);
    transaction.commit();
    LOGGER.debug(ModelDBMessages.GETTING_PROJECT_BY_ID_MSG_STR);
    return projectEntity.getProtoObject();
  } catch (Exception ex) {
    if (ModelDBUtils.needToRetry(ex)) {
      return setProjectShortName(projectId, projectShortName, userInfo);
    } else {
      throw ex;
    }
  }
}
 
Example #24
Source File: CloudSpannerStatement.java    From spanner-jdbc with MIT License 5 votes vote down vote up
@Override
public int executeUpdate(String[] sqlTokens) throws SQLException {
  if (sqlTokens.length != 1)
    throw new CloudSpannerSQLException(
        "Invalid argument(s) for WAIT_FOR_DDL_OPERATIONS. Expected \"WAIT_FOR_DDL_OPERATIONS\"",
        Code.INVALID_ARGUMENT);
  getConnection().waitForDdlOperations();
  return 0;
}
 
Example #25
Source File: StubInstance.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
@Override
public boolean pollOperation(String operationName, ExecutionStage.Value stage) {
  throwIfStopped();
  return deadlined(operationQueueBlockingStub)
          .poll(
              PollOperationRequest.newBuilder()
                  .setOperationName(operationName)
                  .setStage(stage)
                  .build())
          .getCode()
      == Code.OK.getNumber();
}
 
Example #26
Source File: AbstractCloudSpannerStatement.java    From spanner-jdbc with MIT License 5 votes vote down vote up
/**
 * Transform the given UPDATE-statement into an "INSERT INTO TAB1 (...) SELECT ... FROM TAB1 WHERE
 * ... ON DUPLICATE KEY UPDATE"
 * 
 * @param update The UPDATE-statement
 * @return An SQL-statement equal to the UPDATE-statement but in INSERT form
 * @throws SQLException if a database exception occurs while getting the table meta data or if the
 *         statement tries to update the primary key value
 */
protected String createInsertSelectOnDuplicateKeyUpdateStatement(Update update)
    throws SQLException {
  String tableName = unquoteIdentifier(update.getTables().get(0).getName());
  TableKeyMetaData table = getConnection().getTable(tableName);
  List<String> keyColumns = table.getKeyColumns();
  List<String> updateColumns = update.getColumns().stream().map(Column::getColumnName)
      .map(String::toUpperCase).collect(Collectors.toList());
  List<String> quotedKeyColumns =
      keyColumns.stream().map(this::quoteIdentifier).collect(Collectors.toList());
  List<String> quotedAndQualifiedKeyColumns =
      keyColumns.stream().map(x -> quoteIdentifier(tableName) + "." + quoteIdentifier(x))
          .collect(Collectors.toList());

  List<String> quotedUpdateColumns =
      updateColumns.stream().map(this::quoteIdentifier).collect(Collectors.toList());
  List<String> expressions =
      update.getExpressions().stream().map(Object::toString).collect(Collectors.toList());
  if (updateColumns.stream().anyMatch(keyColumns::contains)) {
    String invalidCols =
        updateColumns.stream().filter(keyColumns::contains).collect(Collectors.joining());
    throw new CloudSpannerSQLException(
        "UPDATE of a primary key value is not allowed, cannot UPDATE the column(s) "
            + invalidCols,
        Code.INVALID_ARGUMENT);
  }

  StringBuilder res = new StringBuilder();
  res.append("INSERT INTO ").append(quoteIdentifier(tableName)).append("\n(");
  res.append(String.join(", ", quotedKeyColumns)).append(", ");
  res.append(String.join(", ", quotedUpdateColumns)).append(")");
  res.append("\nSELECT ").append(String.join(", ", quotedAndQualifiedKeyColumns)).append(", ");
  res.append(String.join(", ", expressions));
  res.append("\nFROM ").append(quoteIdentifier(tableName));
  if (update.getWhere() != null)
    res.append("\n").append("WHERE ").append(update.getWhere().toString());
  res.append("\nON DUPLICATE KEY UPDATE");

  return res.toString();
}
 
Example #27
Source File: RemoteRpcTest.java    From google-cloud-datastore with Apache License 2.0 5 votes vote down vote up
@Test
public void testException() {
  Status statusProto =
      Status.newBuilder()
          .setCode(Code.UNAUTHENTICATED_VALUE)
          .setMessage("The request does not have valid authentication credentials.")
          .build();
  DatastoreException exception = RemoteRpc.makeException("url", METHOD_NAME,
      new ByteArrayInputStream(statusProto.toByteArray()), "application/x-protobuf",
      Charsets.UTF_8, new RuntimeException(), 401);
  assertEquals(Code.UNAUTHENTICATED, exception.getCode());
  assertEquals("The request does not have valid authentication credentials.",
      exception.getMessage());
  assertEquals(METHOD_NAME, exception.getMethodName());
}
 
Example #28
Source File: ProjectServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public void getProjectById(
    GetProjectById request, StreamObserver<GetProjectById.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 GetProjectById request";
      LOGGER.info(errorMessage);
      Status status =
          Status.newBuilder()
              .setCode(Code.INVALID_ARGUMENT_VALUE)
              .setMessage(errorMessage)
              .addDetails(Any.pack(GetProjectById.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(GetProjectById.Response.newBuilder().setProject(project).build());
    responseObserver.onCompleted();

  } catch (Exception e) {
    ModelDBUtils.observeError(responseObserver, e, GetProjectById.Response.getDefaultInstance());
  }
}
 
Example #29
Source File: AuthServiceUtils.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public String getVertaIdFromUserInfo(UserInfo userInfo) {
  if (userInfo != null
      && userInfo.getVertaInfo() != null
      && !userInfo.getVertaInfo().getUserId().isEmpty()) {
    return userInfo.getVertaInfo().getUserId();
  }
  Status status =
      Status.newBuilder()
          .setCode(Code.NOT_FOUND_VALUE)
          .setMessage("VertaId not found in userInfo")
          .build();
  throw StatusProto.toStatusRuntimeException(status);
}
 
Example #30
Source File: ExperimentRunServiceImpl.java    From modeldb with Apache License 2.0 5 votes vote down vote up
@Override
public void commitMultipartArtifact(
    CommitMultipartArtifact request,
    StreamObserver<CommitMultipartArtifact.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 CommitMultipartArtifact request";
    } else if (request.getKey().isEmpty()) {
      errorMessage = "Artifact key not found in CommitMultipartArtifact request";
    }

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

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

    CommitMultipartArtifact.Response response =
        experimentRunDAO.commitMultipartArtifact(
            request,
            (s3Key, uploadId, partETags) ->
                artifactStoreDAO.commitMultipart(s3Key, uploadId, partETags));
    responseObserver.onNext(response);
    responseObserver.onCompleted();
  } catch (Exception e) {
    ModelDBUtils.observeError(
        responseObserver, e, CommitMultipartArtifact.Response.getDefaultInstance());
  }
}