use of graphql.GraphQL in project carbon-apimgt by wso2.
the class QueryAnalyzer method analyseQueryComplexity.
/**
* This method analyses the query complexity.
*
* @param fieldComplexityCalculator Field Complexity Calculator
* @param maxQueryComplexity Maximum query complexity value
* @param payload payload of the request
* @return true, if query complexity does not exceed the maximum or false, if query complexity exceeds the maximum
*/
public QueryAnalyzerResponseDTO analyseQueryComplexity(int maxQueryComplexity, String payload, FieldComplexityCalculator fieldComplexityCalculator) {
if (log.isDebugEnabled()) {
log.debug("Analyzing query complexity for " + payload + " and max complexity: " + maxQueryComplexity);
}
QueryAnalyzerResponseDTO queryAnalyzerResponseDTO = new QueryAnalyzerResponseDTO();
// Otherwise, bypass the check.
if (maxQueryComplexity > 0) {
MaxQueryComplexityInstrumentation maxQueryComplexityInstrumentation = new MaxQueryComplexityInstrumentation(maxQueryComplexity, fieldComplexityCalculator);
GraphQL runtime = GraphQL.newGraphQL(schema).instrumentation(maxQueryComplexityInstrumentation).build();
ExecutionResult executionResult = runtime.execute(payload);
List<GraphQLError> errors = executionResult.getErrors();
if (errors.size() > 0) {
for (GraphQLError error : errors) {
queryAnalyzerResponseDTO.addErrorToList((error.getMessage()));
}
// TODO: https://github.com/wso2/carbon-apimgt/issues/8147
queryAnalyzerResponseDTO.getErrorList().removeIf(s -> s.contains("non-nullable"));
if (queryAnalyzerResponseDTO.getErrorList().size() == 0) {
if (log.isDebugEnabled()) {
log.debug("Maximum query complexity was not exceeded");
}
queryAnalyzerResponseDTO.setSuccess(true);
} else {
log.error(queryAnalyzerResponseDTO.getErrorList());
queryAnalyzerResponseDTO.getErrorList().clear();
queryAnalyzerResponseDTO.addErrorToList("maximum query complexity exceeded");
}
queryAnalyzerResponseDTO.setSuccess(false);
return queryAnalyzerResponseDTO;
}
}
queryAnalyzerResponseDTO.setSuccess(true);
return queryAnalyzerResponseDTO;
}
use of graphql.GraphQL in project engine by craftercms.
the class SiteGraphQLController method handleRequest.
protected Map<String, Object> handleRequest(String query, String operationName, Map<String, Object> variables) {
SiteContext siteContext = SiteContext.getCurrent();
RequestContext requestContext = RequestContext.getCurrent();
GraphQL graphQL = siteContext.getGraphQL();
if (Objects.isNull(graphQL)) {
logger.warn("GraphQL schema has not been initialized for site {}", siteContext.getSiteName());
return Collections.singletonMap("errors", Collections.singletonList(Collections.singletonMap("message", "GraphQL schema has not been initialized for site " + siteContext.getSiteName())));
}
ExecutionInput.Builder executionInput = newExecutionInput().query(query).operationName(operationName).variables(variables).context(requestContext);
StopWatch watch = new StopWatch("graphql - " + operationName);
watch.start("query");
ExecutionResult result = graphQL.execute(executionInput);
watch.stop();
if (logger.isTraceEnabled()) {
logger.trace(watch.prettyPrint());
}
return result.toSpecification();
}
use of graphql.GraphQL in project graphql-java by graphql-java.
the class BatchingExamples method starWarsExample.
void starWarsExample() {
// a batch loader function that will be called with N or more keys for batch loading
BatchLoader<String, Object> characterBatchLoader = new BatchLoader<String, Object>() {
@Override
public CompletionStage<List<Object>> load(List<String> keys) {
//
return CompletableFuture.supplyAsync(() -> getCharacterDataViaBatchHTTPApi(keys));
}
};
// a data loader for characters that points to the character batch loader
DataLoader<String, Object> characterDataLoader = new DataLoader<>(characterBatchLoader);
//
// use this data loader in the data fetchers associated with characters and put them into
// the graphql schema (not shown)
//
DataFetcher heroDataFetcher = new DataFetcher() {
@Override
public Object get(DataFetchingEnvironment environment) {
// R2D2
return characterDataLoader.load("2001");
}
};
DataFetcher friendsDataFetcher = new DataFetcher() {
@Override
public Object get(DataFetchingEnvironment environment) {
StarWarsCharacter starWarsCharacter = environment.getSource();
List<String> friendIds = starWarsCharacter.getFriendIds();
return characterDataLoader.loadMany(friendIds);
}
};
//
// DataLoaderRegistry is a place to register all data loaders in that needs to be dispatched together
// in this case there is 1 but you can have many
//
DataLoaderRegistry registry = new DataLoaderRegistry();
registry.register("character", characterDataLoader);
//
// this instrumentation implementation will dispatched all the dataloaders
// as each level fo the graphql query is executed and hence make batched objects
// available to the query and the associated DataFetchers
//
DataLoaderDispatcherInstrumentation dispatcherInstrumentation = new DataLoaderDispatcherInstrumentation(registry);
//
// now build your graphql object and execute queries on it.
// the data loader will be invoked via the data fetchers on the
// schema fields
//
GraphQL graphQL = GraphQL.newGraphQL(buildSchema()).instrumentation(dispatcherInstrumentation).build();
}
use of graphql.GraphQL in project graphql-java by graphql-java.
the class ExecutionExamples method simpleAsyncQueryExecution.
@SuppressWarnings("Convert2MethodRef")
private void simpleAsyncQueryExecution() throws Exception {
GraphQL graphQL = buildSchema();
ExecutionInput executionInput = ExecutionInput.newExecutionInput().query("query { hero { name } }").build();
CompletableFuture<ExecutionResult> promise = graphQL.executeAsync(executionInput);
promise.thenAccept(executionResult -> {
// here you might send back the results as JSON over HTTP
encodeResultToJsonAndSendResponse(executionResult);
});
promise.join();
}
use of graphql.GraphQL in project graphql-java by graphql-java.
the class ReadmeExamples method executionStrategies.
void executionStrategies() {
ThreadPoolExecutor threadPoolExecutor = 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(threadPoolExecutor)).mutationExecutionStrategy(new AsyncExecutionStrategy()).subscriptionExecutionStrategy(new AsyncExecutionStrategy()).build();
}
Aggregations