graphql.execution.instrumentation.Instrumentation Java Examples

The following examples show how to use graphql.execution.instrumentation.Instrumentation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GraphQLProvider.java    From graphql-java-examples with MIT License 6 votes vote down vote up
@PostConstruct
public void init() throws IOException {
    URL url = Resources.getResource("starWarsSchemaAnnotated.graphqls");
    String sdl = Resources.toString(url, Charsets.UTF_8);
    GraphQLSchema graphQLSchema = buildSchema(sdl);

    //
    // 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.
    //
    DataLoaderDispatcherInstrumentation dlInstrumentation =
            new DataLoaderDispatcherInstrumentation(dataLoaderRegistry, newOptions().includeStatistics(true));

    Instrumentation instrumentation = new ChainedInstrumentation(
            asList(new TracingInstrumentation(), dlInstrumentation)
    );


    this.graphQL = GraphQL.newGraphQL(graphQLSchema).instrumentation(instrumentation).build();
}
 
Example #2
Source File: Util.java    From rsocket-rpc-java with Apache License 2.0 6 votes vote down vote up
static CompletableFuture<ExecutionResult> executeGraphQLRequest(
    GraphQLRequest request,
    ByteBuf byteBuf,
    DataLoaderRegistry registry,
    GraphQLSchema graphQLSchema,
    Instrumentation instrumentation) {
  ExecutionInput.Builder builder =
      ExecutionInput.newExecutionInput()
          .query(request.getQuery())
          .operationName(request.getOperationName())
          .variables(request.getVariables())
          .context(byteBuf)
          .executionId(ExecutionId.generate());

  if (registry != null) {
    builder.dataLoaderRegistry(registry);
  }

  ExecutionInput executionInput = builder.build();

  return GraphQL.newGraphQL(graphQLSchema)
      .instrumentation(instrumentation)
      .build()
      .executeAsync(executionInput);
}
 
Example #3
Source File: FuturesConverter.java    From rejoiner with Apache License 2.0 6 votes vote down vote up
public static Instrumentation apiFutureInstrumentation() {
  return new SimpleInstrumentation() {
    @Override
    public DataFetcher<?> instrumentDataFetcher(
        DataFetcher<?> dataFetcher, InstrumentationFieldFetchParameters parameters) {
      return (DataFetcher<Object>)
          dataFetchingEnvironment -> {
            Object data = dataFetcher.get(dataFetchingEnvironment);
            if (data instanceof ApiFuture) {
              return FutureConverter.toCompletableFuture(
                  apiFutureToListenableFuture((ApiFuture<?>) data));
            }
            return data;
          };
    }
  };
}
 
Example #4
Source File: GraphQLProvider.java    From graphql-java-examples with MIT License 5 votes vote down vote up
@PostConstruct
public void init() throws IOException {
    URL url = Resources.getResource("starWarsSchemaAnnotated.graphqls");
    String sdl = Resources.toString(url, Charsets.UTF_8);
    GraphQLSchema graphQLSchema = buildSchema(sdl);

    Instrumentation instrumentation = new TracingInstrumentation();

    this.graphQL = GraphQL.newGraphQL(graphQLSchema).instrumentation(instrumentation).build();
}
 
Example #5
Source File: GraphQlServlet.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

  DataLoaderRegistry dataLoaderRegistry = registryProvider.get();
  Instrumentation instrumentation =
      new ChainedInstrumentation(
          Arrays.asList(
              GuavaListenableFutureSupport.listenableFutureInstrumentation(),
              new TracingInstrumentation()));
  GraphQL graphql = GraphQL.newGraphQL(schema).instrumentation(instrumentation).build();

  Map<String, Object> json = readJson(req);
  String query = (String) json.get("query");
  if (query == null) {
    resp.setStatus(400);
    return;
  }
  String operationName = (String) json.get("operationName");
  Map<String, Object> variables = getVariables(json.get("variables"));

  ExecutionInput executionInput =
      ExecutionInput.newExecutionInput()
          .query(query)
          .operationName(operationName)
          .variables(variables)
          .dataLoaderRegistry(dataLoaderRegistry)
          .context(dataLoaderRegistry)
          .build();
  ExecutionResult executionResult = graphql.execute(executionInput);
  resp.setContentType("application/json");
  resp.setStatus(HttpServletResponse.SC_OK);
  GSON.toJson(executionResult.toSpecification(), resp.getWriter());
  logger.info("stats: " + dataLoaderRegistry.getStatistics());
}
 
Example #6
Source File: GuavaListenableFutureSupport.java    From rejoiner with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a {@link ListenableFuture} to a Java8 {@link java.util.concurrent.CompletableFuture}.
 *
 * <p>{@see CompletableFuture} is supported by the provided {@link
 * graphql.execution.AsyncExecutionStrategy}.
 *
 * <p>Note: This should be installed before any other instrumentation.
 */
public static Instrumentation listenableFutureInstrumentation(Executor executor) {
  return new SimpleInstrumentation() {
    @Override
    public DataFetcher<?> instrumentDataFetcher(
        DataFetcher<?> dataFetcher, InstrumentationFieldFetchParameters parameters) {
      return (DataFetcher<Object>)
          dataFetchingEnvironment -> {
            Object data = dataFetcher.get(dataFetchingEnvironment);
            if (data instanceof ListenableFuture) {
              ListenableFuture<Object> listenableFuture = (ListenableFuture<Object>) data;
              CompletableFuture<Object> completableFuture = new CompletableFuture<>();
              Futures.addCallback(
                  listenableFuture,
                  new FutureCallback<Object>() {
                    @Override
                    public void onSuccess(Object result) {
                      completableFuture.complete(result);
                    }

                    @Override
                    public void onFailure(Throwable t) {
                      completableFuture.completeExceptionally(t);
                    }
                  },
                  executor);
              return completableFuture;
            }
            return data;
          };
    }
  };
}
 
Example #7
Source File: App.java    From federation-jvm with MIT License 4 votes vote down vote up
@Bean
public Instrumentation addFederatedTracing() {
    return new FederatedTracingInstrumentation(new FederatedTracingInstrumentation.Options(true));
}
 
Example #8
Source File: GraphQLServerRequestStream.java    From rsocket-rpc-java with Apache License 2.0 4 votes vote down vote up
GraphQLServerRequestStream(
    DataLoaderRegistry registry, Instrumentation instrumentation, GraphQLSchema graphQLSchema) {
  this.registry = registry;
  this.instrumentation = instrumentation;
  this.graphQLSchema = graphQLSchema;
}
 
Example #9
Source File: GraphQLServerRequestResponse.java    From rsocket-rpc-java with Apache License 2.0 4 votes vote down vote up
GraphQLServerRequestResponse(
    DataLoaderRegistry registry, Instrumentation instrumentation, GraphQLSchema graphQLSchema) {
  this.registry = registry;
  this.instrumentation = instrumentation;
  this.graphQLSchema = graphQLSchema;
}
 
Example #10
Source File: StockTickerWebSocket.java    From graphql-java-subscription-example with MIT License 4 votes vote down vote up
@Override
public void onWebSocketText(String graphqlQuery) {
    log.info("Websocket said {}", graphqlQuery);

    QueryParameters parameters = QueryParameters.from(graphqlQuery);

    ExecutionInput executionInput = ExecutionInput.newExecutionInput()
            .query(parameters.getQuery())
            .variables(parameters.getVariables())
            .operationName(parameters.getOperationName())
            .build();

    Instrumentation instrumentation = new ChainedInstrumentation(
            singletonList(new TracingInstrumentation())
    );

    //
    // In order to have subscriptions in graphql-java you MUST use the
    // SubscriptionExecutionStrategy strategy.
    //
    GraphQL graphQL = GraphQL
            .newGraphQL(graphqlPublisher.getGraphQLSchema())
            .instrumentation(instrumentation)
            .build();

    ExecutionResult executionResult = graphQL.execute(executionInput);

    Publisher<ExecutionResult> stockPriceStream = executionResult.getData();

    stockPriceStream.subscribe(new Subscriber<ExecutionResult>() {

        @Override
        public void onSubscribe(Subscription s) {
            subscriptionRef.set(s);
            request(1);
        }

        @Override
        public void onNext(ExecutionResult er) {
            log.debug("Sending stick price update");
            try {
                Object stockPriceUpdate = er.getData();
                getRemote().sendString(JsonKit.toJsonString(stockPriceUpdate));
            } catch (IOException e) {
                e.printStackTrace();
            }
            request(1);
        }

        @Override
        public void onError(Throwable t) {
            log.error("Subscription threw an exception", t);
            getSession().close();
        }

        @Override
        public void onComplete() {
            log.info("Subscription complete");
            getSession().close();
        }
    });
}
 
Example #11
Source File: HttpMain.java    From graphql-java-http-example with MIT License 4 votes vote down vote up
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());

    //
    // 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.
    //
    StarWarsWiring.Context context = new StarWarsWiring.Context();
    executionInput.context(context);

    //
    // you need a schema in order to execute queries
    GraphQLSchema schema = buildStarWarsSchema();

    //
    // 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 = context.getDataLoaderRegistry();


    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 is pluggable
            .instrumentation(instrumentation)
            .build();
    ExecutionResult executionResult = graphQL.execute(executionInput.build());

    returnAsJson(httpResponse, executionResult);
}
 
Example #12
Source File: GraphQLFactory.java    From dropwizard-graphql with Apache License 2.0 4 votes vote down vote up
@JsonIgnore
public void setInstrumentations(@Nullable List<Instrumentation> instrumentations) {
  this.instrumentations = Optional.ofNullable(instrumentations).orElseGet(ArrayList::new);
}
 
Example #13
Source File: GuavaListenableFutureSupport.java    From rejoiner with Apache License 2.0 2 votes vote down vote up
/**
 * Converts a {@link ListenableFuture} to a Java8 {@link java.util.concurrent.CompletableFuture}.
 *
 * <p>{@see CompletableFuture} is supported by the provided {@link
 * graphql.execution.AsyncExecutionStrategy}.
 *
 * <p>Note: This should be installed before any other instrumentation.
 */
public static Instrumentation listenableFutureInstrumentation() {
  return listenableFutureInstrumentation(MoreExecutors.directExecutor());
}