use of org.molgenis.emx2.graphql.GraphqlException in project graphql-java-servlet by graphql-java-kickstart.
the class HttpRequestInvokerImpl method invokeAndHandleAsync.
private void invokeAndHandleAsync(GraphQLInvocationInput invocationInput, HttpServletRequest request, HttpServletResponse response, ListenerHandler listenerHandler) {
AsyncContext asyncContext = request.isAsyncStarted() ? request.getAsyncContext() : request.startAsync(request, response);
asyncContext.setTimeout(configuration.getAsyncTimeout());
AtomicReference<FutureExecutionResult> futureHolder = new AtomicReference<>();
AsyncTimeoutListener timeoutListener = event -> {
log.warn("GraphQL execution canceled because timeout of " + configuration.getAsyncTimeout() + " millis was reached. The following query was being executed when this happened:\n{}", String.join("\n", invocationInput.getQueries()));
FutureExecutionResult futureResult = futureHolder.get();
if (futureResult != null) {
futureResult.cancel();
} else {
writeErrorResponse(invocationInput, request, response, listenerHandler, new CancellationException());
}
};
asyncContext.addListener(timeoutListener);
configuration.getAsyncExecutor().execute(() -> {
try {
FutureExecutionResult futureResult = invoke(invocationInput, request, response);
futureHolder.set(futureResult);
handle(futureResult, request, response, listenerHandler).thenAccept(it -> asyncContext.complete());
} catch (GraphQLException e) {
response.setStatus(STATUS_BAD_REQUEST);
log.info("Bad request: cannot handle http request", e);
listenerHandler.onError(e);
asyncContext.complete();
} catch (Exception e) {
response.setStatus(STATUS_INTERNAL_SERVER_ERROR);
log.error("Cannot handle http request", e);
listenerHandler.onError(e);
asyncContext.complete();
}
});
}
use of org.molgenis.emx2.graphql.GraphqlException in project mc-doubletap by mbround18.
the class KeycloakAuthorizer method authenticate.
@Override
public Policy[] authenticate(Object context) {
if (context == null || context.toString() == null) {
return null;
}
String jwt = context.toString();
if (!jwt.startsWith("Bearer")) {
throw new GraphQLException("Token did not include prefix!");
}
jwt = jwt.substring(7);
KeycloakJWT jwtParsed = parseJwt(jwt);
boolean isValid = jwtParsed.isValid(context.toString());
if (!isValid) {
throw new GraphQLException("The provided token is invalid!");
}
Stream<String> roles = Arrays.stream(jwtParsed.roles());
Stream<Policy[]> policies = roles.map(this::fetchPolicies);
return policies.flatMap(Arrays::stream).toArray(Policy[]::new);
}
use of org.molgenis.emx2.graphql.GraphqlException in project mc-doubletap by mbround18.
the class WhitelistMutations method setUserWhitelistStatus.
private static OfflinePlayer setUserWhitelistStatus(String name, Boolean status) {
PlayerInfo playerInfo = fetchPlayerByName(name);
if (playerInfo == null) {
throw new GraphQLException(format("Player %s not found!", name));
}
OfflinePlayer player = getOfflinePlayer(playerInfo.idToUUID());
if (player.isWhitelisted() == status) {
logger.info(format("%s whitelist status is unchanged", name));
return player;
}
String logMessage;
if (status) {
logMessage = format("Added %s to whitelist", name);
} else {
logMessage = format("Removed %s from whitelist", name);
}
logger.info(logMessage);
player.setWhitelisted(status);
return player;
}
use of org.molgenis.emx2.graphql.GraphqlException in project federation-jvm by apollographql.
the class FederatedTracingInstrumentationTest method setupSchema.
@BeforeEach
void setupSchema() {
TypeDefinitionRegistry typeDefs = new SchemaParser().parse(tracingSDL);
RuntimeWiring resolvers = RuntimeWiring.newRuntimeWiring().type("Query", builder -> builder.dataFetcher("widgets", env -> {
ArrayList<Object> objects = new ArrayList<>(2);
objects.add(new Object());
objects.add(new Object());
return objects;
}).dataFetcher("listOfLists", env -> {
ArrayList<ArrayList<Object>> lists = new ArrayList<>(2);
lists.add(new ArrayList<>(2));
lists.add(new ArrayList<>(2));
lists.get(0).add(new Object());
lists.get(0).add(new Object());
lists.get(1).add(new Object());
lists.get(1).add(new Object());
return lists;
}).dataFetcher("listOfScalars", env -> new String[] { "one", "two", "three" })).type("Widget", builder -> builder.dataFetcher("foo", env -> "hello world").dataFetcher("bar", env -> {
throw new GraphQLException("whoops");
})).build();
GraphQLSchema graphQLSchema = new SchemaGenerator().makeExecutableSchema(typeDefs, resolvers);
graphql = GraphQL.newGraphQL(graphQLSchema).instrumentation(new FederatedTracingInstrumentation()).build();
}
use of org.molgenis.emx2.graphql.GraphqlException in project graphql-calculator by graphql-calculator.
the class AsyncExecutionStrategy method completeValueForList.
/**
* Called to complete a list of value for a field based on a list type. This iterates the values and calls
* {@link #completeValue(ExecutionContext, ExecutionStrategyParameters)} for each value.
*
* @param executionContext contains the top level execution parameters
* @param parameters contains the parameters holding the fields to be executed and source object
* @param iterableValues the values to complete, can't be null
* @return a {@link FieldValueInfo}
*/
protected FieldValueInfo completeValueForList(ExecutionContext executionContext, ExecutionStrategyParameters parameters, Iterable<Object> iterableValues) {
OptionalInt size = FpKit.toSize(iterableValues);
ExecutionStepInfo executionStepInfo = parameters.getExecutionStepInfo();
InstrumentationFieldCompleteParameters instrumentationParams = new InstrumentationFieldCompleteParameters(executionContext, parameters, () -> executionStepInfo, iterableValues);
Instrumentation instrumentation = executionContext.getInstrumentation();
InstrumentationContext<ExecutionResult> completeListCtx = instrumentation.beginFieldListComplete(instrumentationParams);
List<FieldValueInfo> fieldValueInfos = new ArrayList<>(size.orElse(1));
int index = 0;
for (Object item : iterableValues) {
ResultPath indexedPath = parameters.getPath().segment(index);
ExecutionStepInfo stepInfoForListElement = executionStepInfoFactory.newExecutionStepInfoForListElement(executionStepInfo, index);
NonNullableFieldValidator nonNullableFieldValidator = new NonNullableFieldValidator(executionContext, stepInfoForListElement);
int finalIndex = index;
FetchedValue value = unboxPossibleDataFetcherResult(executionContext, parameters, item);
ExecutionStrategyParameters newParameters = parameters.transform(builder -> builder.executionStepInfo(stepInfoForListElement).nonNullFieldValidator(nonNullableFieldValidator).listSize(// -1 signals that we don't know the size
size.orElse(-1)).localContext(value.getLocalContext()).currentListIndex(finalIndex).path(indexedPath).source(value.getFetchedValue()));
fieldValueInfos.add(completeValue(executionContext, newParameters));
index++;
}
// 将列表元素对应的异步任务 List<CompletableFuture<Object>> 转换成所有元素结果集合对应的异步任务 CompletableFuture<List<Object>>
CompletableFuture<List<ExecutionResult>> resultsFuture = Async.each(fieldValueInfos, (item, i) -> item.getFieldValue());
CompletableFuture<ExecutionResult> overallResult = new CompletableFuture<>();
completeListCtx.onDispatched(overallResult);
resultsFuture.whenComplete((results, exception) -> {
if (exception != null) {
ExecutionResult executionResult = handleNonNullException(executionContext, overallResult, exception);
completeListCtx.onCompleted(executionResult, exception);
return;
}
List<Object> completedResults = new ArrayList<>(results.size());
for (ExecutionResult completedValue : results) {
completedResults.add(completedValue.getData());
}
ExecutionResultImpl executionResult = new ExecutionResultImpl(completedResults, null);
// onCompleted before 'overallResult.complete(executionResult)'
// if onCompleted throw Exception, then it will handed in whenComplete
completeListCtx.onCompleted(executionResult, null);
overallResult.complete(executionResult);
}).whenComplete((ignored, exception) -> {
if (exception != null) {
AbortExecutionException graphQLException = new AbortExecutionException(exception.getMessage());
ExecutionResultImpl resultx = new ExecutionResultImpl(null, Collections.singletonList(graphQLException));
overallResult.complete(resultx);
}
});
return FieldValueInfo.newFieldValueInfo(LIST).fieldValue(overallResult).fieldValueInfos(fieldValueInfos).build();
}
Aggregations