Search in sources :

Example 6 with Document

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

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

Example 8 with Document

use of graphql.language.Document in project structr by structr.

the class GraphQLServlet method handleGraphQLRequest.

// ----- private methods -----
private void handleGraphQLRequest(final HttpServletRequest request, final HttpServletResponse response, final String query) throws IOException, FrameworkException {
    final SecurityContext securityContext;
    final Authenticator authenticator;
    try {
        // isolate request authentication in a transaction
        try (final Tx tx = StructrApp.getInstance().tx()) {
            authenticator = config.getAuthenticator();
            securityContext = authenticator.initializeAndExamineRequest(request, response);
            tx.success();
        }
        final App app = StructrApp.getInstance(securityContext);
        if (securityContext != null) {
            // isolate write output
            try (final Tx tx = app.tx()) {
                final Document doc = GraphQLRequest.parse(new Parser(), query);
                if (doc != null) {
                    final List<ValidationError> errors = new Validator().validateDocument(SchemaService.getGraphQLSchema(), doc);
                    if (errors.isEmpty()) {
                        // no validation errors in query, do request
                        final GraphQLWriter graphQLWriter = new GraphQLWriter(true);
                        // no trailing semicolon so we dont trip MimeTypes.getContentTypeWithoutCharset
                        response.setContentType("application/json; charset=utf-8");
                        final Writer writer = response.getWriter();
                        graphQLWriter.stream(securityContext, writer, new GraphQLRequest(securityContext, doc, query));
                        // useful newline
                        writer.append("\n");
                    } else {
                        final Map<String, Object> map = new LinkedHashMap<>();
                        final Writer writer = response.getWriter();
                        final Gson gson = getGson();
                        map.put("errors", errors);
                        gson.toJson(map, writer);
                        // useful newline
                        writer.append("\n");
                        // send 422 status
                        response.setStatus(422);
                    }
                }
                tx.success();
            }
        }
    } catch (FrameworkException frameworkException) {
        // set status & write JSON output
        response.setStatus(frameworkException.getStatus());
        getGson().toJson(frameworkException, response.getWriter());
        response.getWriter().println();
    } catch (IllegalStateException | IllegalArgumentException iex) {
        final Map<String, Object> map = new LinkedHashMap<>();
        map.put("code", 422);
        map.put("message", iex.getMessage());
        // set status & write JSON output
        response.setStatus(422);
        getGson().toJson(map, response.getWriter());
        response.getWriter().println();
    } catch (UnsupportedOperationException uoe) {
        logger.warn("POST not supported");
        int code = HttpServletResponse.SC_BAD_REQUEST;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "POST not supported: " + uoe.getMessage()));
    } catch (Throwable t) {
        logger.warn("Exception in POST", t);
        int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        response.setStatus(code);
        response.getWriter().append(RestMethodResult.jsonError(code, "JsonSyntaxException in POST: " + t.getMessage()));
    } finally {
        try {
            // response.getWriter().flush();
            response.getWriter().close();
        } catch (Throwable t) {
            logger.warn("Unable to flush and close response: {}", t.getMessage());
        }
    }
}
Also used : StructrApp(org.structr.core.app.StructrApp) App(org.structr.core.app.App) Gson(com.google.gson.Gson) Document(graphql.language.Document) LinkedHashMap(java.util.LinkedHashMap) GraphQLRequest(org.structr.core.graphql.GraphQLRequest) GraphQLWriter(org.structr.rest.serialization.GraphQLWriter) ValidationError(graphql.validation.ValidationError) Authenticator(org.structr.core.auth.Authenticator) Tx(org.structr.core.graph.Tx) FrameworkException(org.structr.common.error.FrameworkException) Parser(graphql.parser.Parser) SecurityContext(org.structr.common.SecurityContext) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Validator(graphql.validation.Validator) Writer(java.io.Writer) GraphQLWriter(org.structr.rest.serialization.GraphQLWriter)

Example 9 with Document

use of graphql.language.Document in project structr by structr.

the class GraphQLCommand method processMessage.

@Override
public void processMessage(final WebSocketMessage webSocketData) {
    final StructrWebSocket socket = getWebSocket();
    final SecurityContext securityContext = socket.getSecurityContext();
    final List<GraphObject> result = new LinkedList<>();
    final String query = (String) webSocketData.getNodeData().get("query");
    if (query != null) {
        if (securityContext != null) {
            try {
                final Document doc = GraphQLRequest.parse(new Parser(), query);
                if (doc != null) {
                    final List<ValidationError> errors = new Validator().validateDocument(SchemaService.getGraphQLSchema(), doc);
                    if (errors.isEmpty()) {
                        // no validation errors in query, do request
                        result.addAll(createResult(securityContext, new GraphQLRequest(securityContext, doc, query)));
                    } else {
                        final Map<String, Object> map = new LinkedHashMap<>();
                        map.put("errors", errors);
                        logger.warn("Errors occured while processing GraphQL request.");
                        getWebSocket().send(MessageBuilder.status().data(map).code(422).message("Errors occured while processing GraphQL request.").build(), true);
                        return;
                    }
                }
            } catch (IOException ioex) {
                logger.warn("Could not process GraphQL request.", ioex);
                getWebSocket().send(MessageBuilder.status().code(422).message(ioex.getMessage()).build(), true);
                return;
            } catch (FrameworkException ex) {
                logger.warn("Could not process GraphQL request.", ex);
                getWebSocket().send(MessageBuilder.status().code(ex.getStatus()).message(ex.getMessage()).build(), true);
                return;
            }
        }
    }
    webSocketData.setResult(result);
    // send only over local connection (no broadcast)
    getWebSocket().send(webSocketData, true);
}
Also used : FrameworkException(org.structr.common.error.FrameworkException) StructrWebSocket(org.structr.websocket.StructrWebSocket) IOException(java.io.IOException) GraphObject(org.structr.core.GraphObject) Document(graphql.language.Document) LinkedList(java.util.LinkedList) Parser(graphql.parser.Parser) LinkedHashMap(java.util.LinkedHashMap) GraphQLRequest(org.structr.core.graphql.GraphQLRequest) SecurityContext(org.structr.common.SecurityContext) GraphObject(org.structr.core.GraphObject) ValidationError(graphql.validation.ValidationError) Validator(graphql.validation.Validator)

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