Implement GraphQLQueryBodyParameter and GraphQLQueryBody annotation (#1896)

* implement GraphQLQueryBodyParameter and GraphQLQueryBody annotation

* GraphQLQueryBodyParameter to recognize application/graphql

* fix 500 error on method without @GraphQLQueryBody

* refactor to processGraphQlGetRequest and processGraphQlPostRequest

* add testGraphPostContentTypeJson and testGraphPostContentTypeGraphql to GraphQLR4RawTest

* fix imports
This commit is contained in:
Ibrohim Kholilul Islam 2020-07-16 20:25:26 +07:00 committed by GitHub
parent 962055e092
commit 5a79304893
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 267 additions and 26 deletions

View File

@ -20,6 +20,9 @@ package ca.uhn.fhir.rest.annotation;
* #L%
*/
import ca.uhn.fhir.rest.api.RequestTypeEnum;
import org.hl7.fhir.instance.model.api.IBaseResource;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@ -32,4 +35,5 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(value= ElementType.METHOD)
public @interface GraphQL {
RequestTypeEnum type() default RequestTypeEnum.GET;
}

View File

@ -37,6 +37,6 @@ import java.lang.annotation.Target;
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface GraphQLQuery {
public @interface GraphQLQueryBody {
// ignore
}

View File

@ -0,0 +1,42 @@
package ca.uhn.fhir.rest.annotation;
/*-
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2020 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the LBoicense.
* #L%
*/
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation should be placed on the parameter of a
* {@link GraphQL @GraphQL} annotated method. The given
* parameter will be populated with the specific graphQL
* query being requested.
*
* <p>
* This parameter should be of type {@link String}
* </p>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface GraphQLQueryUrl {
// ignore
}

View File

@ -66,6 +66,7 @@ public class Constants {
public static final String CT_HTML = "text/html";
public static final String CT_HTML_WITH_UTF8 = "text/html" + CHARSET_UTF8_CTSUFFIX;
public static final String CT_JSON = "application/json";
public static final String CT_GRAPHQL = "application/graphql";
public static final String CT_JSON_PATCH = "application/json-patch+json";
public static final String CT_OCTET_STREAM = "application/octet-stream";
public static final String CT_TEXT = "text/plain";

View File

@ -25,9 +25,12 @@ import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.FhirVersionEnum;
import ca.uhn.fhir.context.support.IValidationSupport;
import ca.uhn.fhir.rest.annotation.GraphQL;
import ca.uhn.fhir.rest.annotation.GraphQLQuery;
import ca.uhn.fhir.rest.annotation.GraphQLQueryBody;
import ca.uhn.fhir.rest.annotation.GraphQLQueryUrl;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.Initialize;
import ca.uhn.fhir.rest.annotation.ResourceParam;
import ca.uhn.fhir.rest.api.RequestTypeEnum;
import ca.uhn.fhir.rest.server.RestfulServer;
import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
@ -107,9 +110,23 @@ public class GraphQLProvider {
myStorageServices = theStorageServices;
}
@GraphQL
public String processGraphQlRequest(ServletRequestDetails theRequestDetails, @IdParam IIdType theId, @GraphQLQuery String theQuery) {
@GraphQL(type=RequestTypeEnum.GET)
public String processGraphQlGetRequest(ServletRequestDetails theRequestDetails, @IdParam IIdType theId, @GraphQLQueryUrl String queryUrl) {
if (queryUrl != null) {
return processGraphQLRequest(theRequestDetails, theId, queryUrl);
}
throw new InvalidRequestException("Unable to parse empty GraphQL expression");
}
@GraphQL(type=RequestTypeEnum.POST)
public String processGraphQlPostRequest(ServletRequestDetails theRequestDetails, @IdParam IIdType theId, @GraphQLQueryBody String queryBody) {
if (queryBody != null) {
return processGraphQLRequest(theRequestDetails, theId, queryBody);
}
throw new InvalidRequestException("Unable to parse empty GraphQL expression");
}
public String processGraphQLRequest(ServletRequestDetails theRequestDetails, IIdType theId, String theQuery) {
IGraphQLEngine engine = engineFactory.get();
engine.setAppInfo(theRequestDetails);
engine.setServices(myStorageServices);

View File

@ -331,7 +331,7 @@ public abstract class BaseMethodBinding<T> {
}
if (graphQL != null) {
return new GraphQLMethodBinding(theMethod, theContext, theProvider);
return new GraphQLMethodBinding(theMethod, graphQL.type(), theContext, theProvider);
}
Class<? extends IBaseResource> returnType;

View File

@ -23,7 +23,10 @@ package ca.uhn.fhir.rest.server.method;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.interceptor.api.HookParams;
import ca.uhn.fhir.interceptor.api.Pointcut;
import ca.uhn.fhir.rest.annotation.GraphQLQueryBody;
import ca.uhn.fhir.rest.annotation.GraphQLQueryUrl;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.api.RequestTypeEnum;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
import ca.uhn.fhir.rest.api.server.IRestfulServer;
import ca.uhn.fhir.rest.api.server.RequestDetails;
@ -43,11 +46,17 @@ import java.lang.reflect.Method;
public class GraphQLMethodBinding extends BaseMethodBinding<String> {
private final Integer myIdParamIndex;
private final Integer myQueryUrlParamIndex;
private final Integer myQueryBodyParamIndex;
private final RequestTypeEnum myMethodRequestType;
public GraphQLMethodBinding(Method theMethod, FhirContext theContext, Object theProvider) {
public GraphQLMethodBinding(Method theMethod, RequestTypeEnum theMethodRequestType, FhirContext theContext, Object theProvider) {
super(theMethod, theContext, theProvider);
myIdParamIndex = ParameterUtil.findIdParameterIndex(theMethod, theContext);
myQueryUrlParamIndex = ParameterUtil.findParamAnnotationIndex(theMethod, GraphQLQueryUrl.class);
myQueryBodyParamIndex = ParameterUtil.findParamAnnotationIndex(theMethod, GraphQLQueryBody.class);
myMethodRequestType = theMethodRequestType;
}
@Override
@ -68,13 +77,23 @@ public class GraphQLMethodBinding extends BaseMethodBinding<String> {
@Override
public MethodMatchEnum incomingServerRequestMatchesMethod(RequestDetails theRequest) {
if (Constants.OPERATION_NAME_GRAPHQL.equals(theRequest.getOperation())) {
if (Constants.OPERATION_NAME_GRAPHQL.equals(theRequest.getOperation()) && myMethodRequestType.equals(theRequest.getRequestType())) {
return MethodMatchEnum.EXACT;
}
return MethodMatchEnum.NONE;
}
private String getQueryValue(Object[] methodParams) {
switch (myMethodRequestType) {
case POST:
return (String) methodParams[myQueryBodyParamIndex];
case GET:
return (String) methodParams[myQueryUrlParamIndex];
}
return null;
}
@Override
public Object invokeServer(IRestfulServer<?> theServer, RequestDetails theRequest) throws BaseServerResponseException, IOException {
Object[] methodParams = createMethodParams(theRequest);
@ -82,7 +101,7 @@ public class GraphQLMethodBinding extends BaseMethodBinding<String> {
methodParams[myIdParamIndex] = theRequest.getId();
}
Object response = invokeServerMethod(theServer, theRequest, methodParams);
String responseString = (String) invokeServerMethod(theServer, theRequest, methodParams);
int statusCode = Constants.STATUS_HTTP_200_OK;
String statusMessage = Constants.HTTP_STATUS_NAMES.get(statusCode);
@ -90,20 +109,19 @@ public class GraphQLMethodBinding extends BaseMethodBinding<String> {
String charset = Constants.CHARSET_NAME_UTF8;
boolean respondGzip = theRequest.isRespondGzip();
String responseString = (String) response;
HttpServletRequest servletRequest=null;
HttpServletResponse servletResponse=null;
HttpServletRequest servletRequest = null;
HttpServletResponse servletResponse = null;
if (theRequest instanceof ServletRequestDetails) {
servletRequest = ((ServletRequestDetails) theRequest).getServletRequest();
servletResponse = ((ServletRequestDetails) theRequest).getServletResponse();
}
String graphQLQuery = getQueryValue(methodParams);
// Interceptor call: SERVER_OUTGOING_GRAPHQL_RESPONSE
HookParams params = new HookParams()
.add(RequestDetails.class, theRequest)
.addIfMatchesType(ServletRequestDetails.class, theRequest)
.add(String.class, theRequest.getParameters().get(Constants.PARAM_GRAPHQL_QUERY)[0])
.add(String.class, graphQLQuery)
.add(String.class, responseString)
.add(HttpServletRequest.class, servletRequest)
.add(HttpServletResponse.class, servletResponse);
@ -128,7 +146,6 @@ public class GraphQLMethodBinding extends BaseMethodBinding<String> {
writer.write(responseString);
writer.close();
return null;
}
}

View File

@ -0,0 +1,91 @@
package ca.uhn.fhir.rest.server.method;
/*
* #%L
* HAPI FHIR - Server Framework
* %%
* Copyright (C) 2014 - 2020 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.parser.json.JsonLikeObject;
import ca.uhn.fhir.parser.json.JsonLikeStructure;
import ca.uhn.fhir.parser.json.JsonLikeValue;
import ca.uhn.fhir.parser.json.jackson.JacksonStructure;
import ca.uhn.fhir.rest.annotation.Count;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.api.server.RequestDetails;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.io.IOUtils;
import javax.annotation.Nullable;
import java.io.IOException;
import java.io.Reader;
import java.lang.reflect.Method;
import java.util.Collection;
import static ca.uhn.fhir.rest.api.Constants.CT_GRAPHQL;
import static ca.uhn.fhir.rest.api.Constants.CT_JSON;
import static ca.uhn.fhir.rest.server.method.ResourceParameter.createRequestReader;
public class GraphQLQueryBodyParameter implements IParameter {
private Class<?> myType;
@Override
public Object translateQueryParametersIntoServerArgument(RequestDetails theRequest, BaseMethodBinding<?> theMethodBinding) throws InternalErrorException, InvalidRequestException {
String ctValue = theRequest.getHeader(Constants.HEADER_CONTENT_TYPE);
Reader requestReader = createRequestReader(theRequest);
if (CT_JSON.equals(ctValue)) {
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(requestReader);
if (jsonNode != null && jsonNode.get("query") != null) {
return jsonNode.get("query").asText();
}
} catch (IOException e) {
throw new InternalErrorException(e);
}
}
if (CT_GRAPHQL.equals(ctValue)) {
try {
return IOUtils.toString(requestReader);
} catch (IOException e) {
throw new InternalErrorException(e);
}
}
return null;
}
@Override
public void initializeTypes(Method theMethod, Class<? extends Collection<?>> theOuterCollectionType, Class<? extends Collection<?>> theInnerCollectionType, Class<?> theParameterType) {
if (theOuterCollectionType != null) {
throw new ConfigurationException("Method '" + theMethod.getName() + "' in type '" +theMethod.getDeclaringClass().getCanonicalName()+ "' is annotated with @" + Count.class.getName() + " but can not be of collection type");
}
if (!String.class.equals(theParameterType)) {
throw new ConfigurationException("Method '" + theMethod.getName() + "' in type '" +theMethod.getDeclaringClass().getCanonicalName()+ "' is annotated with @" + Count.class.getName() + " but type '" + theParameterType + "' is an invalid type, must be one of Integer or IntegerType");
}
myType = theParameterType;
}
}

View File

@ -34,7 +34,7 @@ import org.apache.commons.lang3.StringUtils;
import java.lang.reflect.Method;
import java.util.Collection;
public class GraphQLQueryParameter implements IParameter {
public class GraphQLQueryUrlParameter implements IParameter {
private Class<?> myType;

View File

@ -213,8 +213,10 @@ public class MethodUtil {
((AtParameter) param).setType(theContext, parameterType, innerCollectionType, outerCollectionType);
} else if (nextAnnotation instanceof Count) {
param = new CountParameter();
} else if (nextAnnotation instanceof GraphQLQuery) {
param = new GraphQLQueryParameter();
} else if (nextAnnotation instanceof GraphQLQueryUrl) {
param = new GraphQLQueryUrlParameter();
} else if (nextAnnotation instanceof GraphQLQueryBody) {
param = new GraphQLQueryBodyParameter();
} else if (nextAnnotation instanceof Sort) {
param = new SortParameter(theContext);
} else if (nextAnnotation instanceof TransactionParam) {

View File

@ -6,7 +6,7 @@ import ca.uhn.fhir.interceptor.api.HookParams;
import ca.uhn.fhir.interceptor.api.IInterceptorBroadcaster;
import ca.uhn.fhir.interceptor.api.Pointcut;
import ca.uhn.fhir.rest.annotation.GraphQL;
import ca.uhn.fhir.rest.annotation.GraphQLQuery;
import ca.uhn.fhir.rest.annotation.GraphQLQueryUrl;
import ca.uhn.fhir.rest.annotation.History;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.Operation;
@ -226,7 +226,7 @@ public class AuthorizationInterceptorDstu3Test {
}
@GraphQL
public String processGraphQlRequest(ServletRequestDetails theRequestDetails, @IdParam IIdType theId, @GraphQLQuery String theQuery) {
public String processGraphQlRequest(ServletRequestDetails theRequestDetails, @IdParam IIdType theId, @GraphQLQueryUrl String theQuery) {
ourHitMethod = true;
return "{'foo':'bar'}";
}

View File

@ -2,12 +2,14 @@ package ca.uhn.fhir.rest.server;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.rest.annotation.GraphQL;
import ca.uhn.fhir.rest.annotation.GraphQLQuery;
import ca.uhn.fhir.rest.annotation.GraphQLQueryUrl;
import ca.uhn.fhir.rest.annotation.GraphQLQueryBody;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.OptionalParam;
import ca.uhn.fhir.rest.annotation.Search;
import ca.uhn.fhir.rest.api.Constants;
import ca.uhn.fhir.rest.api.EncodingEnum;
import ca.uhn.fhir.rest.api.RequestTypeEnum;
import ca.uhn.fhir.rest.param.TokenAndListParam;
import ca.uhn.fhir.test.utilities.JettyUtil;
import ca.uhn.fhir.util.TestUtil;
@ -15,6 +17,8 @@ import ca.uhn.fhir.util.UrlUtil;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
@ -114,6 +118,62 @@ public class GraphQLR4RawTest {
}
@Test
public void testGraphPostContentTypeJson() throws Exception {
ourNextRetVal = "{\"foo\"}";
HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/123/$graphql");
StringEntity entity = new StringEntity("{\"query\": \"{name{family,given}}\"}");
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
CloseableHttpResponse status = ourClient.execute(httpPost);
try {
String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8);
ourLog.info(responseContent);
assertEquals(200, status.getStatusLine().getStatusCode());
assertEquals("{\"foo\"}", responseContent);
assertThat(status.getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue(), startsWith("application/json"));
assertEquals("Patient/123", ourLastId.getValue());
assertEquals("{name{family,given}}", ourLastQuery);
} finally {
IOUtils.closeQuietly(status.getEntity().getContent());
}
}
@Test
public void testGraphPostContentTypeGraphql() throws Exception {
ourNextRetVal = "{\"foo\"}";
HttpPost httpPost = new HttpPost("http://localhost:" + ourPort + "/Patient/123/$graphql");
StringEntity entity = new StringEntity("{name{family,given}}");
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/graphql");
CloseableHttpResponse status = ourClient.execute(httpPost);
try {
String responseContent = IOUtils.toString(status.getEntity().getContent(), StandardCharsets.UTF_8);
ourLog.info(responseContent);
assertEquals(200, status.getStatusLine().getStatusCode());
assertEquals("{\"foo\"}", responseContent);
assertThat(status.getFirstHeader(Constants.HEADER_CONTENT_TYPE).getValue(), startsWith("application/json"));
assertEquals("Patient/123", ourLastId.getValue());
assertEquals("{name{family,given}}", ourLastQuery);
} finally {
IOUtils.closeQuietly(status.getEntity().getContent());
}
}
@Test
public void testGraphInstanceUnknownType() throws Exception {
ourNextRetVal = "{\"foo\"}";
@ -157,9 +217,16 @@ public class GraphQLR4RawTest {
public static class MyGraphQLProvider {
@GraphQL(type=RequestTypeEnum.GET)
public String processGet(@IdParam IdType theId, @GraphQLQueryUrl String theQuery) {
ourMethodCount++;
ourLastId = theId;
ourLastQuery = theQuery;
return ourNextRetVal;
}
@GraphQL
public String process(@IdParam IdType theId, @GraphQLQuery String theQuery) {
@GraphQL(type=RequestTypeEnum.POST)
public String processPost(@IdParam IdType theId, @GraphQLQueryBody String theQuery) {
ourMethodCount++;
ourLastId = theId;
ourLastQuery = theQuery;

View File

@ -6,7 +6,7 @@ import ca.uhn.fhir.interceptor.api.IAnonymousInterceptor;
import ca.uhn.fhir.interceptor.api.IInterceptorBroadcaster;
import ca.uhn.fhir.interceptor.api.Pointcut;
import ca.uhn.fhir.rest.annotation.GraphQL;
import ca.uhn.fhir.rest.annotation.GraphQLQuery;
import ca.uhn.fhir.rest.annotation.GraphQLQueryUrl;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.Operation;
import ca.uhn.fhir.rest.annotation.Read;
@ -858,7 +858,7 @@ public class ResponseHighlightingInterceptorTest {
public static class GraphQLProvider {
@GraphQL
public String processGraphQlRequest(ServletRequestDetails theRequestDetails, @IdParam IIdType theId, @GraphQLQuery String theQuery) {
public String processGraphQlRequest(ServletRequestDetails theRequestDetails, @IdParam IIdType theId, @GraphQLQueryUrl String theQuery) {
return "{\"foo\":\"bar\"}";
}
}

View File

@ -10,7 +10,7 @@ import ca.uhn.fhir.rest.annotation.ConditionalUrlParam;
import ca.uhn.fhir.rest.annotation.Create;
import ca.uhn.fhir.rest.annotation.Delete;
import ca.uhn.fhir.rest.annotation.GraphQL;
import ca.uhn.fhir.rest.annotation.GraphQLQuery;
import ca.uhn.fhir.rest.annotation.GraphQLQueryUrl;
import ca.uhn.fhir.rest.annotation.History;
import ca.uhn.fhir.rest.annotation.IdParam;
import ca.uhn.fhir.rest.annotation.Operation;
@ -3888,7 +3888,7 @@ public class AuthorizationInterceptorR4Test {
}
@GraphQL
public String processGraphQlRequest(ServletRequestDetails theRequestDetails, @IdParam IIdType theId, @GraphQLQuery String theQuery) {
public String processGraphQlRequest(ServletRequestDetails theRequestDetails, @IdParam IIdType theId, @GraphQLQueryUrl String theQuery) {
ourHitMethod = true;
return "{'foo':'bar'}";
}