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);
}
}
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);
}
}
}
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);
}
}
}
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);
}
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);
}
}
Aggregations