@Override public void drop() { // 'true' dropping in the sense of dropping on the floor doesn't seem easily done with Jetty sendReply(Response.forStatus(Status.INTERNAL_SERVER_ERROR.withReasonPhrase("dropped"))); }
private static void handleException(Throwable e, OngoingRequest ongoingRequest) { String message = e.getMessage(); message = !Strings.isNullOrEmpty(message) ? ": \"" + message + "\"" : ""; message = CharMatcher.anyOf("\n\r").replaceFrom(message, ' '); LOG.warn("Got Exception {} when invoking endpoint for request: {}", message, ongoingRequest.request(), e); ongoingRequest.reply(forStatus(INTERNAL_SERVER_ERROR.withReasonPhrase(message))); } }
private <E> Either<Response<?>, E> deserialize(RequestContext rc, Class<? extends E> entityClass) { final Optional<ByteString> payloadOpt = rc.request().payload(); if (!payloadOpt.isPresent()) { return Either.left(Response.forStatus( Status.BAD_REQUEST .withReasonPhrase("Missing payload"))); } final E entity; try { entity = codec.read(payloadOpt.get(), entityClass, rc); } catch (Throwable e) { LOG.warn("error", e); return Either.left(Response.forStatus( Status.BAD_REQUEST .withReasonPhrase("Payload parsing failed: " + e.getMessage()))); } return Either.right(entity); }
private <R> Function<Response<R>, Response<ByteString>> serialize( RequestContext rc, Class<? extends R> entityClass) { return response -> { final Optional<R> entityOpt = response.payload(); if (!entityOpt.isPresent()) { //noinspection unchecked return (Response<ByteString>) response; } final EncodedResponse encoded; try { encoded = codec.write(entityOpt.get(), entityClass, rc); } catch (Throwable e) { LOG.error("error", e); return Response.forStatus( Status.INTERNAL_SERVER_ERROR .withReasonPhrase("Payload serialization failed: " + e.getMessage())); } final Response<ByteString> result = response.withPayload(encoded.data()); return contentType != null ? result.withHeader(CONTENT_TYPE, contentType) : encoded.contentType().isPresent() ? result.withHeader(CONTENT_TYPE, encoded.contentType().get()) : result; }; } }
private StatusType eventInjectorHelper(Event event) { try { stateManager.receive(event).toCompletableFuture().get(); } catch (IsClosedException | InterruptedException e) { return INTERNAL_SERVER_ERROR.withReasonPhrase(e.getMessage()); } catch (ExecutionException e) { if (e.getCause() instanceof IllegalArgumentException || e.getCause() instanceof IllegalStateException) { return BAD_REQUEST.withReasonPhrase(e.getCause().getMessage()); } else { return INTERNAL_SERVER_ERROR.withReasonPhrase(e.getMessage()); } } return OK; }
private Response<TriggerRequest> handleException(final ExecutionException e) { Throwable cause; if ((cause = findCause(e, IllegalStateException.class)) != null || (cause = findCause(e, IllegalArgumentException.class)) != null) { // TODO: propagate error information using a more specific exception type return Response.forStatus(CONFLICT.withReasonPhrase(cause.getMessage())); } else if (findCause(e, AlreadyInitializedException.class) != null) { return Response.forStatus(CONFLICT.withReasonPhrase( "This workflow instance is already triggered. Did you want to `retry` running it instead?")); } else { return Response.forStatus(INTERNAL_SERVER_ERROR.withReasonPhrase(e.getCause().getMessage())); } } }
private ResponseException denialResponseException(String message) { return new ResponseException(Response.forStatus(FORBIDDEN.withReasonPhrase(message))); }
public static <T> Middleware<AsyncHandler<Response<T>>, AsyncHandler<Response<T>>> clientValidator( Supplier<List<String>> supplier) { return innerHandler -> requestContext -> { if (requestContext.request().header("User-Agent") // TODO: should the blacklist be a set so this lookup is O(1) instead of O(n) ? .map(header -> supplier.get().contains(header)) .orElse(false)) { // TODO: fire some stats return completedFuture(Response.forStatus(Status.NOT_ACCEPTABLE.withReasonPhrase( "blacklisted client version, please upgrade"))); } else { return innerHandler.invoke(requestContext); } }; }
private Response<Collection<Workflow>> workflows() { try { return Response.forPayload(storage.workflows().values()); } catch (IOException e) { return Response.forStatus(Status.INTERNAL_SERVER_ERROR.withReasonPhrase( "Failed to get workflows")); } }
private Optional<String> projectPolicyAccess(String projectId, String principalEmail) { final com.google.api.services.cloudresourcemanager.model.Policy policy = getProjectPolicy(projectId) .orElseThrow(() -> new ResponseException(Response.forStatus( BAD_REQUEST.withReasonPhrase("Project does not exist: " + projectId)))); final List<String> members = emptyListIfNull(policy.getBindings()).stream() .filter(binding -> serviceAccountUserRole.equals(binding.getRole())) .flatMap(binding -> emptyListIfNull(binding.getMembers()).stream()) .collect(toList()); return memberStatus(principalEmail, members); }
public void authorizeWorkflowAction(AuthContext ac, WorkflowId workflowId) { final Optional<Workflow> workflowOpt; try { workflowOpt = storage.workflow(workflowId); } catch (IOException e) { throw new RuntimeException(e); } final Workflow workflow = workflowOpt.orElseThrow(() -> new ResponseException( Response.forStatus(Status.NOT_FOUND.withReasonPhrase("workflow not found")))); authorizeWorkflowAction(ac, workflow); }
private Optional<String> serviceAccountPolicyAccess(String serviceAccount, String principalEmail) { final com.google.api.services.iam.v1.model.Policy policy = getServiceAccountPolicy(serviceAccount) .orElseThrow(() -> new ResponseException(Response.forStatus( BAD_REQUEST.withReasonPhrase("Service account does not exist: " + serviceAccount)))); final List<String> members = emptyListIfNull(policy.getBindings()).stream() .filter(binding -> serviceAccountUserRole.equals(binding.getRole())) .flatMap(binding -> emptyListIfNull(binding.getMembers()).stream()) .collect(toList()); return memberStatus(principalEmail, members); }
private <E> Either<Response<?>, E> deserialize(RequestContext rc, Class<? extends E> entityClass) { final Optional<ByteString> payloadOpt = rc.request().payload(); if (!payloadOpt.isPresent()) { return Either.left(Response.forStatus( Status.BAD_REQUEST .withReasonPhrase("Missing payload"))); } final E entity; try { entity = codec.read(payloadOpt.get(), entityClass, rc); } catch (Throwable e) { LOG.warn("error", e); return Either.left(Response.forStatus( Status.BAD_REQUEST .withReasonPhrase("Payload parsing failed: " + e.getMessage()))); } return Either.right(entity); }
private Response<List<Workflow>> workflows(String componentId) { try { return Response.forPayload(storage.workflows(componentId)); } catch (IOException e) { return Response.forStatus(Status.INTERNAL_SERVER_ERROR.withReasonPhrase( "Failed to get workflows of component " + componentId)); } }
public static <T> Middleware<AsyncHandler<Response<T>>, AsyncHandler<Response<T>>> authenticator( RequestAuthenticator authenticator) { return h -> rc -> { final Optional<GoogleIdToken> idToken = auth(rc, authenticator).user(); if (!"GET".equals(rc.request().method()) && !idToken.isPresent()) { return completedFuture( Response.forStatus(Status.UNAUTHORIZED.withReasonPhrase("Unauthorized access"))); } return h.invoke(rc); }; } }
private Response<Resource> updateResource(String id, Resource resource) { if (!resource.id().equals(id)) { return Response.forStatus( Status.BAD_REQUEST.withReasonPhrase("ID of payload does not match ID in uri.")); } try { storage.storeResource(resource); } catch (IOException e) { throw new RuntimeException(e); } return Response.forStatus(Status.OK).withPayload(resource); } }
private Response<WorkflowState> state(String componentId, String id) { try { return Response.forPayload(storage.workflowState(WorkflowId.create(componentId, id))); } catch (IOException e) { return Response .forStatus(Status.INTERNAL_SERVER_ERROR.withReasonPhrase("Couldn't fetch state.")); } }
private Response<WorkflowInstanceExecutionData> instance( String componentId, String id, String instanceId) { final WorkflowId workflowId = WorkflowId.create(componentId, id); final WorkflowInstance workflowInstance = WorkflowInstance.create(workflowId, instanceId); try { final WorkflowInstanceExecutionData workflowInstanceExecutionData = storage.executionData(workflowInstance); return Response.forPayload(workflowInstanceExecutionData); } catch (ResourceNotFoundException e) { return Response.forStatus(Status.NOT_FOUND.withReasonPhrase(e.getMessage())); } catch (IOException e) { return Response.forStatus( Status.INTERNAL_SERVER_ERROR.withReasonPhrase("Couldn't fetch execution info.")); } }
private Response<WorkflowInstance> retryWorkflowInstanceAfter(AuthContext ac, RequestContext rc, WorkflowInstance workflowInstance) { workflowActionAuthorizer.authorizeWorkflowAction(ac, workflowInstance.workflowId()); final long delay; try { delay = Long.parseLong(rc.request().parameter("delay").orElse("0")); } catch (NumberFormatException e) { return Response.forStatus(BAD_REQUEST.withReasonPhrase( "Delay parameter could not be parsed")); } final Event event = Event.retryAfter(workflowInstance, delay); return Response.forStatus(eventInjectorHelper(event)).withPayload(workflowInstance); }
private Response<Event> injectEvent(AuthContext ac, Event event) { workflowActionAuthorizer.authorizeWorkflowAction(ac, event.workflowInstance().workflowId()); if ("dequeue".equals(EventUtil.name(event))) { // For backwards compatibility return Response.forStatus(eventInjectorHelper( Event.retryAfter(event.workflowInstance(), 0L))).withPayload(event); } else if ("halt".equals(EventUtil.name(event))) { // For backwards compatibility return Response.forStatus(eventInjectorHelper(event)); } else if ("timeout".equals(EventUtil.name(event))) { // This is for manually getting out of a stale state return Response.forStatus(eventInjectorHelper(event)); } else { return Response.forStatus(BAD_REQUEST.withReasonPhrase( "This API for injecting generic events is deprecated, refer to the specific API for the " + "event you want to send to the scheduler")); } }