graphql.language.Document Java Examples

The following examples show how to use graphql.language.Document. 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 5 votes vote down vote up
@Override
public InstrumentationContext<Document> beginParse(InstrumentationExecutionParameters parameters) {
    FederatedTracingState state = parameters.getInstrumentationState();
    if (state == null) {
        return super.beginParse(parameters);
    }

    return whenCompleted((document, throwable) -> {
        for (GraphQLError error : convertErrors(throwable, null)) {
            state.addRootError(error);
        }
    });
}
 
Example #2
Source File: GraphQLAPIHandler.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method validate the payload
 *
 * @param messageContext message context of the request
 * @param document       graphQL schema of the request
 * @return true or false
 */
private boolean validatePayloadWithSchema(MessageContext messageContext, Document document) {
    ArrayList<String> validationErrorMessageList = new ArrayList<>();
    List<ValidationError> validationErrors;
    String validationErrorMessage;

    synchronized (apiUUID + CLASS_NAME_AND_METHOD) {
        if (schema == null) {
            Entry localEntryObj = (Entry) messageContext.getConfiguration().getLocalRegistry().get(apiUUID +
                    GRAPHQL_IDENTIFIER);
            if (localEntryObj != null) {
                SchemaParser schemaParser = new SchemaParser();
                schemaDefinition = localEntryObj.getValue().toString();
                TypeDefinitionRegistry registry = schemaParser.parse(schemaDefinition);
                schema = UnExecutableSchemaGenerator.makeUnExecutableSchema(registry);
            }
        }
    }

    validationErrors = validator.validateDocument(schema, document);
    if (validationErrors != null && validationErrors.size() > 0) {
        if (log.isDebugEnabled()) {
            log.debug("Validation failed for " + document);
        }
        for (ValidationError error : validationErrors) {
            validationErrorMessageList.add(error.getDescription());
        }
        validationErrorMessage = String.join(",", validationErrorMessageList);
        handleFailure(messageContext, validationErrorMessage);
        return false;
    }
    return true;
}
 
Example #3
Source File: GraphQLValidationAnnotator.java    From js-graphql-intellij-plugin with MIT License 5 votes vote down vote up
private LogicalPosition getLogicalPositionFromOffset(PsiFile psiFile, int offset) {
    com.intellij.openapi.editor.Document document = PsiDocumentManager.getInstance(psiFile.getProject()).getDocument(getTopLevelFile(psiFile));
    if (document != null) {
        final int lineNumber = document.getLineNumber(offset);
        final int lineStartOffset = document.getLineStartOffset(lineNumber);
        return new LogicalPosition(lineNumber, offset - lineStartOffset);
    }
    return new LogicalPosition(-1, -1);
}
 
Example #4
Source File: ApiGen.java    From graphql-apigen with Apache License 2.0 5 votes vote down vote up
private void add(Map<String, TypeEntry> types, URL path) throws IOException {
    String content = slurp(path);
    try {
        Document doc = parser.parseDocument(content);
        for ( Definition definition : doc.getDefinitions() ) {
            if ( definition instanceof SchemaDefinition ) {
                if ( generatedTypes == types ) {
                    schemaDefinitions.add(new TypeEntry(definition, path, defaultPackageName));
                }
                continue;
            } else if ( ! (definition instanceof TypeDefinition) ) {
                // TODO: What about @definition types?
                throw new RuntimeException(
                    "GraphQL schema documents must only contain schema type definitions, got "+
                    definition.getClass().getSimpleName() + " [" +
                    definition.getSourceLocation().getLine() + "," +
                    definition.getSourceLocation().getColumn() + "]");
            }
            TypeEntry newEntry = new TypeEntry(definition, path, defaultPackageName);
            TypeEntry oldEntry = referenceTypes.get(newEntry.getName());

            if ( null != oldEntry ) {
                // TODO: Support the extend type?
                throw new RuntimeException(
                    "Duplicate type definition for '" + newEntry.getName() + "'" +
                    " defined both in " + oldEntry.getSourceLocation() + " and " +
                    newEntry.getSourceLocation());
            }

            types.put(newEntry.getName(), newEntry);
            if ( types != referenceTypes ) {
                // All types should be added to reference types...
                referenceTypes.put(newEntry.getName(), newEntry);
            }
        }
    } catch ( Exception ex ) {
        throw new RuntimeException(ex.getMessage() + " when parsing '"+path+"'", ex);
    }
}
 
Example #5
Source File: GqlModel.java    From manifold with Apache License 2.0 5 votes vote down vote up
private void buildRegistry( Document document )
{
  TypeDefinitionRegistry typeRegistry = new TypeDefinitionRegistry();
  List<Definition> definitions = document.getDefinitions();
  Map<String, OperationDefinition> operations = new LinkedHashMap<>();
  Map<String, FragmentDefinition> fragments = new LinkedHashMap<>();
  List<GraphQLError> errors = new ArrayList<>();
  for( Definition definition: definitions )
  {
    if( definition instanceof SchemaDefinition )
    {
      _schemaDefinition = (SchemaDefinition)definition;
    }
    else if( definition instanceof SDLDefinition )
    {
      // types, interfaces, unions, inputs, scalars, extensions
      typeRegistry.add( (SDLDefinition)definition ).ifPresent( errors::add );
      if( definition instanceof ScalarTypeDefinition )
      {
        // register scalar type
        typeRegistry.scalars().put( ((ScalarTypeDefinition)definition).getName(), (ScalarTypeDefinition)definition );
      }
    }
    else if( definition instanceof OperationDefinition )
    {
      // queries, mutations, subscriptions
      operations.put( ((OperationDefinition)definition).getName(), (OperationDefinition)definition );
    }
    else if( definition instanceof FragmentDefinition )
    {
      // fragments
      fragments.put( ((FragmentDefinition)definition).getName(), (FragmentDefinition)definition );
    }
  }
  _issues = new GqlIssueContainer( errors, getFile() );
  _typeRegistry = typeRegistry;
  _operations = operations;
  _fragments = fragments;
}
 
Example #6
Source File: ExecutionForestFactory.java    From hypergraphql with Apache License 2.0 5 votes vote down vote up
private SelectionSet selectionSet(final Document queryDocument) {

        final Definition definition = queryDocument.getDefinitions().get(0);

        if(definition.getClass().isAssignableFrom(FragmentDefinition.class)) {

            return getFragmentSelectionSet(queryDocument);

        } else if(definition.getClass().isAssignableFrom(OperationDefinition.class)) {
            final OperationDefinition operationDefinition = (OperationDefinition)definition;
            return operationDefinition.getSelectionSet();
        }
        throw new IllegalArgumentException(queryDocument.getClass().getName() + " is not supported");
    }
 
Example #7
Source File: Generator.java    From smallrye-graphql with Apache License 2.0 5 votes vote down vote up
private void generateQueryMethod(Document query) {
    List<OperationDefinition> definitions = query.getDefinitionsOfType(OperationDefinition.class);
    if (definitions.size() != 1)
        throw new GraphQlGeneratorException("expected exactly one definition but found "
                + definitions.stream().map(this::operationInfo).collect(listString()));
    OperationDefinition operation = definitions.get(0);
    List<Field> fields = operation.getSelectionSet().getSelectionsOfType(Field.class);
    if (fields.size() != 1)
        throw new GraphQlGeneratorException("expected exactly one field but got "
                + fields.stream().map(Field::getName).collect(listString()));
    Field field = fields.get(0);
    body.append(new MethodGenerator(operation, field));
}
 
Example #8
Source File: GraphqlServlet.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
/**
 * Initialises and parses the GraphQL schema.
 * 
 * @return The registry of type definitions.
 * @throws IOException If an I/O error occurs.
 */
@SuppressWarnings("unchecked")
private TypeDefinitionRegistry buildTypeDefinitionRegistry() throws IOException {
    String json = readResource("magento-luma-schema-2.3.5.json");

    Type type = TypeToken.getParameterized(Map.class, String.class, Object.class).getType();
    Map<String, Object> map = gson.fromJson(json, type);
    Map<String, Object> data = (Map<String, Object>) map.get("data");

    Document document = new IntrospectionResultToSchema().createSchemaDefinition(data);
    String sdl = new SchemaPrinter().print(document);
    return new SchemaParser().parse(sdl);
}
 
Example #9
Source File: ExecutionForestFactory.java    From hypergraphql with Apache License 2.0 4 votes vote down vote up
public ExecutionForest getExecutionForest(Document queryDocument , HGQLSchema schema) {

        ExecutionForest forest = new ExecutionForest();

        SelectionSet queryFields = selectionSet(queryDocument);

        final AtomicInteger counter = new AtomicInteger(0);
        queryFields.getSelections().forEach(child -> { // query fields - why no args?

            if (child.getClass().getSimpleName().equals("Field")) {

                String nodeId = "x_" + counter.incrementAndGet();
                forest.getForest().add(new ExecutionTreeNode((Field) child, nodeId , schema));

            }
        });
        return forest;
    }
 
Example #10
Source File: ValidatedQuery.java    From hypergraphql with Apache License 2.0 4 votes vote down vote up
public Document getParsedQuery() {
    return parsedQuery;
}
 
Example #11
Source File: ValidatedQuery.java    From hypergraphql with Apache License 2.0 4 votes vote down vote up
public Document getParsedQuery() {
    return parsedQuery;
}
 
Example #12
Source File: GqlModel.java    From manifold with Apache License 2.0 4 votes vote down vote up
private void parse( Reader schemaInput ) throws ParseCancellationException
{
  Parser parser = new Parser();
  Document document = parser.parseDocument( schemaInput );
  buildRegistry( document );
}
 
Example #13
Source File: RelayDataFetchingEnvironmentDecorator.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
@Override
public Document getDocument() {
    return delegate.getDocument();
}
 
Example #14
Source File: Generator.java    From smallrye-graphql with Apache License 2.0 4 votes vote down vote up
private List<Document> parseQueries() {
    return queryStrings.stream()
            .map(this::query)
            .collect(toList());
}
 
Example #15
Source File: GraphQLUtil.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
public static Document parseDocument(String input, int lineDelta, int firstLineColumnDelta) {
    return parseDocument(input, null, lineDelta, firstLineColumnDelta);
}
 
Example #16
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 #17
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 #18
Source File: GraphQLIntrospectionResultToSchema.java    From js-graphql-intellij-plugin with MIT License 4 votes vote down vote up
/**
 * Returns a IDL Document that represents the schema as defined by the introspection result map
 *
 * @param introspectionResult the result of an introspection query on a schema
 *
 * @return a IDL Document of the schema
 */
@SuppressWarnings("unchecked")
public Document createSchemaDefinition(Map<String, Object> introspectionResult) {
    assertTrue(introspectionResult.get("__schema") != null, () -> "__schema expected");
    Map<String, Object> schema = (Map<String, Object>) introspectionResult.get("__schema");


    Map<String, Object> queryType = (Map<String, Object>) schema.get("queryType");
    assertNotNull(queryType, () -> "queryType expected");
    TypeName query = TypeName.newTypeName().name((String) queryType.get("name")).build();
    boolean nonDefaultQueryName = !"Query".equals(query.getName());

    SchemaDefinition.Builder schemaDefinition = SchemaDefinition.newSchemaDefinition();
    schemaDefinition.operationTypeDefinition(OperationTypeDefinition.newOperationTypeDefinition().name("query").typeName(query).build());

    Map<String, Object> mutationType = (Map<String, Object>) schema.get("mutationType");
    boolean nonDefaultMutationName = false;
    if (mutationType != null) {
        TypeName mutation = TypeName.newTypeName().name((String) mutationType.get("name")).build();
        nonDefaultMutationName = !"Mutation".equals(mutation.getName());
        schemaDefinition.operationTypeDefinition(OperationTypeDefinition.newOperationTypeDefinition().name("mutation").typeName(mutation).build());
    }

    Map<String, Object> subscriptionType = (Map<String, Object>) schema.get("subscriptionType");
    boolean nonDefaultSubscriptionName = false;
    if (subscriptionType != null) {
        TypeName subscription = TypeName.newTypeName().name(((String) subscriptionType.get("name"))).build();
        nonDefaultSubscriptionName = !"Subscription".equals(subscription.getName());
        schemaDefinition.operationTypeDefinition(OperationTypeDefinition.newOperationTypeDefinition().name("subscription").typeName(subscription).build());
    }

    Document.Builder document = Document.newDocument();
    if (nonDefaultQueryName || nonDefaultMutationName || nonDefaultSubscriptionName) {
        document.definition(schemaDefinition.build());
    }

    List<Map<String, Object>> types = (List<Map<String, Object>>) schema.get("types");
    for (Map<String, Object> type : types) {
        TypeDefinition typeDefinition = createTypeDefinition(type);
        if (typeDefinition == null) continue;
        document.definition(typeDefinition);
    }

    return document.build();
}
 
Example #19
Source File: GraphQLAPIHandler.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
public boolean handleRequest(MessageContext messageContext) {
    try {
        String payload;
        Parser parser = new Parser();

        org.apache.axis2.context.MessageContext axis2MC = ((Axis2MessageContext) messageContext).
                getAxis2MessageContext();
        String requestPath = messageContext.getProperty(REST_SUB_REQUEST_PATH).toString();
        if (requestPath != null && !requestPath.isEmpty()) {
            String[] queryParams = ((Axis2MessageContext) messageContext).getProperties().
                    get(REST_SUB_REQUEST_PATH).toString().split(QUERY_PATH_STRING);
            if (queryParams.length > 1) {
                payload = URLDecoder.decode(queryParams[1], UNICODE_TRANSFORMATION_FORMAT);
            } else {
                RelayUtils.buildMessage(axis2MC);
                OMElement body = axis2MC.getEnvelope().getBody().getFirstElement();
                if (body != null && body.getFirstElement() != null) {
                    payload = body.getFirstElement().getText();
                } else {
                    if (log.isDebugEnabled()) {
                        log.debug("Invalid query parameter " + queryParams[0]);
                    }
                    handleFailure(messageContext, "Invalid query parameter");
                    return false;
                }
            }
            messageContext.setProperty(APIConstants.GRAPHQL_PAYLOAD, payload);
        } else {
            handleFailure(messageContext, "Request path cannot be empty");
            return false;
        }

        // Validate payload with graphQLSchema
        Document document = parser.parseDocument(payload);

        if (validatePayloadWithSchema(messageContext, document)) {
            supportForBasicAndAuthentication(messageContext);

            // Extract the operation type and operations from the payload
            for (Definition definition : document.getDefinitions()) {
                if (definition instanceof OperationDefinition) {
                    OperationDefinition operation = (OperationDefinition) definition;
                    if (operation.getOperation() != null) {
                        String httpVerb = ((Axis2MessageContext) messageContext).getAxis2MessageContext().
                                getProperty(HTTP_METHOD).toString();
                        messageContext.setProperty(HTTP_VERB, httpVerb);
                        ((Axis2MessageContext) messageContext).getAxis2MessageContext().setProperty(HTTP_METHOD,
                                operation.getOperation().toString());
                        String operationList = getOperationList(messageContext, operation);
                        messageContext.setProperty(APIConstants.API_ELECTED_RESOURCE, operationList);
                        if (log.isDebugEnabled()) {
                            log.debug("Operation list has been successfully added to elected property");
                        }
                        return true;
                    }
                } else {
                    handleFailure(messageContext, "Operation definition cannot be empty");
                    return false;
                }
            }
        } else {
            return false;
        }
    } catch (IOException | XMLStreamException | InvalidSyntaxException e) {
        log.error(e.getMessage());
        handleFailure(messageContext, e.getMessage());
    }
    return false;
}
 
Example #20
Source File: QueryValidator.java    From hypergraphql with Apache License 2.0 3 votes vote down vote up
public ValidatedQuery validateQuery(String query) {

        ValidatedQuery result = new ValidatedQuery();
        result.errors = validationErrors;

        Document document;

        try {

            document = parser.parseDocument(query);
            result.parsedQuery = document;

        } catch (Exception e) {
            ValidationError err = new ValidationError(ValidationErrorType.InvalidSyntax, new SourceLocation(0, 0), "Invalid query syntax.");
            validationErrors.add(err);
            result.valid = false;

            return result;
        }

        validationErrors.addAll(validator.validateDocument(schema, document));
        if (validationErrors.size() > 0) {
            result.valid = false;

            return result;

        }

        result.valid = true;

        return result;

    }
 
Example #21
Source File: QueryValidator.java    From hypergraphql with Apache License 2.0 3 votes vote down vote up
public ValidatedQuery validateQuery(String query) {

        ValidatedQuery result = new ValidatedQuery();
        result.errors = validationErrors;

        Document document;

        try {

            document = parser.parseDocument(query);
            result.parsedQuery = document;

        } catch (Exception e) {
            ValidationError err = new ValidationError(ValidationErrorType.InvalidSyntax, new SourceLocation(0, 0), "Invalid query syntax.");
            validationErrors.add(err);
            result.valid = false;

            return result;
        }

        validationErrors.addAll(validator.validateDocument(schema, document));
        if (validationErrors.size() > 0) {
            result.valid = false;

            return result;

        }

        result.valid = true;

        return result;

    }
 
Example #22
Source File: FederationSdlPrinter.java    From federation-jvm with MIT License 2 votes vote down vote up
/**
 * This can print an in memory GraphQL IDL document back to a logical schema definition.
 * If you want to turn a Introspection query result into a Document (and then into a printed
 * schema) then use {@link graphql.introspection.IntrospectionResultToSchema#createSchemaDefinition(java.util.Map)}
 * first to get the {@link graphql.language.Document} and then print that.
 *
 * @param schemaIDL the parsed schema IDL
 * @return the logical schema definition
 */
public String print(Document schemaIDL) {
    TypeDefinitionRegistry registry = new SchemaParser().buildRegistry(schemaIDL);
    return print(UnExecutableSchemaGenerator.makeUnExecutableSchema(registry));
}