graphql.kickstart.servlet.GraphQLMultipartInvocationInputParser Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of graphql-java-servlet Show documentation
Show all versions of graphql-java-servlet Show documentation
relay.js-compatible GraphQL servlet
package graphql.kickstart.servlet;
import static java.util.stream.Collectors.joining;
import graphql.GraphQLException;
import graphql.kickstart.execution.GraphQLObjectMapper;
import graphql.kickstart.execution.GraphQLRequest;
import graphql.kickstart.execution.context.ContextSetting;
import graphql.kickstart.execution.input.GraphQLInvocationInput;
import graphql.kickstart.servlet.core.internal.VariableMapper;
import graphql.kickstart.servlet.input.GraphQLInvocationInputFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import lombok.extern.slf4j.Slf4j;
@Slf4j
class GraphQLMultipartInvocationInputParser extends AbstractGraphQLInvocationInputParser {
private static final String[] MULTIPART_KEYS = new String[] {"operations", "graphql", "query"};
GraphQLMultipartInvocationInputParser(
GraphQLInvocationInputFactory invocationInputFactory,
GraphQLObjectMapper graphQLObjectMapper,
ContextSetting contextSetting) {
super(invocationInputFactory, graphQLObjectMapper, contextSetting);
}
@Override
public GraphQLInvocationInput getGraphQLInvocationInput(
HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
final Map> parts =
request.getParts().stream().collect(Collectors.groupingBy(Part::getName));
for (String key : MULTIPART_KEYS) {
// Check to see if there is a part under the key we seek
if (!parts.containsKey(key)) {
continue;
}
final Optional queryItem = findPart(parts);
if (!queryItem.isPresent()) {
log.info("Bad POST multipart request: no part named {}", Arrays.toString(MULTIPART_KEYS));
throw new GraphQLException(
"Bad POST multipart request: no part named " + Arrays.toString(MULTIPART_KEYS));
}
return getGraphQLInvocationInput(request, response, parts, key, queryItem.get());
}
log.info("Bad POST multipart request: no part named {}", Arrays.toString(MULTIPART_KEYS));
throw new GraphQLException(
"Bad POST multipart request: no part named " + Arrays.toString(MULTIPART_KEYS));
} catch (ServletException e) {
throw new IOException("Cannot get parts from request", e);
}
}
private GraphQLInvocationInput getGraphQLInvocationInput(
HttpServletRequest request,
HttpServletResponse response,
Map> parts,
String key,
Part queryItem)
throws IOException {
InputStream inputStream = queryItem.getInputStream();
final Optional