Search in sources :

Example 1 with Parser

use of graphql.parser.Parser in project graphql-java by graphql-java.

the class AstValueHelper method valueFromAst.

/**
 * Parses an AST value literal into the correct {@link graphql.language.Value} which
 * MUST be of the correct shape eg '"string"' or 'true' or '1' or '{ "object", "form" }'
 * or '[ "array", "form" ]' otherwise an exception is thrown
 *
 * @param astLiteral the string to parse an AST literal
 *
 * @return a valid Value
 *
 * @throws graphql.AssertException if the input can be parsed
 */
public static Value valueFromAst(String astLiteral) {
    // we use the parser to give us the AST elements as if we defined an inputType
    String toParse = "input X { x : String = " + astLiteral + "}";
    try {
        Document doc = new Parser().parseDocument(toParse);
        InputObjectTypeDefinition inputType = (InputObjectTypeDefinition) doc.getDefinitions().get(0);
        InputValueDefinition inputValueDefinition = inputType.getInputValueDefinitions().get(0);
        return inputValueDefinition.getDefaultValue();
    } catch (Exception e) {
        return Assert.assertShouldNeverHappen("valueFromAst of '%s' failed because of '%s'", astLiteral, e.getMessage());
    }
}
Also used : GraphQLException(graphql.GraphQLException) AssertException(graphql.AssertException) IntrospectionException(java.beans.IntrospectionException) InvocationTargetException(java.lang.reflect.InvocationTargetException) Parser(graphql.parser.Parser)

Example 2 with Parser

use of graphql.parser.Parser in project structr by structr.

the class WebSocketDataGSONAdapter method serialize.

// ~--- methods --------------------------------------------------------
@Override
public JsonElement serialize(WebSocketMessage src, Type typeOfSrc, JsonSerializationContext context) {
    JsonObject root = new JsonObject();
    JsonObject jsonNodeData = new JsonObject();
    JsonObject jsonRelData = new JsonObject();
    JsonArray removedProperties = new JsonArray();
    JsonArray modifiedProperties = new JsonArray();
    if (src.getCommand() != null) {
        root.add("command", new JsonPrimitive(src.getCommand()));
    }
    if (src.getId() != null) {
        root.add("id", new JsonPrimitive(src.getId()));
    }
    if (src.getPageId() != null) {
        root.add("pageId", new JsonPrimitive(src.getPageId()));
    }
    if (src.getMessage() != null) {
        root.add("message", new JsonPrimitive(src.getMessage()));
    }
    if (src.getJsonErrorObject() != null) {
        root.add("error", src.getJsonErrorObject());
    }
    if (src.getCode() != 0) {
        root.add("code", new JsonPrimitive(src.getCode()));
    }
    if (src.getSessionId() != null) {
        root.add("sessionId", new JsonPrimitive(src.getSessionId()));
    }
    if (src.getCallback() != null) {
        root.add("callback", new JsonPrimitive(src.getCallback()));
    }
    if (src.getButton() != null) {
        root.add("button", new JsonPrimitive(src.getButton()));
    }
    if (src.getParent() != null) {
        root.add("parent", new JsonPrimitive(src.getParent()));
    }
    if (src.getView() != null) {
        root.add("view", new JsonPrimitive(src.getView()));
    }
    if (src.getSortKey() != null) {
        root.add("sort", new JsonPrimitive(src.getSortKey()));
    }
    if (src.getSortOrder() != null) {
        root.add("order", new JsonPrimitive(src.getSortOrder()));
    }
    if (src.getPageSize() > 0) {
        root.add("pageSize", new JsonPrimitive(src.getPageSize()));
    }
    if (src.getPage() > 0) {
        root.add("page", new JsonPrimitive(src.getPage()));
    }
    JsonArray nodesWithChildren = new JsonArray();
    Set<String> nwc = src.getNodesWithChildren();
    if ((nwc != null) && !src.getNodesWithChildren().isEmpty()) {
        for (String nodeId : nwc) {
            nodesWithChildren.add(new JsonPrimitive(nodeId));
        }
        root.add("nodesWithChildren", nodesWithChildren);
    }
    // serialize session valid flag (output only)
    root.add("sessionValid", new JsonPrimitive(src.isSessionValid()));
    // UPDATE only, serialize only removed and modified properties and use the correct values
    if ((src.getGraphObject() != null)) {
        if (!src.getModifiedProperties().isEmpty()) {
            for (PropertyKey modifiedKey : src.getModifiedProperties()) {
                modifiedProperties.add(toJsonPrimitive(modifiedKey));
            }
            root.add("modifiedProperties", modifiedProperties);
        }
        if (!src.getRemovedProperties().isEmpty()) {
            for (PropertyKey removedKey : src.getRemovedProperties()) {
                removedProperties.add(toJsonPrimitive(removedKey));
            }
            root.add("removedProperties", removedProperties);
        }
    }
    // serialize node data
    if (src.getNodeData() != null) {
        for (Entry<String, Object> entry : src.getNodeData().entrySet()) {
            Object value = entry.getValue();
            String key = entry.getKey();
            if (value != null) {
                jsonNodeData.add(key, toJsonPrimitive(value));
            }
        }
        root.add("data", jsonNodeData);
    }
    // serialize relationship data
    if (src.getRelData() != null) {
        for (Entry<String, Object> entry : src.getRelData().entrySet()) {
            Object value = entry.getValue();
            String key = entry.getKey();
            if (value != null) {
                jsonRelData.add(key, toJsonPrimitive(value));
            }
        }
        root.add("relData", jsonRelData);
    }
    // serialize result list
    if (src.getResult() != null) {
        if ("GRAPHQL".equals(src.getCommand())) {
            try {
                if (src.getResult() != null && !src.getResult().isEmpty()) {
                    final GraphObject firstResultObject = src.getResult().get(0);
                    final SecurityContext securityContext = firstResultObject.getSecurityContext();
                    final StringWriter output = new StringWriter();
                    final String query = (String) src.getNodeData().get("query");
                    final Document doc = GraphQLRequest.parse(new Parser(), query);
                    final GraphQLWriter graphQLWriter = new GraphQLWriter(false);
                    graphQLWriter.stream(securityContext, output, new GraphQLRequest(securityContext, doc, query));
                    JsonElement graphQLResult = new JsonParser().parse(output.toString());
                    root.add("result", graphQLResult);
                } else {
                    root.add("result", new JsonArray());
                }
            } catch (IOException | FrameworkException ex) {
                logger.warn("Unable to set process GraphQL query", ex);
            }
        } else {
            if (src.getView() != null) {
                try {
                    propertyView.set(null, src.getView());
                } catch (FrameworkException fex) {
                    logger.warn("Unable to set property view", fex);
                }
            } else {
                try {
                    propertyView.set(null, PropertyView.Ui);
                } catch (FrameworkException fex) {
                    logger.warn("Unable to set property view", fex);
                }
            }
            JsonArray result = new JsonArray();
            for (GraphObject obj : src.getResult()) {
                result.add(graphObjectSerializer.serialize(obj, System.currentTimeMillis()));
            }
            root.add("result", result);
        }
        root.add("rawResultCount", toJsonPrimitive(src.getRawResultCount()));
    }
    return root;
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) GraphObject(org.structr.core.GraphObject) Document(graphql.language.Document) JsonParser(com.google.gson.JsonParser) Parser(graphql.parser.Parser) JsonArray(com.google.gson.JsonArray) GraphQLRequest(org.structr.core.graphql.GraphQLRequest) GraphQLWriter(org.structr.rest.serialization.GraphQLWriter) StringWriter(java.io.StringWriter) JsonElement(com.google.gson.JsonElement) SecurityContext(org.structr.common.SecurityContext) JsonObject(com.google.gson.JsonObject) GraphObject(org.structr.core.GraphObject) PropertyKey(org.structr.core.property.PropertyKey) JsonParser(com.google.gson.JsonParser)

Example 3 with Parser

use of graphql.parser.Parser in project graphql-java by graphql-java.

the class GraphQL method parseValidateAndExecute.

private CompletableFuture<ExecutionResult> parseValidateAndExecute(ExecutionInput executionInput, GraphQLSchema graphQLSchema, InstrumentationState instrumentationState) {
    AtomicReference<ExecutionInput> executionInputRef = new AtomicReference<>(executionInput);
    PreparsedDocumentEntry preparsedDoc = preparsedDocumentProvider.get(executionInput.getQuery(), transformedQuery -> {
        // if they change the original query in the pre-parser, then we want to see it downstream from then on
        executionInputRef.set(executionInput.transform(bldr -> bldr.query(transformedQuery)));
        return parseAndValidate(executionInputRef.get(), graphQLSchema, instrumentationState);
    });
    if (preparsedDoc.hasErrors()) {
        return CompletableFuture.completedFuture(new ExecutionResultImpl(preparsedDoc.getErrors()));
    }
    return execute(executionInputRef.get(), preparsedDoc.getDocument(), graphQLSchema, instrumentationState);
}
Also used : Execution(graphql.execution.Execution) ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) AbortExecutionException(graphql.execution.AbortExecutionException) ExecutionStrategy(graphql.execution.ExecutionStrategy) InstrumentationExecutionParameters(graphql.execution.instrumentation.parameters.InstrumentationExecutionParameters) LoggerFactory(org.slf4j.LoggerFactory) CompletableFuture(java.util.concurrent.CompletableFuture) UnaryOperator(java.util.function.UnaryOperator) InstrumentationState(graphql.execution.instrumentation.InstrumentationState) PreparsedDocumentEntry(graphql.execution.preparsed.PreparsedDocumentEntry) AtomicReference(java.util.concurrent.atomic.AtomicReference) ExecutionId(graphql.execution.ExecutionId) Parser(graphql.parser.Parser) SubscriptionExecutionStrategy(graphql.execution.SubscriptionExecutionStrategy) Map(java.util.Map) AsyncExecutionStrategy(graphql.execution.AsyncExecutionStrategy) GraphQLSchema(graphql.schema.GraphQLSchema) NoOpPreparsedDocumentProvider(graphql.execution.preparsed.NoOpPreparsedDocumentProvider) Logger(org.slf4j.Logger) PreparsedDocumentProvider(graphql.execution.preparsed.PreparsedDocumentProvider) CompletionException(java.util.concurrent.CompletionException) InvalidSyntaxError.toInvalidSyntaxError(graphql.InvalidSyntaxError.toInvalidSyntaxError) ExecutionIdProvider(graphql.execution.ExecutionIdProvider) InstrumentationContext(graphql.execution.instrumentation.InstrumentationContext) Consumer(java.util.function.Consumer) InstrumentationValidationParameters(graphql.execution.instrumentation.parameters.InstrumentationValidationParameters) Document(graphql.language.Document) ValidationError(graphql.validation.ValidationError) List(java.util.List) Instrumentation(graphql.execution.instrumentation.Instrumentation) Assert.assertNotNull(graphql.Assert.assertNotNull) SimpleInstrumentation(graphql.execution.instrumentation.SimpleInstrumentation) AsyncSerialExecutionStrategy(graphql.execution.AsyncSerialExecutionStrategy) Validator(graphql.validation.Validator) PreparsedDocumentEntry(graphql.execution.preparsed.PreparsedDocumentEntry) AtomicReference(java.util.concurrent.atomic.AtomicReference)

Example 4 with Parser

use of graphql.parser.Parser in project graphql-java by graphql-java.

the class GraphQL method parse.

private ParseResult parse(ExecutionInput executionInput, GraphQLSchema graphQLSchema, InstrumentationState instrumentationState) {
    InstrumentationContext<Document> parseInstrumentation = instrumentation.beginParse(new InstrumentationExecutionParameters(executionInput, graphQLSchema, instrumentationState));
    Parser parser = new Parser();
    Document document;
    try {
        document = parser.parseDocument(executionInput.getQuery());
    } catch (ParseCancellationException e) {
        parseInstrumentation.onCompleted(null, e);
        return ParseResult.ofError(e);
    }
    parseInstrumentation.onCompleted(document, null);
    return ParseResult.of(document);
}
Also used : ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) InstrumentationExecutionParameters(graphql.execution.instrumentation.parameters.InstrumentationExecutionParameters) Document(graphql.language.Document) Parser(graphql.parser.Parser)

Example 5 with Parser

use of graphql.parser.Parser in project graphql-java by graphql-java.

the class SchemaParser method parse.

/**
 * Parse a string of schema definitions and create a {@link TypeDefinitionRegistry}
 *
 * @param schemaInput the schema string to parse
 *
 * @return registry of type definitions
 *
 * @throws SchemaProblem if there are problems compiling the schema definitions
 */
public TypeDefinitionRegistry parse(String schemaInput) throws SchemaProblem {
    try {
        Parser parser = new Parser();
        Document document = parser.parseDocument(schemaInput);
        return buildRegistry(document);
    } catch (ParseCancellationException e) {
        throw handleParseException(e);
    }
}
Also used : ParseCancellationException(org.antlr.v4.runtime.misc.ParseCancellationException) Document(graphql.language.Document) Parser(graphql.parser.Parser)

Aggregations

Parser (graphql.parser.Parser)7 Document (graphql.language.Document)6 ValidationError (graphql.validation.ValidationError)3 Validator (graphql.validation.Validator)3 ParseCancellationException (org.antlr.v4.runtime.misc.ParseCancellationException)3 SecurityContext (org.structr.common.SecurityContext)3 FrameworkException (org.structr.common.error.FrameworkException)3 GraphQLRequest (org.structr.core.graphql.GraphQLRequest)3 InstrumentationExecutionParameters (graphql.execution.instrumentation.parameters.InstrumentationExecutionParameters)2 IOException (java.io.IOException)2 LinkedHashMap (java.util.LinkedHashMap)2 Map (java.util.Map)2 Gson (com.google.gson.Gson)1 JsonArray (com.google.gson.JsonArray)1 JsonElement (com.google.gson.JsonElement)1 JsonObject (com.google.gson.JsonObject)1 JsonParser (com.google.gson.JsonParser)1 JsonPrimitive (com.google.gson.JsonPrimitive)1 Assert.assertNotNull (graphql.Assert.assertNotNull)1 AssertException (graphql.AssertException)1