Search in sources :

Example 1 with Document

use of graphql.language.Document in project graphql-java by graphql-java.

the class GraphqlAntlrToLanguage method visitDocument.

// MARKER START: Here GraphqlOperation.g4 specific methods begin
@Override
public Void visitDocument(GraphqlParser.DocumentContext ctx) {
    result = new Document();
    newNode(result, ctx);
    return super.visitDocument(ctx);
}
Also used : Document(graphql.language.Document)

Example 2 with Document

use of graphql.language.Document in project graphql-java by graphql-java.

the class IntrospectionResultToSchema method createSchemaDefinition.

/**
 * Returns a IDL Document that reprSesents 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 = new TypeName((String) queryType.get("name"));
    boolean nonDefaultQueryName = !"Query".equals(query.getName());
    SchemaDefinition schemaDefinition = new SchemaDefinition();
    schemaDefinition.getOperationTypeDefinitions().add(new OperationTypeDefinition("query", query));
    Map<String, Object> mutationType = (Map<String, Object>) schema.get("mutationType");
    boolean nonDefaultMutationName = false;
    if (mutationType != null) {
        TypeName mutation = new TypeName((String) mutationType.get("name"));
        nonDefaultMutationName = !"Mutation".equals(mutation.getName());
        schemaDefinition.getOperationTypeDefinitions().add(new OperationTypeDefinition("mutation", mutation));
    }
    Map<String, Object> subscriptionType = (Map<String, Object>) schema.get("subscriptionType");
    boolean nonDefaultSubscriptionName = false;
    if (subscriptionType != null) {
        TypeName subscription = new TypeName((String) subscriptionType.get("name"));
        nonDefaultSubscriptionName = !"Subscription".equals(subscription.getName());
        schemaDefinition.getOperationTypeDefinitions().add(new OperationTypeDefinition("subscription", subscription));
    }
    Document document = new Document();
    if (nonDefaultQueryName || nonDefaultMutationName || nonDefaultSubscriptionName) {
        document.getDefinitions().add(schemaDefinition);
    }
    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.getDefinitions().add(typeDefinition);
    }
    return document;
}
Also used : TypeName(graphql.language.TypeName) SchemaDefinition(graphql.language.SchemaDefinition) ArrayList(java.util.ArrayList) List(java.util.List) OperationTypeDefinition(graphql.language.OperationTypeDefinition) Document(graphql.language.Document) Map(java.util.Map) InputObjectTypeDefinition(graphql.language.InputObjectTypeDefinition) EnumTypeDefinition(graphql.language.EnumTypeDefinition) UnionTypeDefinition(graphql.language.UnionTypeDefinition) OperationTypeDefinition(graphql.language.OperationTypeDefinition) ScalarTypeDefinition(graphql.language.ScalarTypeDefinition) ObjectTypeDefinition(graphql.language.ObjectTypeDefinition) TypeDefinition(graphql.language.TypeDefinition) InterfaceTypeDefinition(graphql.language.InterfaceTypeDefinition)

Example 3 with Document

use of graphql.language.Document in project graphql-java by graphql-java.

the class SchemaDiff method diffSchemaImpl.

private void diffSchemaImpl(DiffSet diffSet, DifferenceReporter reporter) {
    Map<String, Object> oldApi = diffSet.getOld();
    Map<String, Object> newApi = diffSet.getNew();
    Document oldDoc = new IntrospectionResultToSchema().createSchemaDefinition(oldApi);
    Document newDoc = new IntrospectionResultToSchema().createSchemaDefinition(newApi);
    DiffCtx ctx = new DiffCtx(reporter, oldDoc, newDoc);
    Optional<SchemaDefinition> oldSchemaDef = getSchemaDef(oldDoc);
    Optional<SchemaDefinition> newSchemaDef = getSchemaDef(newDoc);
    // check query operation
    checkOperation(ctx, "query", oldSchemaDef, newSchemaDef);
    checkOperation(ctx, "mutation", oldSchemaDef, newSchemaDef);
    checkOperation(ctx, "subscription", oldSchemaDef, newSchemaDef);
    reporter.onEnd();
}
Also used : SchemaDefinition(graphql.language.SchemaDefinition) Document(graphql.language.Document) IntrospectionResultToSchema(graphql.introspection.IntrospectionResultToSchema)

Example 4 with Document

use of graphql.language.Document in project graphql-java by graphql-java.

the class GraphQL method parseAndValidate.

private PreparsedDocumentEntry parseAndValidate(ExecutionInput executionInput, GraphQLSchema graphQLSchema, InstrumentationState instrumentationState) {
    log.debug("Parsing query: '{}'...", executionInput.getQuery());
    ParseResult parseResult = parse(executionInput, graphQLSchema, instrumentationState);
    if (parseResult.isFailure()) {
        log.warn("Query failed to parse : '{}'", executionInput.getQuery());
        return new PreparsedDocumentEntry(toInvalidSyntaxError(parseResult.getException()));
    } else {
        final Document document = parseResult.getDocument();
        log.debug("Validating query: '{}'", executionInput.getQuery());
        final List<ValidationError> errors = validate(executionInput, document, graphQLSchema, instrumentationState);
        if (!errors.isEmpty()) {
            log.warn("Query failed to validate : '{}'", executionInput.getQuery());
            return new PreparsedDocumentEntry(errors);
        }
        return new PreparsedDocumentEntry(document);
    }
}
Also used : PreparsedDocumentEntry(graphql.execution.preparsed.PreparsedDocumentEntry) ValidationError(graphql.validation.ValidationError) Document(graphql.language.Document)

Example 5 with Document

use of graphql.language.Document 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)

Aggregations

Document (graphql.language.Document)9 Parser (graphql.parser.Parser)5 ValidationError (graphql.validation.ValidationError)3 SecurityContext (org.structr.common.SecurityContext)3 FrameworkException (org.structr.common.error.FrameworkException)3 GraphQLRequest (org.structr.core.graphql.GraphQLRequest)3 SchemaDefinition (graphql.language.SchemaDefinition)2 Validator (graphql.validation.Validator)2 IOException (java.io.IOException)2 LinkedHashMap (java.util.LinkedHashMap)2 Map (java.util.Map)2 ParseCancellationException (org.antlr.v4.runtime.misc.ParseCancellationException)2 GraphObject (org.structr.core.GraphObject)2 GraphQLWriter (org.structr.rest.serialization.GraphQLWriter)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