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());
}
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}
}
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);
}
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();
}
}
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();
}
}
Aggregations