Search in sources :

Example 1 with GraphQLRequestExecutionException

use of com.graphql_java_generator.exception.GraphQLRequestExecutionException in project graphql-maven-plugin-project by graphql-java-generator.

the class RestTemplateQueryExecutor method execute.

// @Override
// public <T> T execute(ObjectResponse objectResponse, Map<String, Object> parameters, Class<T> valueType)
// throws GraphQLRequestExecutionException {
// // TODO Auto-generated method stub
// return null;
// }
@Override
public <T extends GraphQLRequestObject> T execute(AbstractGraphQLRequest graphQLRequest, Map<String, Object> parameters, Class<T> valueType) throws GraphQLRequestExecutionException {
    String request = null;
    try {
        // Let's build the GraphQL request, to send to the server
        request = graphQLRequest.buildRequestAsString(parameters);
        logger.trace(GRAPHQL_MARKER, "Generated GraphQL request: {}", request);
        return doJsonRequestExecution(request, valueType);
    } catch (IOException e) {
        throw new GraphQLRequestExecutionException("Error when executing query <" + request + ">: " + e.getMessage(), e);
    }
}
Also used : IOException(java.io.IOException) GraphQLRequestExecutionException(com.graphql_java_generator.exception.GraphQLRequestExecutionException)

Example 2 with GraphQLRequestExecutionException

use of com.graphql_java_generator.exception.GraphQLRequestExecutionException in project graphql-maven-plugin-project by graphql-java-generator.

the class RestTemplateQueryExecutor method doJsonRequestExecution.

protected <T> T doJsonRequestExecution(String jsonRequest, Class<T> valueType) throws IOException, GraphQLRequestExecutionException {
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<String>(jsonRequest, headers);
    JsonResponseWrapper response = this.restTemplate.postForEntity(graphqlEndpoint, entity, JsonResponseWrapper.class).getBody();
    if (logger.isInfoEnabled()) {
        logger.trace("Parsed response data: {}", objectMapper.writeValueAsString(response.data));
        logger.trace("Parsed response errors: {}", objectMapper.writeValueAsString(response.errors));
    }
    if (response.errors == null || response.errors.size() == 0) {
        // No errors. Let's parse the data
        return objectMapper.treeToValue(response.data, valueType);
    } else {
        int nbErrors = 0;
        String agregatedMessage = null;
        for (com.graphql_java_generator.client.response.Error error : response.errors) {
            String msg = error.toString();
            nbErrors += 1;
            logger.error(GRAPHQL_MARKER, msg);
            if (agregatedMessage == null) {
                agregatedMessage = msg;
            } else {
                agregatedMessage += ", ";
                agregatedMessage += msg;
            }
        }
        if (nbErrors == 0) {
            throw new GraphQLRequestExecutionException("An unknown error occured");
        } else {
            throw new GraphQLRequestExecutionException(nbErrors + " errors occured: " + agregatedMessage);
        }
    }
}
Also used : HttpHeaders(org.springframework.http.HttpHeaders) JsonResponseWrapper(com.graphql_java_generator.client.response.JsonResponseWrapper) HttpEntity(org.springframework.http.HttpEntity) GraphQLRequestExecutionException(com.graphql_java_generator.exception.GraphQLRequestExecutionException)

Example 3 with GraphQLRequestExecutionException

use of com.graphql_java_generator.exception.GraphQLRequestExecutionException in project graphql-maven-plugin-project by graphql-java-generator.

the class GraphQLReactiveWebSocketHandler method onNext.

/**
 * The callback that will receive the messages from the web socket. It will map these JSON messages to the relevant
 * java class, and call the application callback with this java objects. This message can be any valid message,
 * according to the <a href="https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md">graphql-transport-ws
 * protocol</a>
 *
 * @param message
 *            The received JSON message
 */
@SuppressWarnings("unchecked")
public void onNext(WebSocketMessage message) {
    Map<String, Object> map;
    try {
        map = objectMapper.readValue(message.getPayloadAsText(), HashMap.class);
    } catch (JsonProcessingException e) {
        throw new RuntimeException("Error while reading '" + message.getPayloadAsText() + "' as a Map", e);
    }
    String id = (String) map.get("id");
    RequestData<?, ?> subData = null;
    if (id != null) {
        // Let's find the subscription that manages this uniqueIdOperation
        subData = registeredSubscriptions.get(id);
    }
    String type = (String) map.get("type");
    MessageType messageType = MessageType.resolve(type);
    if (messageType == null) {
        // Invalid message. We close the whole session, as described in the protocol
        GraphQlStatus.closeSession(this, session, GraphQlStatus.INVALID_MESSAGE_STATUS, "Invalid message: " + message.getPayloadAsText());
        return;
    }
    switch(messageType) {
        case CONNECTION_ACK:
            logger.trace("Received 'connection_ack' on web socket {}", session);
            // Ok, the connectionInit message has been sent. It's now allowed to send GraphQL
            // subscription on this web socket (see #executeSubscription() in this class)
            webSocketConnectionInitializationLatch.countDown();
            break;
        case NEXT:
            if (logger.isTraceEnabled())
                logger.trace("Received 'next' for id {} on web socket {} (payload={})", id, session, message.getPayloadAsText());
            if (id == null) {
                // Invalid message. We close the whole session, as described in the protocol
                GraphQlStatus.closeSession(this, session, GraphQlStatus.INVALID_MESSAGE_STATUS, "Invalid message (id is null): " + message.getPayloadAsText());
                return;
            }
            if (subData == null) {
                // Oups! The server sent a message with a uniqueIdOperation that is unknown by the client
                // There is nothing in the protocol for this case...
                // We ignore this message, and mark this unknown uniqueIdOperation as complete so that we receive no
                // other message for this uniqueIdOperation
                logger.warn("[graphql-transport-ws] Unknown uniqueIdOperation {} for web socket session {} (a 'complete' message is sent to the server to that he stops managing this uniqueIdOperation)", id, session);
                webSocketEmitter.emit(subData, session.textMessage(encode(id, MessageType.COMPLETE, null)));
            } else if (subData.isCompleted()) {
                logger.warn("Receive a message for a closed uniqueIdOperation ({}) on web socket {}", id, session);
            } else if (map.get("payload") == null) {
                String msg = "payload is mandatory for 'next' messages";
                logger.error(msg);
                subData.onError(new GraphQLRequestExecutionException(msg));
            } else if (!(map.get("payload") instanceof Map)) {
                String msg = "payload should be a Map, but <" + map.get("payload") + "> is not a Map";
                logger.error(msg);
                subData.onError(new GraphQLRequestExecutionException(msg));
            } else {
                subData.onNext((Map<String, Object>) map.get("payload"));
            }
            break;
        case COMPLETE:
            logger.trace("Received 'complete' for id {} on web socket {} (payload={})", id, session, message);
            subData.onComplete();
            break;
        case ERROR:
            logger.warn("Received 'error' for id {} on web socket {} (payload={})", id, session, message.getPayloadAsText());
            // The payload is a list of GraphQLErrors
            if (map.get("payload") instanceof Map) {
                // The payload is one error
                String msg = (String) ((Map<?, ?>) map.get("payload")).get("message");
                subData.onError(new GraphQLRequestExecutionException(msg));
            } else {
                // The payload is a list of errors
                List<Map<String, Object>> errors = (List<Map<String, Object>>) map.get("payload");
                List<String> errorMessages = errors.stream().map(e -> (String) e.get("message")).collect(Collectors.toList());
                subData.onError(new GraphQLRequestExecutionException(errorMessages));
            }
            break;
        default:
            logger.warn("Received non managed message '{}' for id {} on web socket {} (payload={})", type, id, session, message);
            // Oups! This message type exists in MessageType, but is not properly managed here.
            // This is an internal error.
            String msg = "Non managed message type '" + type + "'";
            if (subData != null) {
                subData.onError(new GraphQLRequestExecutionException(msg));
            } else {
                logger.error(msg);
            }
    }
}
Also used : Arrays(java.util.Arrays) Logger(org.slf4j.Logger) WebSocketSession(org.springframework.web.reactive.socket.WebSocketSession) JsonResponseWrapper(com.graphql_java_generator.client.response.JsonResponseWrapper) GraphQLRequestExecutionException(com.graphql_java_generator.exception.GraphQLRequestExecutionException) GraphqlUtils(com.graphql_java_generator.util.GraphqlUtils) CloseStatus(org.springframework.web.reactive.socket.CloseStatus) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LoggerFactory(org.slf4j.LoggerFactory) IOException(java.io.IOException) HashMap(java.util.HashMap) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Mono(reactor.core.publisher.Mono) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) TimeUnit(java.util.concurrent.TimeUnit) CountDownLatch(java.util.concurrent.CountDownLatch) Flux(reactor.core.publisher.Flux) List(java.util.List) Map(java.util.Map) WebSocketMessage(org.springframework.web.reactive.socket.WebSocketMessage) Error(com.graphql_java_generator.client.response.Error) Nullable(org.springframework.lang.Nullable) WebSocketHandler(org.springframework.web.reactive.socket.WebSocketHandler) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) List(java.util.List) GraphQLRequestExecutionException(com.graphql_java_generator.exception.GraphQLRequestExecutionException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with GraphQLRequestExecutionException

use of com.graphql_java_generator.exception.GraphQLRequestExecutionException in project graphql-maven-plugin-project by graphql-java-generator.

the class RequestExecutionImpl method execute.

/**
 * {@inheritDoc}
 */
@Override
public <R, T> SubscriptionClient execute(AbstractGraphQLRequest graphQLRequest, Map<String, Object> parameters, SubscriptionCallback<T> subscriptionCallback, Class<R> subscriptionType, Class<T> messageType) throws GraphQLRequestExecutionException {
    // This method accepts only subscription at a time (no query and no mutation)
    if (!graphQLRequest.getRequestType().equals(RequestType.subscription))
        throw new GraphQLRequestExecutionException("This method may be called only for subscriptions");
    // Subscription may be subscribed only once at a time, as this method allows only one subscriptionCallback
    if (graphQLRequest.getSubscription().getFields().size() != 1) {
        throw new GraphQLRequestExecutionException("This method may be called only for one subscription at a time, but there was " + graphQLRequest.getSubscription().getFields().size() + " subscriptions in this GraphQLRequest");
    }
    String subscriptionName = graphQLRequest.getSubscription().getFields().get(0).getName();
    String request = graphQLRequest.buildRequestAsString(parameters);
    logger.trace(GRAPHQL_MARKER, "Executing GraphQL subscription '{}' with request {}", subscriptionName, request);
    // Let's create and start the Web Socket
    // 
    // For internal test, we have a self-signed certificate. So we need to short cut certificate check.
    // DO NOT DO THAT IN PRODUCTION!
    boolean trustAll = (System.getProperty("com.graphql-java-generator.websocket.nosslcheck") != null);
    org.eclipse.jetty.util.ssl.SslContextFactory.Client sslContextFactory = new org.eclipse.jetty.util.ssl.SslContextFactory.Client(trustAll);
    HttpClient httpClient = new HttpClient(sslContextFactory);
    WebSocketClient wsClient = new WebSocketClient(httpClient);
    SubscriptionClientWebSocket<R, T> subscriptionClientWebSocket = new SubscriptionClientWebSocket<R, T>(request, subscriptionName, subscriptionCallback, subscriptionType, messageType, graphQLRequest.getGraphQLObjectMapper());
    URI uri = getWebSocketURI();
    try {
        wsClient.start();
        ClientUpgradeRequest clientUpgradeRequest = new ClientUpgradeRequest();
        wsClient.connect(subscriptionClientWebSocket, uri, clientUpgradeRequest);
        logger.debug("Connecting to {}", uri);
    } catch (Exception e) {
        String msg = "Error while opening the Web Socket connection to " + uri;
        logger.error(msg);
        throw new GraphQLRequestExecutionException(msg, e);
    }
    // Let's return the Web Socket client, so that the caller can stop it, when needed.
    return new SubscriptionClientImpl(wsClient);
}
Also used : WebSocketClient(org.eclipse.jetty.websocket.client.WebSocketClient) URI(java.net.URI) GraphQLRequestExecutionException(com.graphql_java_generator.exception.GraphQLRequestExecutionException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) HttpClient(org.eclipse.jetty.client.HttpClient) GraphQLRequestExecutionException(com.graphql_java_generator.exception.GraphQLRequestExecutionException) ClientUpgradeRequest(org.eclipse.jetty.websocket.client.ClientUpgradeRequest) WebSocketClient(org.eclipse.jetty.websocket.client.WebSocketClient) Client(javax.ws.rs.client.Client) HttpClient(org.eclipse.jetty.client.HttpClient)

Example 5 with GraphQLRequestExecutionException

use of com.graphql_java_generator.exception.GraphQLRequestExecutionException in project graphql-maven-plugin-project by graphql-java-generator.

the class RequestExecutionImpl method execute.

/**
 * {@inheritDoc}
 */
@Override
public <R extends GraphQLRequestObject> R execute(AbstractGraphQLRequest graphQLRequest, Map<String, Object> parameters, Class<R> dataResponseType) throws GraphQLRequestExecutionException {
    if (graphQLRequest.getRequestType().equals(RequestType.subscription))
        throw new GraphQLRequestExecutionException("This method may not be called for subscriptions");
    String jsonRequest = graphQLRequest.buildRequestAsString(parameters);
    try {
        logger.trace(GRAPHQL_MARKER, "Executing GraphQL request: {}", jsonRequest);
        Invocation.Builder invocationBuilder = webTarget.request(MediaType.APPLICATION_JSON);
        JsonResponseWrapper response = invocationBuilder.post(Entity.entity(jsonRequest, MediaType.APPLICATION_JSON), JsonResponseWrapper.class);
        return RequestExecutionSpringReactiveImpl.parseDataFromGraphQLServerResponse(graphQLRequest.getGraphQLObjectMapper(), response, dataResponseType);
    } catch (IOException e) {
        throw new GraphQLRequestExecutionException("Error when executing query <" + jsonRequest + ">: " + e.getMessage(), e);
    }
}
Also used : JsonResponseWrapper(com.graphql_java_generator.client.response.JsonResponseWrapper) Invocation(javax.ws.rs.client.Invocation) GraphQLRequestExecutionException(com.graphql_java_generator.exception.GraphQLRequestExecutionException) IOException(java.io.IOException)

Aggregations

GraphQLRequestExecutionException (com.graphql_java_generator.exception.GraphQLRequestExecutionException)21 Test (org.junit.jupiter.api.Test)10 IOException (java.io.IOException)6 JsonResponseWrapper (com.graphql_java_generator.client.response.JsonResponseWrapper)5 Execution (org.junit.jupiter.api.parallel.Execution)4 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)4 ArrayList (java.util.ArrayList)3 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 SubscriptionClient (com.graphql_java_generator.client.SubscriptionClient)2 PostInput (com.graphql_java_generator.samples.forum.client.graphql.forum.client.PostInput)2 TopicPostInput (com.graphql_java_generator.samples.forum.client.graphql.forum.client.TopicPostInput)2 URI (java.net.URI)2 URISyntaxException (java.net.URISyntaxException)2 Calendar (java.util.Calendar)2 GregorianCalendar (java.util.GregorianCalendar)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2