graphql.language.SourceLocation Java Examples

The following examples show how to use graphql.language.SourceLocation. 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: 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 #2
Source File: GqlIssueContainer.java    From manifold with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("WeakerAccess")
public void addIssues( List<GraphQLError> errors )
{
  for( GraphQLError e: errors )
  {
    Optional<SourceLocation> loc = e.getLocations().stream().findFirst();
    int line = 0;
    int column = 0;
    int offset = 0;
    if( loc.isPresent() )
    {
      SourceLocation sourceLocation = loc.get();
      line = sourceLocation.getLine();
      column = sourceLocation.getColumn();
      offset = IFileUtil.findOffset( _file, line, column );
    }
    _issues.add( new GqlIssue( IIssue.Kind.Error, offset, line, column, e.getMessage() ) );
  }
}
 
Example #3
Source File: GqlModel.java    From manifold with Apache License 2.0 6 votes vote down vote up
private GraphQLError toGraphQLError( InvalidSyntaxException ise )
{
  return new GraphQLError()
  {
    @Override
    public String getMessage()
    {
      return ise.getMessage();
    }

    @Override
    public List<SourceLocation> getLocations()
    {
      return Collections.singletonList( ise.getLocation() );
    }

    @Override
    public ErrorClassification getErrorType()
    {
      return ErrorType.InvalidSyntax;
    }
  };
}
 
Example #4
Source File: UsernameFieldValidationTest.java    From notification with Apache License 2.0 6 votes vote down vote up
public static GraphQLError buildError(final String message) {
  return new GraphQLError() {

    @Override
    public String getMessage() {
      return message;
    }

    @Nullable
    @Override
    public List<SourceLocation> getLocations() {
      return null;
    }

    @Nullable
    @Override
    public ErrorType getErrorType() {
      return null;
    }
  };
}
 
Example #5
Source File: GqlParentType.java    From manifold with Apache License 2.0 6 votes vote down vote up
private SourceLocation getActualSourceLocation( SrcLinkedClass srcClass, Node node )
{
  final SourceLocation[] loc = {node.getSourceLocation()};
  srcClass.processContent( loc[0].getLine(), loc[0].getColumn(), ( content, offset) -> {
    int endComment;
    if( content.startsWith( "\"\"\"" ) )
    {
      endComment = content.indexOf( "\"\"\"", offset + 3 );
      if( endComment > 0 )
      {
        endComment += 3;
      }
    }
    else
    {
      endComment = offset;
    }
    loc[0] = adjustLocation( node, content, offset, endComment );
  } );
  return loc[0];
}
 
Example #6
Source File: GraphQLUtil.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
/**
 *
 * Creates a source location based on a token and line/column offsets
 * @param token the token to create a location for
 * @param lineDelta the delta line to apply to the document and all child nodes
 * @param firstLineColumnDelta the column delta for the first line
 * @return the offset location for the token
 */
public static SourceLocation createSourceLocationFromDelta(Token token, int lineDelta, int firstLineColumnDelta) {
    String sourceName = token.getTokenSource().getSourceName();
    if (IntStream.UNKNOWN_SOURCE_NAME.equals(sourceName)) {
        // UNKNOWN_SOURCE_NAME is Antrl's way of indicating that no source name was given during parsing --
        // which is the case when queries and other operations are parsed. We don't want this hardcoded
        // '<unknown>' sourceName to leak to clients when the response is serialized as JSON, so we null it.
        sourceName = null;
    }
    int line = token.getLine();
    int column = token.getCharPositionInLine() + 1;
    if(line == 0 && firstLineColumnDelta > 0) {
        column += firstLineColumnDelta;
    }
    line += lineDelta;
    return new SourceLocation(line, column, sourceName);
}
 
Example #7
Source File: GraphQLTreeNodeNavigationUtil.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
public static void openSourceLocation(Project myProject, SourceLocation location, boolean resolveSDLFromJSON) {
    VirtualFile sourceFile = StandardFileSystems.local().findFileByPath(location.getSourceName());
    if (sourceFile != null) {
        PsiFile file = PsiManager.getInstance(myProject).findFile(sourceFile);
        if (file != null) {
            if (file instanceof JsonFile && resolveSDLFromJSON) {
                GraphQLFile graphQLFile = file.getUserData(GraphQLSchemaKeys.GRAPHQL_INTROSPECTION_JSON_TO_SDL);
                if (graphQLFile != null) {
                    // open the SDL file and not the JSON introspection file it was based on
                    file = graphQLFile;
                    sourceFile = file.getVirtualFile();
                }
            }
            new OpenFileDescriptor(myProject, sourceFile, location.getLine() - 1, location.getColumn() - 1).navigate(true);
        }
    }
}
 
Example #8
Source File: TransformException.java    From smallrye-graphql with Apache License 2.0 6 votes vote down vote up
@Override
public DataFetcherResult.Builder<Object> appendDataFetcherResult(DataFetcherResult.Builder<Object> builder,
        DataFetchingEnvironment dfe) {
    DataFetcherExceptionHandlerParameters handlerParameters = DataFetcherExceptionHandlerParameters
            .newExceptionParameters()
            .dataFetchingEnvironment(dfe)
            .exception(super.getCause())
            .build();

    SourceLocation sourceLocation = getSourceLocation(dfe, handlerParameters);

    List<String> paths = toPathList(handlerParameters.getPath());

    ValidationError error = new ValidationError(ValidationErrorType.WrongType,
            sourceLocation, "argument '" + field.getName() + "' with value 'StringValue{value='" + parameterValue
                    + "'}' is not a valid '" + getScalarTypeName() + "'",
            paths);

    return builder.error(error);
}
 
Example #9
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 #10
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 #11
Source File: FederatedTracingInstrumentation.java    From federation-jvm with MIT License 6 votes vote down vote up
@Override
public InstrumentationContext<Object> beginFieldFetch(InstrumentationFieldFetchParameters parameters) {
    FederatedTracingState state = parameters.getInstrumentationState();
    if (state == null) {
        return super.beginFieldFetch(parameters);
    }

    SourceLocation fieldLocation = parameters.getEnvironment().getField().getSourceLocation();

    long startNanos = System.nanoTime();
    return whenCompleted((result, throwable) -> {
        long endNanos = System.nanoTime();

        ExecutionStepInfo executionStepInfo = parameters.getEnvironment().getExecutionStepInfo();
        state.addFieldFetchData(
                executionStepInfo,
                // relative to the trace's start_time, in ns
                startNanos - state.getStartRequestNanos(),
                // relative to the trace's start_time, in ns
                endNanos - state.getStartRequestNanos(),
                convertErrors(throwable, result),
                fieldLocation
        );
    });
}
 
Example #12
Source File: GraphQLIntrospectionResultToSchema.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
private Description getDescription(Map<String, Object> descriptionAware) {
    final Object rawDescription = descriptionAware.get("description");
    if (rawDescription instanceof String) {
        String description = (String) rawDescription;
        if (!description.trim().isEmpty()) {
            final boolean multiLine = description.contains("\n");
            if (multiLine) {
                // ensures the description stands on separate lines from the triple quotes
                description = "\n" + description.trim() + "\n";
            }
            return new Description(description, new SourceLocation(1, 1), multiLine);
        }
    }
    return null;
}
 
Example #13
Source File: TransformException.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private SourceLocation getSourceLocation(DataFetchingEnvironment dfe,
        DataFetcherExceptionHandlerParameters handlerParameters) {
    List<Argument> arguments = dfe.getField().getArguments();
    for (Argument a : arguments) {
        if (a.getName().equals(this.field.getName())) {
            return a.getSourceLocation();
        }
    }
    // Else fallback to more general
    return handlerParameters.getSourceLocation();
}
 
Example #14
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 #15
Source File: GraphQLSchemaErrorNode.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
@Override
public void handleDoubleClickOrEnter(SimpleTree tree, InputEvent inputEvent) {
    final SourceLocation location = getLocation();
    if (location != null && location.getSourceName() != null) {
        GraphQLTreeNodeNavigationUtil.openSourceLocation(myProject, location, false);
    } else if (error instanceof GraphQLInternalSchemaError) {
        String stackTrace = ExceptionUtil.getThrowableText(((GraphQLInternalSchemaError) error).getException());
        PsiFile file = PsiFileFactory.getInstance(myProject).createFileFromText("graphql-error.txt", PlainTextLanguage.INSTANCE, stackTrace);
        new OpenFileDescriptor(myProject, file.getVirtualFile()).navigate(true);
    }
}
 
Example #16
Source File: GraphQLSchemaErrorNode.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
public GraphQLSchemaErrorNode(SimpleNode parent, GraphQLError error) {
    super(parent);
    this.error = error;
    myName = error.getMessage();
    setIcon(AllIcons.Ide.FatalError);
    SourceLocation location = getLocation();
    if (location != null) {
        getTemplatePresentation().setTooltip(location.getSourceName() + ":" + location.getLine() + ":" + location.getColumn());
    } else if (error instanceof GraphQLInternalSchemaError) {
        getTemplatePresentation().setLocationString(" - double click to open stack trace");
    }
}
 
Example #17
Source File: GraphQlFailedException.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getMessage() {
  String result = "";
  for (GraphQLError error : errors) {
    result += error.getErrorType() + ": " + error.getMessage() + "\n";
    for (SourceLocation sourceLocation : error.getLocations()) {
      result += "  at line: " + sourceLocation.getLine() + " column: " + sourceLocation.getColumn();
    }
  }
  return result;
}
 
Example #18
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 #19
Source File: BookNotFoundException.java    From graphql-java-spring-boot-example with MIT License 4 votes vote down vote up
@Override
public List<SourceLocation> getLocations() {
    return null;
}
 
Example #20
Source File: GraphQLValidationAnnotator.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
private int getOffsetFromSourceLocation(PsiFile psiFile, SourceLocation location) {
    com.intellij.openapi.editor.Document document = PsiDocumentManager.getInstance(psiFile.getProject()).getDocument(getTopLevelFile(psiFile));
    return document != null ? document.getLineStartOffset(location.getLine() - 1) + location.getColumn() - 1 : -1;
}
 
Example #21
Source File: GraphQLSchemaErrorNode.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
private SourceLocation getLocation() {
    final List<SourceLocation> locations = error.getLocations();
    return locations != null && !locations.isEmpty() ? locations.get(0) : null;
}
 
Example #22
Source File: GraphQLUtil.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
/**
 * Parses GraphQL string input into a graphql-java Document, shifting the source locations in the specified document with the specified line delta.
 * Shifting of the sourceLocation is required for proper error reporting locations for GraphQL language injections, e.g. GraphQL in a JavaScript file.
 * @param input a GraphQL document represented as a string to be parsed
 * @param sourceName the file name of the source
 * @param lineDelta the delta line to apply to the document and all child nodes
 * @param firstLineColumnDelta the column delta for the first line
 */
public static Document parseDocument(String input, String sourceName, int lineDelta, int firstLineColumnDelta) {

    CharStream charStream;
    if(sourceName == null) {
        charStream = CharStreams.fromString(input);
    } else{
        charStream = CharStreams.fromString(input, sourceName);
    }

    GraphqlLexer lexer = new GraphqlLexer(charStream);

    CommonTokenStream tokens = new CommonTokenStream(lexer);

    GraphqlParser parser = new GraphqlParser(tokens);
    parser.removeErrorListeners();
    parser.getInterpreter().setPredictionMode(PredictionMode.SLL);
    parser.setErrorHandler(new BailErrorStrategy());
    GraphqlParser.DocumentContext documentContext = parser.document();

    MultiSourceReader multiSourceReader = MultiSourceReader.newMultiSourceReader()
            .string(input, sourceName)
            .trackData(true)
            .build();

    GraphqlAntlrToLanguage antlrToLanguage = new GraphqlAntlrToLanguage(tokens, multiSourceReader) {
        @Override
        protected SourceLocation getSourceLocation(ParserRuleContext parserRuleContext) {
            return createSourceLocationFromDelta(parserRuleContext.getStart(), lineDelta, firstLineColumnDelta);
        }

        @Override
        protected SourceLocation getSourceLocation(Token token) {
            return createSourceLocationFromDelta(token, lineDelta, firstLineColumnDelta);
        }
    };
    Document doc = antlrToLanguage.createDocument(documentContext);

    Token stop = documentContext.getStop();
    List<Token> allTokens = tokens.getTokens();
    if (stop != null && allTokens != null && !allTokens.isEmpty()) {
        Token last = allTokens.get(allTokens.size() - 1);
        //
        // do we have more tokens in the stream than we consumed in the parse?
        // if yes then its invalid.  We make sure its the same channel
        boolean notEOF = last.getType() != Token.EOF;
        boolean lastGreaterThanDocument = last.getTokenIndex() > stop.getTokenIndex();
        boolean sameChannel = last.getChannel() == stop.getChannel();
        if (notEOF && lastGreaterThanDocument && sameChannel) {
            throw new ParseCancellationException("There are more tokens in the query that have not been consumed");
        }
    }
    return doc;
}
 
Example #23
Source File: GraphQLInternalSchemaError.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
@Override
public List<SourceLocation> getLocations() {
    return Collections.emptyList();
}
 
Example #24
Source File: CantDetermineDataSetException.java    From timbuctoo with GNU General Public License v3.0 4 votes vote down vote up
@Override
public List<SourceLocation> getLocations() {
  return null;
}
 
Example #25
Source File: GraphQLValidationError.java    From dropwizard-graphql with Apache License 2.0 4 votes vote down vote up
@Nullable
@Override
public List<SourceLocation> getLocations() {
  return null;
}
 
Example #26
Source File: GqlParentType.java    From manifold with Apache License 2.0 4 votes vote down vote up
private void addSourcePositionAnnotation( SrcLinkedClass srcClass, Node node, String name, SrcAnnotated srcAnno )
{
  SourceLocation loc = getActualSourceLocation( srcClass, node );
  srcClass.addSourcePositionAnnotation( srcAnno, name, loc.getLine(), loc.getColumn() );
}
 
Example #27
Source File: GraphQLException.java    From besu with Apache License 2.0 4 votes vote down vote up
@Override
public List<SourceLocation> getLocations() {
  return null;
}
 
Example #28
Source File: GraphQLErrorAdapter.java    From graphql-java-spring-boot-example with MIT License 4 votes vote down vote up
@Override
public List<SourceLocation> getLocations() {
    return error.getLocations();
}
 
Example #29
Source File: RejoinerIntegrationTest.java    From rejoiner with Apache License 2.0 4 votes vote down vote up
@Override
public List<SourceLocation> getLocations() {
  return null;
}
 
Example #30
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());
}