com.google.rpc.Status Java Examples
The following examples show how to use
com.google.rpc.Status.
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: ModelDBUtils.java From modeldb with Apache License 2.0 | 6 votes |
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 #2
Source File: ModelDBUtils.java From modeldb with Apache License 2.0 | 6 votes |
/** * 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 #3
Source File: PublicRoleServiceUtils.java From modeldb with Apache License 2.0 | 6 votes |
/** * 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 #4
Source File: DefaultStreamObserverFactory.java From buck with Apache License 2.0 | 6 votes |
@Override public StreamObserver<Status> createStreamObserver(String path) { return new StreamObserver<Status>() { @Override public void onNext(Status response) { LOG.info("Logs written to " + path); } @Override public void onError(Throwable t) { LOG.error(t, "LogD failed to send a response: " + io.grpc.Status.fromThrowable(t)); } @Override public void onCompleted() { LOG.info("LogD closing stream to " + path); } }; }
Example #5
Source File: ExperimentDAORdbImpl.java From modeldb with Apache License 2.0 | 6 votes |
@Override public Experiment getExperiment(String experimentId) throws InvalidProtocolBufferException { try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) { ExperimentEntity experimentObj = session.get(ExperimentEntity.class, experimentId); if (experimentObj != null && !experimentObj.getDeleted()) { LOGGER.debug("Experiment getting successfully"); return experimentObj.getProtoObject(); } else { String errorMessage = ModelDBMessages.EXPERIMENT_NOT_FOUND_ERROR_MSG + experimentId; LOGGER.info(errorMessage); Status status = Status.newBuilder().setCode(Code.NOT_FOUND_VALUE).setMessage(errorMessage).build(); throw StatusProto.toStatusRuntimeException(status); } } catch (Exception ex) { if (ModelDBUtils.needToRetry(ex)) { return getExperiment(experimentId); } else { throw ex; } } }
Example #6
Source File: MetricsPublisherTest.java From bazel-buildfarm with Apache License 2.0 | 6 votes |
@Test public void preconditionFailureTest() { Status status = Status.getDefaultInstance().toBuilder().addDetails(Any.pack(preconditionFailure)).build(); Operation operation = defaultOperation .toBuilder() .setResponse(Any.pack(defaultExecuteResponse.toBuilder().setStatus(status).build())) .setMetadata(Any.pack(defaultExecuteOperationMetadata)) .build(); assertThat( new AwsMetricsPublisher(metricsConfig) .populateRequestMetadata(operation, defaultRequestMetadata)) .isNotNull(); }
Example #7
Source File: DatasetServiceImpl.java From modeldb with Apache License 2.0 | 6 votes |
@Override public void deleteDatasets( DeleteDatasets request, StreamObserver<DeleteDatasets.Response> responseObserver) { QPSCountResource.inc(); try (RequestLatencyResource latencyResource = new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) { // Request Parameter Validation if (request.getIdsList().isEmpty()) { LOGGER.info(ModelDBMessages.DATASET_ID_NOT_FOUND_IN_REQUEST); Status status = Status.newBuilder() .setCode(Code.INVALID_ARGUMENT_VALUE) .setMessage(ModelDBMessages.DATASET_ID_NOT_FOUND_IN_REQUEST) .addDetails(Any.pack(DeleteDatasets.Response.getDefaultInstance())) .build(); throw StatusProto.toStatusRuntimeException(status); } boolean deleteStatus = datasetDAO.deleteDatasets(request.getIdsList()); responseObserver.onNext(DeleteDatasets.Response.newBuilder().setStatus(deleteStatus).build()); responseObserver.onCompleted(); } catch (Exception e) { ModelDBUtils.observeError(responseObserver, e, DeleteDatasets.Response.getDefaultInstance()); } }
Example #8
Source File: ExperimentRunDAORdbImpl.java From modeldb with Apache License 2.0 | 6 votes |
@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 #9
Source File: ExperimentRunDAORdbImpl.java From modeldb with Apache License 2.0 | 6 votes |
@Override public List<KeyValue> getExperimentRunMetrics(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 Metrics"); return experimentRunObj.getProtoObject().getMetricsList(); } catch (Exception ex) { if (ModelDBUtils.needToRetry(ex)) { return getExperimentRunMetrics(experimentRunId); } else { throw ex; } } }
Example #10
Source File: CampaignExperimentServiceClient.java From google-ads-java with Apache License 2.0 | 6 votes |
public static ApiFuture<ListCampaignExperimentAsyncErrorsPagedResponse> createAsync( PageContext< ListCampaignExperimentAsyncErrorsRequest, ListCampaignExperimentAsyncErrorsResponse, Status> context, ApiFuture<ListCampaignExperimentAsyncErrorsResponse> futureResponse) { ApiFuture<ListCampaignExperimentAsyncErrorsPage> futurePage = ListCampaignExperimentAsyncErrorsPage.createEmptyPage() .createPageAsync(context, futureResponse); return ApiFutures.transform( futurePage, new ApiFunction< ListCampaignExperimentAsyncErrorsPage, ListCampaignExperimentAsyncErrorsPagedResponse>() { @Override public ListCampaignExperimentAsyncErrorsPagedResponse apply( ListCampaignExperimentAsyncErrorsPage input) { return new ListCampaignExperimentAsyncErrorsPagedResponse(input); } }, MoreExecutors.directExecutor()); }
Example #11
Source File: GoogleVideosImporterTest.java From data-transfer-project with Apache License 2.0 | 6 votes |
@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 #12
Source File: ExperimentRunDAORdbImpl.java From modeldb with Apache License 2.0 | 6 votes |
@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 #13
Source File: MemoryCAS.java From bazel-buildfarm with Apache License 2.0 | 6 votes |
@Override public void get( Digest digest, long offset, long limit, ServerCallStreamObserver<ByteString> blobObserver, RequestMetadata requestMetadata) { Blob blob = get(digest); if (blob == null) { if (delegate != null) { // FIXME change this to a read-through get delegate.get(digest, offset, limit, blobObserver, requestMetadata); } else { blobObserver.onError(io.grpc.Status.NOT_FOUND.asException()); } } else { blobObserver.onNext(blob.getData()); blobObserver.onCompleted(); } }
Example #14
Source File: ExperimentRunDAORdbImpl.java From modeldb with Apache License 2.0 | 6 votes |
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 #15
Source File: CampaignDraftServiceStubSettings.java From google-ads-java with Apache License 2.0 | 6 votes |
@Override public ApiFuture<ListCampaignDraftAsyncErrorsPagedResponse> getFuturePagedResponse( UnaryCallable< ListCampaignDraftAsyncErrorsRequest, ListCampaignDraftAsyncErrorsResponse> callable, ListCampaignDraftAsyncErrorsRequest request, ApiCallContext context, ApiFuture<ListCampaignDraftAsyncErrorsResponse> futureResponse) { PageContext< ListCampaignDraftAsyncErrorsRequest, ListCampaignDraftAsyncErrorsResponse, Status> pageContext = PageContext.create( callable, LIST_CAMPAIGN_DRAFT_ASYNC_ERRORS_PAGE_STR_DESC, request, context); return ListCampaignDraftAsyncErrorsPagedResponse.createAsync( pageContext, futureResponse); }
Example #16
Source File: CloudVisionTemplateTests.java From spring-cloud-gcp with Apache License 2.0 | 6 votes |
@Test public void testExtractTextError() { AnnotateImageResponse response = AnnotateImageResponse.newBuilder() .setError( Status.newBuilder() .setCode(Code.INTERNAL.value()) .setMessage("Error Message from Vision API.")) .build(); BatchAnnotateImagesResponse responseBatch = BatchAnnotateImagesResponse .newBuilder() .addResponses(response) .build(); when(this.imageAnnotatorClient.batchAnnotateImages(any(BatchAnnotateImagesRequest.class))) .thenReturn(responseBatch); this.expectedException.expect(CloudVisionException.class); this.expectedException.expectMessage("Error Message from Vision API."); this.cloudVisionTemplate.extractTextFromImage(FAKE_IMAGE); }
Example #17
Source File: MemoryInstanceTest.java From bazel-buildfarm with Apache License 2.0 | 6 votes |
@Test public void missingOperationIsNotFound() throws InterruptedException { Watcher watcher = mock(Watcher.class); doThrow(io.grpc.Status.NOT_FOUND.asRuntimeException()).when(watcher).observe(eq(null)); boolean caughtNotFoundException = false; try { instance.watchOperation("does-not-exist", watcher).get(); } catch (ExecutionException e) { io.grpc.Status status = io.grpc.Status.fromThrowable(e); if (status.getCode() == io.grpc.Status.Code.NOT_FOUND) { caughtNotFoundException = true; } } assertThat(caughtNotFoundException).isTrue(); verify(watcher, times(1)).observe(eq(null)); }
Example #18
Source File: RemoteRpcTest.java From google-cloud-datastore with Apache License 2.0 | 5 votes |
@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 #19
Source File: ExperimentRunServiceImpl.java From modeldb with Apache License 2.0 | 5 votes |
@Override public void updateExperimentRunName( UpdateExperimentRunName request, StreamObserver<UpdateExperimentRunName.Response> responseObserver) { QPSCountResource.inc(); try (RequestLatencyResource latencyResource = new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) { if (request.getId().isEmpty()) { String errorMessage = "ExperimentRun ID not found in UpdateExperimentRunName request"; LOGGER.info(errorMessage); Status status = Status.newBuilder() .setCode(Code.INVALID_ARGUMENT_VALUE) .setMessage(errorMessage) .addDetails(Any.pack(UpdateExperimentRunName.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.updateExperimentRunName( request.getId(), ModelDBUtils.checkEntityNameLength(request.getName())); responseObserver.onNext(UpdateExperimentRunName.Response.newBuilder().build()); responseObserver.onCompleted(); } catch (Exception e) { ModelDBUtils.observeError( responseObserver, e, UpdateExperimentRunName.Response.getDefaultInstance()); } }
Example #20
Source File: ProjectServiceImpl.java From modeldb with Apache License 2.0 | 5 votes |
@Override public void getProjectReadme( GetProjectReadme request, StreamObserver<GetProjectReadme.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 GetProjectReadme request"; LOGGER.info(errorMessage); Status status = Status.newBuilder() .setCode(Code.INVALID_ARGUMENT_VALUE) .setMessage(errorMessage) .addDetails(Any.pack(GetProjectReadme.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( GetProjectReadme.Response.newBuilder().setReadmeText(project.getReadmeText()).build()); responseObserver.onCompleted(); } catch (Exception e) { ModelDBUtils.observeError( responseObserver, e, GetProjectReadme.Response.getDefaultInstance()); } }
Example #21
Source File: GrpcClientErrorUtils.java From titus-control-plane with Apache License 2.0 | 5 votes |
public static <D extends MessageOrBuilder> Optional<D> getDetail(StatusRuntimeException error, Class<D> detailType) { Status status = getStatus(error); for (Any any : status.getDetailsList()) { Descriptors.Descriptor descriptor = any.getDescriptorForType(); Descriptors.FieldDescriptor typeUrlField = descriptor.findFieldByName("type_url"); String typeUrl = (String) any.getField(typeUrlField); Class type; if (typeUrl.contains(DebugInfo.class.getSimpleName())) { type = DebugInfo.class; } else if (typeUrl.contains(BadRequest.class.getSimpleName())) { type = BadRequest.class; } else { return Optional.empty(); } if (type == detailType) { Message unpack; try { unpack = any.unpack(type); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException("Cannot unpack error details", e); } return Optional.of((D) unpack); } } return Optional.empty(); }
Example #22
Source File: ExperimentRunDAORdbImpl.java From modeldb with Apache License 2.0 | 5 votes |
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 #23
Source File: AbstractErrorUtilsTest.java From google-ads-java with Apache License 2.0 | 5 votes |
@Test public void getGoogleAdsErrors_omitsWhen_operationIndexOutOfSequenceInPaths() throws InvalidProtocolBufferException { MockPath path0 = MockPath.newBuilder().setFieldName("someotherfield").build(); MockPath path1 = MockPath.newBuilder() .setIndex(Int64Value.newBuilder().setValue(0)) .setFieldName(operationsFieldName) .build(); MockError error = MockError.newBuilder().addLocation(path0).addLocation(path1).build(); MockFailure failure = MockFailure.newBuilder().addErrors(error).build(); Status status = Status.newBuilder().addDetails(Any.pack(failure)).build(); List<MockError> result = impl.getGoogleAdsErrors(0, status); assertEquals(0, result.size()); }
Example #24
Source File: CampaignDraftServiceClient.java From google-ads-java with Apache License 2.0 | 5 votes |
@Override public ApiFuture<ListCampaignDraftAsyncErrorsPage> createPageAsync( PageContext< ListCampaignDraftAsyncErrorsRequest, ListCampaignDraftAsyncErrorsResponse, Status> context, ApiFuture<ListCampaignDraftAsyncErrorsResponse> futureResponse) { return super.createPageAsync(context, futureResponse); }
Example #25
Source File: AbstractErrorUtilsTest.java From google-ads-java with Apache License 2.0 | 5 votes |
@Test public void getGoogleAdsErrors_omitsWhen_missingFieldName() throws InvalidProtocolBufferException { MockPath path = MockPath.newBuilder().setIndex(Int64Value.newBuilder().setValue(0).build()).build(); MockError error = MockError.newBuilder().addLocation(path).build(); MockFailure failure = MockFailure.newBuilder().addErrors(error).build(); Status status = Status.newBuilder().addDetails(Any.pack(failure)).build(); List<MockError> result = impl.getGoogleAdsErrors(0, status); assertEquals(0, result.size()); }
Example #26
Source File: ExperimentRunServiceImpl.java From modeldb with Apache License 2.0 | 5 votes |
@Override public void logJobId(LogJobId request, StreamObserver<LogJobId.Response> responseObserver) { QPSCountResource.inc(); try (RequestLatencyResource latencyResource = new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) { String errorMessage = null; if (request.getId().isEmpty() && request.getJobId().isEmpty()) { errorMessage = "ExperimentRun ID and Job ID not found in LogJobId request"; } else if (request.getId().isEmpty()) { errorMessage = "ExperimentRun ID not found in LogJobId request"; } else if (request.getJobId().isEmpty()) { errorMessage = "Job ID not found in LogJobId request"; } if (errorMessage != null) { LOGGER.info(errorMessage); Status status = Status.newBuilder() .setCode(Code.INVALID_ARGUMENT_VALUE) .setMessage(errorMessage) .addDetails(Any.pack(LogJobId.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.logJobId(request.getId(), request.getJobId()); responseObserver.onNext(LogJobId.Response.newBuilder().build()); responseObserver.onCompleted(); } catch (Exception e) { ModelDBUtils.observeError(responseObserver, e, LogJobId.Response.getDefaultInstance()); } }
Example #27
Source File: DatasetDAORdbImpl.java From modeldb with Apache License 2.0 | 5 votes |
@Override public Boolean deleteDatasets(List<String> datasetIds) { // Get self allowed resources id where user has delete permission List<String> allowedDatasetIds = roleService.getAccessibleResourceIdsByActions( ModelDBServiceResourceTypes.DATASET, ModelDBActionEnum.ModelDBServiceActions.DELETE, datasetIds); if (allowedDatasetIds.isEmpty()) { Status status = Status.newBuilder() .setCode(Code.PERMISSION_DENIED_VALUE) .setMessage("Access Denied for given dataset Ids : " + datasetIds) .build(); throw StatusProto.toStatusRuntimeException(status); } try (Session session = ModelDBHibernateUtil.getSessionFactory().openSession()) { Transaction transaction = session.beginTransaction(); Query deletedDatasetsQuery = session.createQuery(DELETED_STATUS_DATASET_QUERY_STRING); deletedDatasetsQuery.setParameter("deleted", true); deletedDatasetsQuery.setParameter("datasetIds", allowedDatasetIds); int updatedCount = deletedDatasetsQuery.executeUpdate(); LOGGER.debug("Mark Datasets as deleted : {}, count : {}", allowedDatasetIds, updatedCount); transaction.commit(); LOGGER.debug("Dataset deleted successfully"); return true; } catch (Exception ex) { if (ModelDBUtils.needToRetry(ex)) { return deleteDatasets(datasetIds); } else { throw ex; } } }
Example #28
Source File: Actions.java From bazel-buildfarm with Apache License 2.0 | 5 votes |
public static void checkPreconditionFailure( Digest actionDigest, PreconditionFailure preconditionFailure) throws StatusException { if (preconditionFailure.getViolationsCount() != 0) { throw StatusProto.toStatusException( Status.newBuilder() .setCode(Code.FAILED_PRECONDITION.getNumber()) .setMessage(invalidActionVerboseMessage(actionDigest, preconditionFailure)) .addDetails(Any.pack(preconditionFailure)) .build()); } }
Example #29
Source File: Actions.java From bazel-buildfarm with Apache License 2.0 | 5 votes |
public static Status asExecutionStatus(Throwable t) { Status.Builder status = Status.newBuilder(); io.grpc.Status grpcStatus = io.grpc.Status.fromThrowable(t); switch (grpcStatus.getCode()) { case DEADLINE_EXCEEDED: // translate timeouts to retriable errors here, rather than // indications that the execution timed out status.setCode(Code.UNAVAILABLE.getNumber()); break; default: status.setCode(grpcStatus.getCode().value()); break; } return status.setMessage(t.getMessage()).build(); }
Example #30
Source File: ExperimentRunServiceImpl.java From modeldb with Apache License 2.0 | 5 votes |
@Override public void logMetrics(LogMetrics request, StreamObserver<LogMetrics.Response> responseObserver) { QPSCountResource.inc(); try (RequestLatencyResource latencyResource = new RequestLatencyResource(ModelDBAuthInterceptor.METHOD_NAME.get())) { String errorMessage = null; if (request.getId().isEmpty() && request.getMetricsList().isEmpty()) { errorMessage = "ExperimentRun ID and New Metrics not found in LogMetrics request"; } else if (request.getId().isEmpty()) { errorMessage = "ExperimentRun ID not found in LogMetrics request"; } else if (request.getMetricsList().isEmpty()) { errorMessage = "New Metrics not found in LogMetrics request"; } if (errorMessage != null) { LOGGER.info(errorMessage); Status status = Status.newBuilder() .setCode(Code.INVALID_ARGUMENT_VALUE) .setMessage(errorMessage) .addDetails(Any.pack(LogMetrics.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(), request.getMetricsList()); responseObserver.onNext(LogMetrics.Response.newBuilder().build()); responseObserver.onCompleted(); } catch (Exception e) { ModelDBUtils.observeError(responseObserver, e, LogMetrics.Response.getDefaultInstance()); } }