Search in sources :

Example 6 with GraphQL

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

the class BatchCompare method batchedRun.

void batchedRun() {
    System.out.println("=== BatchedExecutionStrategy ===");
    GraphQLSchema schema = buildBatchedSchema();
    GraphQL graphQL = GraphQL.newGraphQL(schema).queryExecutionStrategy(new BatchedExecutionStrategy()).build();
    ExecutionInput executionInput = ExecutionInput.newExecutionInput().query("query { shops { id name departments { id name products { id name } } } }").build();
    ExecutionResult result = graphQL.execute(executionInput);
    System.out.println("\nExecutionResult: " + result.toSpecification());
}
Also used : GraphQL(graphql.GraphQL) ExecutionResult(graphql.ExecutionResult) ExecutionInput(graphql.ExecutionInput) GraphQLSchema(graphql.schema.GraphQLSchema) BatchedExecutionStrategy(graphql.execution.batched.BatchedExecutionStrategy)

Example 7 with GraphQL

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

the class HelloWorld method main.

public static void main(String[] args) {
    String schema = "type Query{hello: String}";
    SchemaParser schemaParser = new SchemaParser();
    TypeDefinitionRegistry typeDefinitionRegistry = schemaParser.parse(schema);
    RuntimeWiring runtimeWiring = newRuntimeWiring().type("Query", builder -> builder.dataFetcher("hello", new StaticDataFetcher("world"))).build();
    SchemaGenerator schemaGenerator = new SchemaGenerator();
    GraphQLSchema graphQLSchema = schemaGenerator.makeExecutableSchema(typeDefinitionRegistry, runtimeWiring);
    GraphQL build = GraphQL.newGraphQL(graphQLSchema).build();
    ExecutionResult executionResult = build.execute("{hello}");
    System.out.println(executionResult.getData().toString());
// Prints: {hello=world}
}
Also used : ExecutionResult(graphql.ExecutionResult) StaticDataFetcher(graphql.schema.StaticDataFetcher) GraphQL(graphql.GraphQL) RuntimeWiring(graphql.schema.idl.RuntimeWiring) SchemaParser(graphql.schema.idl.SchemaParser) RuntimeWiring.newRuntimeWiring(graphql.schema.idl.RuntimeWiring.newRuntimeWiring) GraphQLSchema(graphql.schema.GraphQLSchema) TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) SchemaGenerator(graphql.schema.idl.SchemaGenerator) RuntimeWiring(graphql.schema.idl.RuntimeWiring) RuntimeWiring.newRuntimeWiring(graphql.schema.idl.RuntimeWiring.newRuntimeWiring) GraphQL(graphql.GraphQL) TypeDefinitionRegistry(graphql.schema.idl.TypeDefinitionRegistry) SchemaGenerator(graphql.schema.idl.SchemaGenerator) StaticDataFetcher(graphql.schema.StaticDataFetcher) ExecutionResult(graphql.ExecutionResult) SchemaParser(graphql.schema.idl.SchemaParser) GraphQLSchema(graphql.schema.GraphQLSchema)

Example 8 with GraphQL

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

the class HttpMain method handleStarWars.

private void handleStarWars(HttpServletRequest httpRequest, HttpServletResponse httpResponse) throws IOException {
    // 
    // this builds out the parameters we need like the graphql query from the http request
    QueryParameters parameters = QueryParameters.from(httpRequest);
    if (parameters.getQuery() == null) {
        // 
        // how to handle nonsensical requests is up to your application
        httpResponse.setStatus(400);
        return;
    }
    ExecutionInput.Builder executionInput = newExecutionInput().query(parameters.getQuery()).operationName(parameters.getOperationName()).variables(parameters.getVariables());
    // 
    // This example uses the DataLoader technique to ensure that the most efficient
    // loading of data (in this case StarWars characters) happens.  We pass that to data
    // fetchers via the graphql context object.
    // 
    DataLoaderRegistry dataLoaderRegistry = buildDataLoaderRegistry();
    // 
    // the context object is something that means something to down stream code.  It is instructions
    // from yourself to your other code such as DataFetchers.  The engine passes this on unchanged and
    // makes it available to inner code
    // 
    // the graphql guidance says  :
    // 
    // - GraphQL should be placed after all authentication middleware, so that you
    // - have access to the same session and user information you would in your
    // - HTTP endpoint handlers.
    // 
    Map<String, Object> context = new HashMap<>();
    context.put("YouAppSecurityClearanceLevel", "CodeRed");
    context.put("YouAppExecutingUser", "Dr Nefarious");
    context.put("dataloaderRegistry", dataLoaderRegistry);
    executionInput.context(context);
    // 
    // you need a schema in order to execute queries
    GraphQLSchema schema = buildStarWarsSchema();
    DataLoaderDispatcherInstrumentation dlInstrumentation = new DataLoaderDispatcherInstrumentation(dataLoaderRegistry, newOptions().includeStatistics(true));
    Instrumentation instrumentation = new ChainedInstrumentation(asList(new TracingInstrumentation(), dlInstrumentation));
    // finally you build a runtime graphql object and execute the query
    GraphQL graphQL = GraphQL.newGraphQL(schema).instrumentation(instrumentation).build();
    ExecutionResult executionResult = graphQL.execute(executionInput.build());
    returnAsJson(httpResponse, executionResult);
}
Also used : ChainedInstrumentation(graphql.execution.instrumentation.ChainedInstrumentation) HashMap(java.util.HashMap) GraphQL(graphql.GraphQL) DataLoaderDispatcherInstrumentation(graphql.execution.instrumentation.dataloader.DataLoaderDispatcherInstrumentation) DataLoaderDispatcherInstrumentation(graphql.execution.instrumentation.dataloader.DataLoaderDispatcherInstrumentation) TracingInstrumentation(graphql.execution.instrumentation.tracing.TracingInstrumentation) ChainedInstrumentation(graphql.execution.instrumentation.ChainedInstrumentation) Instrumentation(graphql.execution.instrumentation.Instrumentation) ExecutionResult(graphql.ExecutionResult) GraphQLSchema(graphql.schema.GraphQLSchema) TracingInstrumentation(graphql.execution.instrumentation.tracing.TracingInstrumentation) DataLoaderRegistry(org.dataloader.DataLoaderRegistry) ExecutionInput.newExecutionInput(graphql.ExecutionInput.newExecutionInput) ExecutionInput(graphql.ExecutionInput)

Example 9 with GraphQL

use of graphql.GraphQL in project timbuctoo by HuygensING.

the class GraphQl method executeGraphql.

public Response executeGraphql(String query, String acceptHeader, String acceptParam, String queryFromBody, Map variables, String operationName, String authHeader) {
    final SerializerWriter serializerWriter;
    if (acceptParam != null && !acceptParam.isEmpty()) {
        // Accept param overrules header because it's more under the user's control
        acceptHeader = acceptParam;
    }
    if (unSpecifiedAcceptHeader(acceptHeader)) {
        acceptHeader = MediaType.APPLICATION_JSON;
    }
    if (MediaType.APPLICATION_JSON.equals(acceptHeader)) {
        serializerWriter = null;
    } else {
        Optional<SerializerWriter> bestMatch = serializerWriterRegistry.getBestMatch(acceptHeader);
        if (bestMatch.isPresent()) {
            serializerWriter = bestMatch.get();
        } else {
            return Response.status(415).type(MediaType.APPLICATION_JSON_TYPE).entity("{\"errors\": [\"The available mediatypes are: " + String.join(", ", serializerWriterRegistry.getSupportedMimeTypes()) + "\"]}").build();
        }
    }
    if (query != null && queryFromBody != null) {
        return Response.status(400).type(MediaType.APPLICATION_JSON_TYPE).entity("{\"errors\": [\"There's both a query as url paramatere and a query in the body. Please pick one.\"]}").build();
    }
    if (query == null && queryFromBody == null) {
        return Response.status(400).type(MediaType.APPLICATION_JSON_TYPE).entity("{\"errors\": [\"Please provide the graphql query as the query property of a JSON encoded object. " + "E.g. {query: \\\"{\\n  persons {\\n ... \\\"}\"]}").build();
    }
    Optional<User> user;
    try {
        user = userValidator.getUserFromAccessToken(authHeader);
    } catch (UserValidationException e) {
        user = Optional.empty();
    }
    UserPermissionCheck userPermissionCheck = new UserPermissionCheck(user, permissionFetcher, newHashSet(Permission.READ));
    final GraphQLSchema transform = graphqlGetter.get().transform(b -> b.fieldVisibility(new PermissionBasedFieldVisibility(userPermissionCheck, dataSetRepository)));
    final GraphQL.Builder builder = GraphQL.newGraphQL(transform);
    if (serializerWriter != null) {
        builder.queryExecutionStrategy(new SerializerExecutionStrategy());
    }
    GraphQL graphQl = builder.build();
    final ExecutionResult result = graphQl.execute(newExecutionInput().root(new RootData(user)).context(contextData(userPermissionCheck, user)).query(queryFromBody).operationName(operationName).variables(variables == null ? Collections.emptyMap() : variables).build());
    if (serializerWriter == null) {
        return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(result.toSpecification()).build();
    } else {
        if (result.getErrors() != null && !result.getErrors().isEmpty()) {
            return Response.status(415).type(MediaType.APPLICATION_JSON_TYPE).entity(result.toSpecification()).build();
        }
        return Response.ok().type(serializerWriter.getMimeType()).entity((StreamingOutput) os -> {
            serializerWriter.getSerializationFactory().create(os).serialize(new SerializableResult(result.getData()));
        }).build();
    }
}
Also used : UserValidationException(nl.knaw.huygens.timbuctoo.v5.security.exceptions.UserValidationException) User(nl.knaw.huygens.timbuctoo.v5.security.dto.User) GraphQL(graphql.GraphQL) SerializableResult(nl.knaw.huygens.timbuctoo.v5.serializable.SerializableResult) SerializerWriter(nl.knaw.huygens.timbuctoo.v5.dropwizard.contenttypes.SerializerWriter) ExecutionResult(graphql.ExecutionResult) StreamingOutput(javax.ws.rs.core.StreamingOutput) GraphQLSchema(graphql.schema.GraphQLSchema) RootData(nl.knaw.huygens.timbuctoo.v5.graphql.datafetchers.dto.RootData) PermissionBasedFieldVisibility(nl.knaw.huygens.timbuctoo.v5.graphql.security.PermissionBasedFieldVisibility) SerializerExecutionStrategy(nl.knaw.huygens.timbuctoo.v5.graphql.serializable.SerializerExecutionStrategy) UserPermissionCheck(nl.knaw.huygens.timbuctoo.v5.graphql.security.UserPermissionCheck)

Example 10 with GraphQL

use of graphql.GraphQL in project structr by structr.

the class GraphQLWriter method stream.

public void stream(final SecurityContext securityContext, final Writer output, final GraphQLRequest request) throws IOException, FrameworkException {
    final RestWriter writer = new StructrJsonWriter(securityContext, output);
    if (indent) {
        writer.setIndent("	");
    }
    if (request.hasSchemaQuery()) {
        // schema query is serialized from GraphQL execution result, doesn't need enclosing JSON object
        for (final GraphQLQuery query : request.getQueries()) {
            if (query.isSchemaQuery()) {
                // use graphql-java schema response
                final String originalQuery = request.getOriginalQuery();
                final GraphQL graphQL = GraphQL.newGraphQL(SchemaService.getGraphQLSchema()).build();
                final ExecutionResult result = graphQL.execute(originalQuery);
                final Gson gson = new GsonBuilder().setPrettyPrinting().create();
                if (result != null) {
                    final Map<String, Object> data = result.getData();
                    if (data != null) {
                        gson.toJson(data, output);
                    }
                }
            }
        }
    } else {
        writer.beginDocument(null, null);
        writer.beginObject();
        for (final GraphQLQuery query : request.getQueries()) {
            if (query.isSchemaQuery()) {
                // use graphql-java schema response
                final String originalQuery = request.getOriginalQuery();
                final GraphQL graphQL = GraphQL.newGraphQL(SchemaService.getGraphQLSchema()).build();
                final ExecutionResult result = graphQL.execute(originalQuery);
                final Gson gson = new GsonBuilder().setPrettyPrinting().create();
                if (result != null) {
                    final Map<String, Object> data = result.getData();
                    if (data != null) {
                        gson.toJson(data, output);
                    }
                }
            } else {
                writer.name(query.getFieldName());
                writer.beginArray();
                for (final GraphObject object : query.getEntities(securityContext)) {
                    root.serialize(writer, null, object, query, query.getRootPath());
                }
                writer.endArray();
            }
        }
        // finished
        writer.endObject();
        writer.endDocument();
    }
}
Also used : GsonBuilder(com.google.gson.GsonBuilder) GraphQL(graphql.GraphQL) Gson(com.google.gson.Gson) ExecutionResult(graphql.ExecutionResult) GraphObject(org.structr.core.GraphObject) GraphObject(org.structr.core.GraphObject) GraphQLQuery(org.structr.core.graphql.GraphQLQuery)

Aggregations

GraphQL (graphql.GraphQL)25 ExecutionResult (graphql.ExecutionResult)18 GraphQLSchema (graphql.schema.GraphQLSchema)13 ExecutionInput (graphql.ExecutionInput)6 RuntimeWiring (graphql.schema.idl.RuntimeWiring)5 RuntimeWiring.newRuntimeWiring (graphql.schema.idl.RuntimeWiring.newRuntimeWiring)5 SchemaGenerator (graphql.schema.idl.SchemaGenerator)5 SchemaParser (graphql.schema.idl.SchemaParser)5 TypeDefinitionRegistry (graphql.schema.idl.TypeDefinitionRegistry)5 GraphQLError (graphql.GraphQLError)4 DataFetchingEnvironment (graphql.schema.DataFetchingEnvironment)4 List (java.util.List)4 DataLoaderRegistry (org.dataloader.DataLoaderRegistry)4 DataLoaderDispatcherInstrumentation (graphql.execution.instrumentation.dataloader.DataLoaderDispatcherInstrumentation)3 ArrayList (java.util.ArrayList)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 ExecutorServiceExecutionStrategy (graphql.execution.ExecutorServiceExecutionStrategy)2