Search in sources :

Example 1 with GraphQL

use of graphql.GraphQL in project admin-console-beta by connexta.

the class GraphQLServlet method query.

private void query(String query, String operationName, Map<String, Object> variables, GraphQLSchema schema, HttpServletRequest req, HttpServletResponse resp, GraphQLContext context) throws IOException {
    if (Subject.getSubject(AccessController.getContext()) == null && context.getSubject().isPresent()) {
        Subject.doAs(context.getSubject().get(), new PrivilegedAction<Void>() {

            @Override
            @SneakyThrows
            public Void run() {
                query(query, operationName, variables, schema, req, resp, context);
                return null;
            }
        });
    } else {
        runListeners(operationListeners, l -> runListener(l, it -> it.beforeGraphQLOperation(context, operationName, query, variables)));
        ExecutionResult executionResult = new GraphQL(schema, getQueryExecutionStrategy(), getMutationExecutionStrategy()).execute(query, operationName, context, transformVariables(schema, query, variables));
        List<GraphQLError> errors = executionResult.getErrors();
        Object data = executionResult.getData();
        String response = mapper.writeValueAsString(createResultFromDataAndErrors(data, errors));
        resp.setContentType(APPLICATION_JSON_UTF8);
        resp.setStatus(STATUS_OK);
        resp.getWriter().write(response);
        if (errorsPresent(errors)) {
            runListeners(operationListeners, l -> l.onFailedGraphQLOperation(context, operationName, query, variables, data, errors));
        } else {
            runListeners(operationListeners, l -> l.onSuccessfulGraphQLOperation(context, operationName, query, variables, data));
        }
    }
}
Also used : InvalidSyntaxError(graphql.InvalidSyntaxError) Setter(lombok.Setter) GraphQL(graphql.GraphQL) ExecutionStrategy(graphql.execution.ExecutionStrategy) Getter(lombok.Getter) SneakyThrows(lombok.SneakyThrows) ServletException(javax.servlet.ServletException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) GraphQLFieldDefinition(graphql.schema.GraphQLFieldDefinition) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ExecutionResult(graphql.ExecutionResult) HttpServletRequest(javax.servlet.http.HttpServletRequest) CharStreams(com.google.common.io.CharStreams) GraphQLError(graphql.GraphQLError) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) GraphQLSchema(graphql.schema.GraphQLSchema) TypeReference(com.fasterxml.jackson.core.type.TypeReference) JsonDeserializer(com.fasterxml.jackson.databind.JsonDeserializer) RuntimeJsonMappingException(com.fasterxml.jackson.databind.RuntimeJsonMappingException) DeserializationContext(com.fasterxml.jackson.databind.DeserializationContext) JsonParser(com.fasterxml.jackson.core.JsonParser) HttpServlet(javax.servlet.http.HttpServlet) Servlet(javax.servlet.Servlet) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) PrivilegedAction(java.security.PrivilegedAction) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) Subject(javax.security.auth.Subject) Consumer(java.util.function.Consumer) ValidationError(graphql.validation.ValidationError) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Part(javax.servlet.http.Part) Optional(java.util.Optional) AccessController(java.security.AccessController) JsonDeserialize(com.fasterxml.jackson.databind.annotation.JsonDeserialize) InputStream(java.io.InputStream) GraphQL(graphql.GraphQL) SneakyThrows(lombok.SneakyThrows) GraphQLError(graphql.GraphQLError) ExecutionResult(graphql.ExecutionResult)

Example 2 with GraphQL

use of graphql.GraphQL in project graphql-java by graphql-java.

the class BatchingExamples method perRequestGraphQl.

private void perRequestGraphQl() {
    GraphQLSchema staticSchema = staticSchema_Or_MayBeFrom_IoC_Injection();
    DataLoaderRegistry registry = new DataLoaderRegistry();
    registry.register("character", getCharacterDataLoader());
    DataLoaderDispatcherInstrumentation dispatcherInstrumentation = new DataLoaderDispatcherInstrumentation(registry);
    GraphQL graphQL = GraphQL.newGraphQL(staticSchema).instrumentation(dispatcherInstrumentation).build();
    graphQL.execute("{ helloworld }");
// you can now throw away the GraphQL and hence DataLoaderDispatcherInstrumentation
// and DataLoaderRegistry objects since they are really cheap to build per request
}
Also used : DataLoaderRegistry(org.dataloader.DataLoaderRegistry) GraphQL(graphql.GraphQL) DataLoaderDispatcherInstrumentation(graphql.execution.instrumentation.dataloader.DataLoaderDispatcherInstrumentation) GraphQLSchema(graphql.schema.GraphQLSchema)

Example 3 with GraphQL

use of graphql.GraphQL in project graphql-java by graphql-java.

the class DeferredExamples method basicExample.

void basicExample(HttpServletResponse httpServletResponse, String deferredQuery) {
    GraphQLSchema schema = buildSchemaWithDirective();
    GraphQL graphQL = GraphQL.newGraphQL(schema).build();
    // 
    // deferredQuery contains the query with @defer directives in it
    // 
    ExecutionResult initialResult = graphQL.execute(ExecutionInput.newExecutionInput().query(deferredQuery).build());
    // 
    // then initial results happen first, the deferred ones will begin AFTER these initial
    // results have completed
    // 
    sendResult(httpServletResponse, initialResult);
    Map<Object, Object> extensions = initialResult.getExtensions();
    Publisher<ExecutionResult> deferredResults = (Publisher<ExecutionResult>) extensions.get(GraphQL.DEFERRED_RESULTS);
    // 
    // you subscribe to the deferred results like any other reactive stream
    // 
    deferredResults.subscribe(new Subscriber<ExecutionResult>() {

        Subscription subscription;

        @Override
        public void onSubscribe(Subscription s) {
            subscription = s;
            // 
            // how many you request is up to you
            subscription.request(10);
        }

        @Override
        public void onNext(ExecutionResult executionResult) {
            // 
            // as each deferred result arrives, send it to where it needs to go
            // 
            sendResult(httpServletResponse, executionResult);
            subscription.request(10);
        }

        @Override
        public void onError(Throwable t) {
            handleError(httpServletResponse, t);
        }

        @Override
        public void onComplete() {
            completeResponse(httpServletResponse);
        }
    });
}
Also used : GraphQL(graphql.GraphQL) ExecutionResult(graphql.ExecutionResult) Publisher(org.reactivestreams.Publisher) Subscription(org.reactivestreams.Subscription) GraphQLSchema(graphql.schema.GraphQLSchema)

Example 4 with GraphQL

use of graphql.GraphQL in project graphql-java by graphql-java.

the class ExecutionExamples method exampleExecutorServiceExecutionStrategy.

private void exampleExecutorServiceExecutionStrategy() {
    ExecutorService executorService = new ThreadPoolExecutor(2, /* core pool size 2 thread */
    2, /* max pool size 2 thread */
    30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new ThreadPoolExecutor.CallerRunsPolicy());
    GraphQL graphQL = GraphQL.newGraphQL(StarWarsSchema.starWarsSchema).queryExecutionStrategy(new ExecutorServiceExecutionStrategy(executorService)).mutationExecutionStrategy(new AsyncSerialExecutionStrategy()).build();
}
Also used : GraphQL(graphql.GraphQL) ExecutorService(java.util.concurrent.ExecutorService) ExecutorServiceExecutionStrategy(graphql.execution.ExecutorServiceExecutionStrategy) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) AsyncSerialExecutionStrategy(graphql.execution.AsyncSerialExecutionStrategy)

Example 5 with GraphQL

use of graphql.GraphQL in project graphql-java by graphql-java.

the class ExecutionExamples method simpleQueryExecution.

private void simpleQueryExecution() throws Exception {
    GraphQLSchema schema = GraphQLSchema.newSchema().query(queryType).build();
    GraphQL graphQL = GraphQL.newGraphQL(schema).build();
    ExecutionInput executionInput = ExecutionInput.newExecutionInput().query("query { hero { name } }").build();
    ExecutionResult executionResult = graphQL.execute(executionInput);
    Object data = executionResult.getData();
    List<GraphQLError> errors = executionResult.getErrors();
}
Also used : GraphQL(graphql.GraphQL) GraphQLError(graphql.GraphQLError) ExecutionResult(graphql.ExecutionResult) ExecutionInput(graphql.ExecutionInput) GraphQLSchema(graphql.schema.GraphQLSchema)

Aggregations

GraphQL (graphql.GraphQL)21 ExecutionResult (graphql.ExecutionResult)16 GraphQLSchema (graphql.schema.GraphQLSchema)11 ExecutionInput (graphql.ExecutionInput)6 DataLoaderRegistry (org.dataloader.DataLoaderRegistry)4 DataLoaderDispatcherInstrumentation (graphql.execution.instrumentation.dataloader.DataLoaderDispatcherInstrumentation)3 RuntimeWiring (graphql.schema.idl.RuntimeWiring)3 RuntimeWiring.newRuntimeWiring (graphql.schema.idl.RuntimeWiring.newRuntimeWiring)3 SchemaGenerator (graphql.schema.idl.SchemaGenerator)3 SchemaParser (graphql.schema.idl.SchemaParser)3 TypeDefinitionRegistry (graphql.schema.idl.TypeDefinitionRegistry)3 HashMap (java.util.HashMap)3 TypeReference (com.fasterxml.jackson.core.type.TypeReference)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ExecutionInput.newExecutionInput (graphql.ExecutionInput.newExecutionInput)2 GraphQLError (graphql.GraphQLError)2 ExecutorServiceExecutionStrategy (graphql.execution.ExecutorServiceExecutionStrategy)2 DataFetcher (graphql.schema.DataFetcher)2 StaticDataFetcher (graphql.schema.StaticDataFetcher)2 IOException (java.io.IOException)2