graphql.execution.ExecutionPath Java Examples

The following examples show how to use graphql.execution.ExecutionPath. 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: FederatedTracingInstrumentation.java    From federation-jvm with MIT License 6 votes vote down vote up
/**
 * Edit builder for the node at the given path (creating it and its parents if needed).
 */
public void editBuilder(ExecutionPath path, Consumer<Reports.Trace.Node.Builder> builderConsumer) {
    Lock l = treeLock.readLock();
    l.lock();
    try {
        if (isFinalized) {
            throw new RuntimeException("Cannot edit builder after protobuf conversion.");
        }
        Node node = getOrCreateNode(path);
        synchronized (node.builder) {
            builderConsumer.accept(node.builder);
        }
    } finally {
        l.unlock();
    }
}
 
Example #2
Source File: ExceptionHandler.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
private ExceptionWhileDataFetching getExceptionWhileDataFetching(Throwable throwable, SourceLocation sourceLocation,
        ExecutionPath path) {
    if (throwable instanceof RuntimeException) {
        // Check for showlist
        if (exceptionLists.shouldShow(throwable)) {
            return new GraphQLExceptionWhileDataFetching(path, throwable, sourceLocation);
        } else {
            return new GraphQLExceptionWhileDataFetching(config.getDefaultErrorMessage(), path, throwable, sourceLocation);
        }
    } else {
        // Check for hidelist
        if (exceptionLists.shouldHide(throwable)) {
            return new GraphQLExceptionWhileDataFetching(config.getDefaultErrorMessage(), path, throwable, sourceLocation);
        } else {
            return new GraphQLExceptionWhileDataFetching(path, throwable, sourceLocation);
        }
    }
}
 
Example #3
Source File: AbstractDataFetcher.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
protected final DataFetcherResult.Builder<Object> appendPartialResult(
        DataFetcherResult.Builder<Object> resultBuilder,
        DataFetchingEnvironment dfe,
        GraphQLException graphQLException) {
    DataFetcherExceptionHandlerParameters handlerParameters = DataFetcherExceptionHandlerParameters
            .newExceptionParameters()
            .dataFetchingEnvironment(dfe)
            .exception(graphQLException)
            .build();

    SourceLocation sourceLocation = handlerParameters.getSourceLocation();
    ExecutionPath path = handlerParameters.getPath();
    GraphQLExceptionWhileDataFetching error = new GraphQLExceptionWhileDataFetching(path, graphQLException,
            sourceLocation);

    return resultBuilder
            .data(graphQLException.getPartialResults())
            .error(error);
}
 
Example #4
Source File: ExecutionErrorsServiceTest.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
@Test
void testToJsonErrors_WhenExceptionWhileDataFetchingErrorCaught_ShouldReturnJsonBodyWithCustomExtensions() {
    // Given
    Map<String, Object> extensions = new HashMap<>();
    extensions.put("code", "OPERATION_FAILED");
    GraphqlErrorException graphqlErrorException = GraphqlErrorException.newErrorException()
            .extensions(extensions)
            .build();
    ExceptionWhileDataFetching exceptionWhileDataFetching = new ExceptionWhileDataFetching(ExecutionPath.rootPath(),
            graphqlErrorException, new SourceLocation(1, 1));

    // When
    JsonArray jsonArray = executionErrorsService.toJsonErrors(singletonList(exceptionWhileDataFetching));

    // Then
    JsonObject extensionJsonObject = jsonArray.getJsonObject(0).getJsonObject("extensions");
    assertThat(extensionJsonObject.getString("exception")).isEqualTo("graphql.GraphqlErrorException");
    assertThat(extensionJsonObject.getString("classification")).isEqualTo("DataFetchingException");
    assertThat(extensionJsonObject.getString("code")).isEqualTo("OPERATION_FAILED");
}
 
Example #5
Source File: MockDataFetchEnvironment.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
public static DataFetchingEnvironment myFastQueryDfe(String typeName, String fieldName, String operationName,
        String executionId) {
    GraphQLNamedType query = mock(GraphQLNamedType.class);
    when(query.getName()).thenReturn(typeName);

    Field field = mock(Field.class);
    when(field.getName()).thenReturn(fieldName);

    OperationDefinition operationDefinition = mock(OperationDefinition.class);
    when(operationDefinition.getName()).thenReturn(operationName);

    ExecutionPath executionPath = mock(ExecutionPath.class);
    when(executionPath.toString()).thenReturn("/" + typeName + "/" + fieldName);
    ExecutionStepInfo executionStepInfo = mock(ExecutionStepInfo.class);
    when(executionStepInfo.getPath()).thenReturn(executionPath);

    DataFetchingEnvironment dfe = mock(DataFetchingEnvironment.class);
    when(dfe.getParentType()).thenReturn(query);
    when(dfe.getField()).thenReturn(field);
    when(dfe.getOperationDefinition()).thenReturn(operationDefinition);
    when(dfe.getExecutionStepInfo()).thenReturn(executionStepInfo);
    when(dfe.getExecutionId()).thenReturn(ExecutionId.from(executionId));

    return dfe;
}
 
Example #6
Source File: FederatedTracingInstrumentation.java    From federation-jvm with MIT License 5 votes vote down vote up
/**
 * Adds stats data collected from a field fetch.
 */
void addFieldFetchData(ExecutionStepInfo stepInfo, long startFieldNanos, long endFieldNanos, List<GraphQLError> errors, SourceLocation fieldLocation) {
    ExecutionPath path = stepInfo.getPath();
    protoBuilderTree.editBuilder(path, (builder) -> {
        builder.setStartTime(startFieldNanos)
                .setEndTime(endFieldNanos)
                .setParentType(simplePrint(stepInfo.getParent().getUnwrappedNonNullType()))
                .setType(stepInfo.simplePrint())
                .setResponseName(stepInfo.getResultKey());

        // set originalFieldName only when a field alias was used
        String originalFieldName = stepInfo.getField().getName();
        if (!originalFieldName.equals(stepInfo.getResultKey())) {
            builder.setOriginalFieldName(originalFieldName);
        }

        errors.forEach(error -> {
            Reports.Trace.Error.Builder errorBuilder = builder.addErrorBuilder()
                    .setMessage(error.getMessage());
            if (error.getLocations().isEmpty() && fieldLocation != null) {
                errorBuilder.addLocationBuilder()
                        .setColumn(fieldLocation.getColumn())
                        .setLine(fieldLocation.getLine());
            } else {
                error.getLocations().forEach(location -> errorBuilder.addLocationBuilder()
                        .setColumn(location.getColumn())
                        .setLine(location.getLine()));
            }
        });
    });
}
 
Example #7
Source File: FederatedTracingInstrumentation.java    From federation-jvm with MIT License 5 votes vote down vote up
void addRootError(GraphQLError error) {
    protoBuilderTree.editBuilder(ExecutionPath.rootPath(), (builder) -> {
        Reports.Trace.Error.Builder errorBuilder = builder.addErrorBuilder()
                .setMessage(error.getMessage());

        error.getLocations().forEach(location -> errorBuilder.addLocationBuilder()
                .setColumn(location.getColumn())
                .setLine(location.getLine()));
    });
}
 
Example #8
Source File: ExceptionHandler.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
@Override
public DataFetcherExceptionHandlerResult onException(DataFetcherExceptionHandlerParameters handlerParameters) {
    Throwable throwable = handlerParameters.getException();
    SourceLocation sourceLocation = handlerParameters.getSourceLocation();
    ExecutionPath path = handlerParameters.getPath();
    ExceptionWhileDataFetching error = getExceptionWhileDataFetching(throwable, sourceLocation, path);

    if (config.isPrintDataFetcherException()) {
        log.dataFetchingError(throwable);
    }

    return DataFetcherExceptionHandlerResult.newResult().error(error).build();
}
 
Example #9
Source File: TransformException.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private List<String> toPathList(ExecutionPath path) {
    List<String> l = new ArrayList<>();
    for (Object o : path.toList()) {
        l.add(o.toString());
    }
    return l;
}
 
Example #10
Source File: Util.java    From samples with MIT License 5 votes vote down vote up
public static ExecutionPath concatPaths(ExecutionPath parent, ExecutionPath child) {
  if (child == null) {
    return parent;
  }
  List<Object> segments = child.toList();
  for (Object segment : segments) {
    if (segment instanceof Integer) {
      parent = parent.segment(((Integer) segment));
    } else {
      parent = parent.segment((String.valueOf(segment)));
    }
  }
  return parent;
}
 
Example #11
Source File: FederatedTracingInstrumentation.java    From federation-jvm with MIT License 4 votes vote down vote up
public ProtoBuilderTree() {
    root = new Node(Reports.Trace.Node.newBuilder());
    nodesByPath = new ConcurrentHashMap<>();
    nodesByPath.put(ExecutionPath.rootPath(), root);
    treeLock = new ReentrantReadWriteLock();
}
 
Example #12
Source File: FederatedTracingInstrumentation.java    From federation-jvm with MIT License 4 votes vote down vote up
/**
 * Get node for the given path in nodesByPath (creating it and its parents if needed).
 *
 * Note that {@link #treeLock}'s read lock must be held when calling this method.
 */
@NotNull
private Node getOrCreateNode(ExecutionPath path) {
    // Fast path for when the node already exists.
    Node current = nodesByPath.get(path);
    if (current != null) return current;

    // Find the latest ancestor that exists in the map.
    List<Object> pathSegments = path.toList();
    int currentSegmentIndex = pathSegments.size();
    while (current == null) {
        if (currentSegmentIndex <= 0) {
            // The root path's node is inserted at construction time, so this shouldn't
            // happen.
            throw new RuntimeException("root path missing from nodesByPath?");
        }
        currentSegmentIndex--;
        ExecutionPath currentPath = ExecutionPath.fromList(pathSegments.subList(0, currentSegmentIndex));
        current = nodesByPath.get(currentPath);
    }

    // Travel back down to the requested node, creating child nodes along the way as
    // needed.
    for (; currentSegmentIndex < pathSegments.size(); currentSegmentIndex++) {
        Node parent = current;
        ExecutionPath childPath = ExecutionPath.fromList(pathSegments.subList(0, currentSegmentIndex + 1));
        Object childSegment = pathSegments.get(currentSegmentIndex);

        Reports.Trace.Node.Builder childBuilder = Reports.Trace.Node.newBuilder();
        if (childSegment instanceof Integer) {
            childBuilder.setIndex((Integer) childSegment);
        } else if (currentSegmentIndex < pathSegments.size() - 1) {
            // We've encountered a field name node that is an ancestor of the requested
            // node. However, the fetcher for that field name should have ultimately
            // called getOrCreateNode() on its node before getOrCreateNode() was called
            // on the requested node, meaning that this field name node should already
            // be in nodesByPath. Accordingly, we should never encounter such field
            // name ancestor nodes, and we throw when we do.
            throw new RuntimeException("Unexpected missing non-index " + childSegment);
        }
        Node childNode = new Node(childBuilder);

        // Note that putIfAbsent() here will give the child node if it already existed,
        // or null if it didn't (in which case the node passed to putIfAbsent() becomes
        // the child node).
        current = nodesByPath.putIfAbsent(childPath, childNode);
        if (current == null) {
            current = childNode;
            parent.children.add(childNode);
        }
    }

    return current;
}
 
Example #13
Source File: GraphQLExceptionWhileDataFetching.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
public GraphQLExceptionWhileDataFetching(ExecutionPath path, Throwable exception, SourceLocation sourceLocation) {
    super(path, exception, sourceLocation);
    this.message = super.getException().getMessage();
}
 
Example #14
Source File: GraphQLExceptionWhileDataFetching.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
public GraphQLExceptionWhileDataFetching(String message, ExecutionPath path, Throwable exception,
        SourceLocation sourceLocation) {
    super(path, exception, sourceLocation);
    this.message = message;
}
 
Example #15
Source File: ExecutionErrorsServiceTest.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
private JsonArray whenConverting(RuntimeException exception) {
    ExecutionPath path = ExecutionPath.parse("/foo/bar");
    SourceLocation location = new SourceLocation(12, 34);
    GraphQLError graphQLError = new GraphQLExceptionWhileDataFetching(path, exception, location);
    return executionErrorsService.toJsonErrors(singletonList(graphQLError));
}
 
Example #16
Source File: ExecutionResultToProtoAsyncTest.java    From rejoiner with Apache License 2.0 4 votes vote down vote up
@Test
public void toProtoExecutionResultShouldReturnDataAndError()
    throws ExecutionException, InterruptedException {

  ExceptionWhileDataFetching exceptionWhileDataFetching =
      new ExceptionWhileDataFetching(
          ExecutionPath.rootPath(),
          new RuntimeException("hello world"),
          new SourceLocation(10, 20));
  CompletableFuture<ProtoExecutionResult<Proto1>> executionResultCompletableFuture =
      ExecutionResultToProtoAsync.toProtoExecutionResult(
          Proto1.getDefaultInstance(),
          CompletableFuture.completedFuture(
              ExecutionResultImpl.newExecutionResult()
                  .data(
                      ImmutableMap.of(
                          "id",
                          "abc",
                          "intField",
                          123,
                          "testProto",
                          ImmutableMap.of(
                              "innerId", "abc_inner", "enums", ImmutableList.of("FOO"))))
                  .addError(exceptionWhileDataFetching)
                  .build()));
  ProtoTruth.assertThat(executionResultCompletableFuture.get().message())
      .isEqualTo(
          Proto1.newBuilder()
              .setId("abc")
              .setIntField(123)
              .setTestProto(
                  Proto2.newBuilder()
                      .setInnerId("abc_inner")
                      .addEnumsValue(Proto2.TestEnum.FOO_VALUE))
              .build());
  ProtoTruth.assertThat(executionResultCompletableFuture.get().errors())
      .containsExactly(
          GraphqlError.newBuilder()
              .setMessage("Exception while fetching data () : hello world")
              .addLocations(
                  com.google.api.graphql.SourceLocation.newBuilder().setLine(10).setColumn(20))
              .setType(ErrorType.DATA_FETCHING_EXCEPTION)
              .build());
}