use of graphql.ExecutionResult in project graphql-java by graphql-java.
the class AsyncSerialExecutionStrategy method execute.
@Override
public CompletableFuture<ExecutionResult> execute(ExecutionContext executionContext, ExecutionStrategyParameters parameters) throws NonNullableFieldWasNullException {
Instrumentation instrumentation = executionContext.getInstrumentation();
InstrumentationExecutionStrategyParameters instrumentationParameters = new InstrumentationExecutionStrategyParameters(executionContext, parameters);
InstrumentationContext<ExecutionResult> executionStrategyCtx = instrumentation.beginExecutionStrategy(instrumentationParameters);
Map<String, List<Field>> fields = parameters.getFields();
List<String> fieldNames = new ArrayList<>(fields.keySet());
CompletableFuture<List<ExecutionResult>> resultsFuture = Async.eachSequentially(fieldNames, (fieldName, index, prevResults) -> {
List<Field> currentField = fields.get(fieldName);
ExecutionPath fieldPath = parameters.getPath().segment(fieldName);
ExecutionStrategyParameters newParameters = parameters.transform(builder -> builder.field(currentField).path(fieldPath));
return resolveField(executionContext, newParameters);
});
CompletableFuture<ExecutionResult> overallResult = new CompletableFuture<>();
executionStrategyCtx.onDispatched(overallResult);
resultsFuture.whenComplete(handleResults(executionContext, fieldNames, overallResult));
overallResult.whenComplete(executionStrategyCtx::onCompleted);
return overallResult;
}
use of graphql.ExecutionResult in project incubator-skywalking by apache.
the class GraphQLHandler method execute.
private JsonObject execute(String request, Map<String, Object> variables) {
try {
ExecutionInput executionInput = ExecutionInput.newExecutionInput().query(request).variables(variables).build();
ExecutionResult executionResult = graphQL.execute(executionInput);
logger.info("Execution result is {}", executionResult);
Object data = executionResult.getData();
List<GraphQLError> errors = executionResult.getErrors();
JsonObject jsonObject = new JsonObject();
if (data != null) {
jsonObject.add(DATA, gson.fromJson(gson.toJson(data), JsonObject.class));
}
if (CollectionUtils.isNotEmpty(errors)) {
JsonArray errorArray = new JsonArray();
errors.forEach(error -> {
JsonObject errorJson = new JsonObject();
errorJson.addProperty(MESSAGE, error.getMessage());
errorArray.add(errorJson);
});
jsonObject.add(ERRORS, errorArray);
}
return jsonObject;
} catch (Throwable e) {
logger.error(e.getMessage(), e);
JsonObject jsonObject = new JsonObject();
JsonArray errorArray = new JsonArray();
JsonObject errorJson = new JsonObject();
errorJson.addProperty(MESSAGE, e.getMessage());
errorArray.add(errorJson);
jsonObject.add(ERRORS, errorArray);
return jsonObject;
}
}
use of graphql.ExecutionResult 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.ExecutionResult 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();
}
}
use of graphql.ExecutionResult in project nextprot-api by calipho-sib.
the class GraphQLTest method main.
public static void main(String[] args) {
String schema = "type Query{hello: String} schema{query: Query}";
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}
}
Aggregations