Search in sources :

Example 1 with GraphqlException

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();
        }
    });
}
Also used : GenericGraphQLError(graphql.kickstart.execution.error.GenericGraphQLError) RequiredArgsConstructor(lombok.RequiredArgsConstructor) CompletableFuture(java.util.concurrent.CompletableFuture) GraphQLQueryResult(graphql.kickstart.execution.GraphQLQueryResult) GraphQLSingleInvocationInput(graphql.kickstart.execution.input.GraphQLSingleInvocationInput) AtomicReference(java.util.concurrent.atomic.AtomicReference) ExecutionResult(graphql.ExecutionResult) AsyncContext(javax.servlet.AsyncContext) HttpServletRequest(javax.servlet.http.HttpServletRequest) GraphQLInvoker(graphql.kickstart.execution.GraphQLInvoker) GraphQLException(graphql.GraphQLException) STATUS_INTERNAL_SERVER_ERROR(graphql.kickstart.servlet.HttpRequestHandler.STATUS_INTERNAL_SERVER_ERROR) ExecutionResultImpl(graphql.ExecutionResultImpl) CancellationException(java.util.concurrent.CancellationException) GraphQLBatchedInvocationInput(graphql.kickstart.execution.input.GraphQLBatchedInvocationInput) HttpServletResponse(javax.servlet.http.HttpServletResponse) GraphQLInvocationInput(graphql.kickstart.execution.input.GraphQLInvocationInput) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) BatchInputPreProcessResult(graphql.kickstart.servlet.input.BatchInputPreProcessResult) UncheckedIOException(java.io.UncheckedIOException) Slf4j(lombok.extern.slf4j.Slf4j) STATUS_BAD_REQUEST(graphql.kickstart.servlet.HttpRequestHandler.STATUS_BAD_REQUEST) FutureExecutionResult(graphql.kickstart.execution.FutureExecutionResult) BatchInputPreProcessor(graphql.kickstart.servlet.input.BatchInputPreProcessor) CancellationException(java.util.concurrent.CancellationException) FutureExecutionResult(graphql.kickstart.execution.FutureExecutionResult) AsyncContext(javax.servlet.AsyncContext) AtomicReference(java.util.concurrent.atomic.AtomicReference) GraphQLException(graphql.GraphQLException) GraphQLException(graphql.GraphQLException) CancellationException(java.util.concurrent.CancellationException) IOException(java.io.IOException) CompletionException(java.util.concurrent.CompletionException) UncheckedIOException(java.io.UncheckedIOException)

Example 2 with GraphqlException

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);
}
Also used : GraphQLException(graphql.GraphQLException) KeycloakJWT(doubletap.boopninja.doubletap.Authorizors.Keycloak.KeycloakJWT)

Example 3 with GraphqlException

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;
}
Also used : PlayerInfo(doubletap.boopninja.doubletap.External.Mojang.PlayerInfo) Bukkit.getOfflinePlayer(org.bukkit.Bukkit.getOfflinePlayer) OfflinePlayer(org.bukkit.OfflinePlayer) GraphQLException(graphql.GraphQLException)

Example 4 with GraphqlException

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();
}
Also used : BeforeEach(org.junit.jupiter.api.BeforeEach) GraphQL(graphql.GraphQL) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) HashMap(java.util.HashMap) HTTPRequestHeaders(com.apollographql.federation.graphqljava.tracing.HTTPRequestHeaders) FederatedTracingInstrumentation(com.apollographql.federation.graphqljava.tracing.FederatedTracingInstrumentation) ArrayList(java.util.ArrayList) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) SchemaParser(graphql.schema.idl.SchemaParser) Map(java.util.Map) GraphQLSchema(graphql.schema.GraphQLSchema) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) GraphQLException(graphql.GraphQLException) FEDERATED_TRACING_HEADER_VALUE(com.apollographql.federation.graphqljava.tracing.FederatedTracingInstrumentation.FEDERATED_TRACING_HEADER_VALUE) InvalidProtocolBufferException(com.google.protobuf.InvalidProtocolBufferException) FEDERATED_TRACING_HEADER_NAME(com.apollographql.federation.graphqljava.tracing.FederatedTracingInstrumentation.FEDERATED_TRACING_HEADER_NAME) Options(com.apollographql.federation.graphqljava.tracing.FederatedTracingInstrumentation.Options) TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) ExecutionInput(graphql.ExecutionInput) Test(org.junit.jupiter.api.Test) Base64(java.util.Base64) RuntimeWiring(graphql.schema.idl.RuntimeWiring) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) Reports(mdg.engine.proto.Reports) SchemaGenerator(graphql.schema.idl.SchemaGenerator) TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) ArrayList(java.util.ArrayList) SchemaGenerator(graphql.schema.idl.SchemaGenerator) SchemaParser(graphql.schema.idl.SchemaParser) GraphQLSchema(graphql.schema.GraphQLSchema) RuntimeWiring(graphql.schema.idl.RuntimeWiring) FederatedTracingInstrumentation(com.apollographql.federation.graphqljava.tracing.FederatedTracingInstrumentation) GraphQLException(graphql.GraphQLException) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 5 with GraphqlException

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();
}
Also used : AbortExecutionException(graphql.execution.AbortExecutionException) InstrumentationExecutionStrategyParameters(graphql.execution.instrumentation.parameters.InstrumentationExecutionStrategyParameters) FetchedValue(graphql.execution.FetchedValue) MergedSelectionSet(graphql.execution.MergedSelectionSet) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutionContext(graphql.execution.ExecutionContext) NonNullableFieldValidator(graphql.execution.NonNullableFieldValidator) DataFetcherExceptionHandler(graphql.execution.DataFetcherExceptionHandler) OptionalInt(java.util.OptionalInt) ExecutionStrategyParameters(graphql.execution.ExecutionStrategyParameters) ArrayList(java.util.ArrayList) ExecutionResult(graphql.ExecutionResult) ExecutionStepInfo(graphql.execution.ExecutionStepInfo) Internal(calculator.engine.annotation.Internal) GraphQLError(graphql.GraphQLError) LIST(graphql.execution.FieldValueInfo.CompleteValueType.LIST) InstrumentationFieldCompleteParameters(graphql.execution.instrumentation.parameters.InstrumentationFieldCompleteParameters) BiConsumer(java.util.function.BiConsumer) GraphQLException(graphql.GraphQLException) ExecutionStrategyInstrumentationContext(graphql.execution.instrumentation.ExecutionStrategyInstrumentationContext) ExecutionResultImpl(graphql.ExecutionResultImpl) Async(graphql.execution.Async) NonNullableFieldWasNullException(graphql.execution.NonNullableFieldWasNullException) AbstractAsyncExecutionStrategy(graphql.execution.AbstractAsyncExecutionStrategy) Set(java.util.Set) MergedField(graphql.execution.MergedField) ResultPath(graphql.execution.ResultPath) InstrumentationContext(graphql.execution.instrumentation.InstrumentationContext) List(java.util.List) SimpleDataFetcherExceptionHandler(graphql.execution.SimpleDataFetcherExceptionHandler) ImmutableKit.map(graphql.collect.ImmutableKit.map) Instrumentation(graphql.execution.instrumentation.Instrumentation) FpKit(graphql.util.FpKit) FieldValueInfo(graphql.execution.FieldValueInfo) Collections(java.util.Collections) InstrumentationFieldCompleteParameters(graphql.execution.instrumentation.parameters.InstrumentationFieldCompleteParameters) ArrayList(java.util.ArrayList) Instrumentation(graphql.execution.instrumentation.Instrumentation) ExecutionResult(graphql.ExecutionResult) AbortExecutionException(graphql.execution.AbortExecutionException) OptionalInt(java.util.OptionalInt) FieldValueInfo(graphql.execution.FieldValueInfo) FetchedValue(graphql.execution.FetchedValue) CompletableFuture(java.util.concurrent.CompletableFuture) ExecutionStepInfo(graphql.execution.ExecutionStepInfo) ExecutionResultImpl(graphql.ExecutionResultImpl) ResultPath(graphql.execution.ResultPath) InstrumentationExecutionStrategyParameters(graphql.execution.instrumentation.parameters.InstrumentationExecutionStrategyParameters) ExecutionStrategyParameters(graphql.execution.ExecutionStrategyParameters) NonNullableFieldValidator(graphql.execution.NonNullableFieldValidator) ArrayList(java.util.ArrayList) List(java.util.List)

Aggregations

GraphQLException (graphql.GraphQLException)25 List (java.util.List)7 ExecutionResult (graphql.ExecutionResult)5 Map (java.util.Map)5 ArrayList (java.util.ArrayList)4 HashMap (java.util.HashMap)4 CompletableFuture (java.util.concurrent.CompletableFuture)4 ExecutionResultImpl (graphql.ExecutionResultImpl)3 GraphQL (graphql.GraphQL)3 GraphQLError (graphql.GraphQLError)3 GraphQLSchema (graphql.schema.GraphQLSchema)3 SchemaParser (graphql.schema.idl.SchemaParser)3 TypeDefinitionRegistry (graphql.schema.idl.TypeDefinitionRegistry)3 StargateGraphqlContext (io.stargate.graphql.web.StargateGraphqlContext)3 Set (java.util.Set)3 DataFetcherHelper.parseString (doubletap.boopninja.doubletap.Utils.DataFetcherHelper.parseString)2 ExceptionWhileDataFetching (graphql.ExceptionWhileDataFetching)2 ExecutionInput (graphql.ExecutionInput)2 GraphQLRequest (graphql.kickstart.execution.GraphQLRequest)2 SourceLocation (graphql.language.SourceLocation)2