add test + drop implementation implementation for StaticJaxRsServer

This commit is contained in:
petervanhoute 2015-10-29 15:57:30 +01:00
parent 367163c46a
commit 54ad29edc1
19 changed files with 916 additions and 1117 deletions

View File

@ -79,7 +79,7 @@ public abstract class AbstractJaxRsConformanceProvider extends AbstractJaxRsProv
serverConfiguration.setServerBindings(serverBindings);
serverConfiguration.setResourceBindings(new LinkedList<ResourceBinding>(myResourceNameToBinding.values()));
HardcodedServerAddressStrategy hardcodedServerAddressStrategy = new HardcodedServerAddressStrategy();
hardcodedServerAddressStrategy.setValue(getBaseUri());
hardcodedServerAddressStrategy.setValue(getBaseForServer());
serverConfiguration.setServerAddressStrategy(hardcodedServerAddressStrategy);
ServerConformanceProvider serverConformanceProvider = new ServerConformanceProvider(serverConfiguration);
serverConformanceProvider.initializeOperations();

View File

@ -11,7 +11,6 @@ import javax.ws.rs.core.UriInfo;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.jaxrs.server.util.JaxRsRequest;
import ca.uhn.fhir.parser.IParser;
import ca.uhn.fhir.rest.api.RequestTypeEnum;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
import ca.uhn.fhir.rest.server.AddProfileTagEnum;
@ -21,7 +20,6 @@ import ca.uhn.fhir.rest.server.HardcodedServerAddressStrategy;
import ca.uhn.fhir.rest.server.IResourceProvider;
import ca.uhn.fhir.rest.server.IRestfulServerDefaults;
import ca.uhn.fhir.rest.server.IServerAddressStrategy;
import ca.uhn.fhir.rest.server.RestfulServerUtils;
/**
* Abstract Jax Rs Rest Server
@ -56,21 +54,21 @@ public abstract class AbstractJaxRsProvider implements IRestfulServerDefaults, I
public IServerAddressStrategy getServerAddressStrategy() {
HardcodedServerAddressStrategy addressStrategy = new HardcodedServerAddressStrategy();
addressStrategy.setValue(getBaseUri());
addressStrategy.setValue(getBaseForRequest());
return addressStrategy;
}
public String getBaseUri() {
}
public String getBaseForServer() {
return getUriInfo().getBaseUri().toASCIIString();
}
public String getBaseForRequest() {
return getBaseForServer();
}
/**
* PARSING METHODS
*/
public IParser getParser(JaxRsRequest theRequestDetails) {
return RestfulServerUtils.getNewParser(getFhirContext(), theRequestDetails);
}
protected JaxRsRequest createRequestDetails(final String resourceString, RequestTypeEnum requestType, RestOperationTypeEnum restOperation) {
return new JaxRsRequest(this, resourceString, requestType, restOperation);
}

View File

@ -18,6 +18,7 @@ import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import ca.uhn.fhir.jaxrs.server.interceptor.JaxRsExceptionInterceptor;
import ca.uhn.fhir.jaxrs.server.util.JaxRsRequest;
@ -43,7 +44,7 @@ import ca.uhn.fhir.util.UrlUtil;
*
*/
@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN})
@Consumes({MediaType.APPLICATION_FORM_URLENCODED,MediaType.APPLICATION_JSON, "application/json+fhir", "application/xml+fhir"})
@Consumes({MediaType.APPLICATION_FORM_URLENCODED, MediaType.APPLICATION_JSON, Constants.CT_FHIR_JSON, Constants.CT_FHIR_XML})
public abstract class AbstractJaxRsResourceProvider<R extends IResource> extends AbstractJaxRsProvider implements IRestfulServer<JaxRsRequest> {
private final MethodBindings bindings;
@ -56,8 +57,8 @@ public abstract class AbstractJaxRsResourceProvider<R extends IResource> extends
bindings = MethodBindings.getMethodBindings(this, subclass);
}
@Override
public String getBaseUri() {
@Override
public String getBaseForRequest() {
try {
return new URL(getUriInfo().getBaseUri().toURL(), getResourceType().getSimpleName()).toExternalForm();
} catch(Exception e) {
@ -111,6 +112,7 @@ public abstract class AbstractJaxRsResourceProvider<R extends IResource> extends
protected Response customOperation(final String resource, RequestTypeEnum requestType, String id, String operationName, RestOperationTypeEnum operationType)
throws Exception {
Validate.notNull(resource, "resource may not be null");
return executeMethod(resource, requestType, operationType, id, getBindings().getBinding(operationType, operationName));
}
@ -124,7 +126,7 @@ public abstract class AbstractJaxRsResourceProvider<R extends IResource> extends
if (id == null) {
throw new InvalidRequestException("Don't know how to handle request path: " + getUriInfo().getRequestUri().toASCIIString());
}
theRequest.setId(new IdDt(getBaseUri(), id, UrlUtil.unescape(versionString)));
theRequest.setId(new IdDt(getBaseForRequest(), id, UrlUtil.unescape(versionString)));
return (Response) method.invokeServer(this, theRequest);
}
@ -138,7 +140,7 @@ public abstract class AbstractJaxRsResourceProvider<R extends IResource> extends
throw new InvalidRequestException("Don't know how to handle request path: " + getUriInfo().getRequestUri().toASCIIString());
}
theRequest.setCompartmentName(compartment);
theRequest.setId(new IdDt(getBaseUri(), id));
theRequest.setId(new IdDt(getBaseForRequest(), id));
return (Response) method.invokeServer(this, theRequest);
}

View File

@ -1,46 +0,0 @@
package ca.uhn.fhir.jaxrs.server;
import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.slf4j.LoggerFactory;
import ca.uhn.fhir.jaxrs.server.interceptor.JaxRsExceptionInterceptor;
import ca.uhn.fhir.model.api.Bundle;
import ca.uhn.fhir.rest.annotation.Transaction;
import ca.uhn.fhir.rest.annotation.TransactionParam;
/**
* Rest Service for static requests such as
* @author Peter Van Houte
*/
@Local
@Path(StaticJaxRsServer.PATH)
@Stateless
@Produces(MediaType.APPLICATION_JSON)
public class StaticJaxRsServer {
private static final org.slf4j.Logger ourLog = LoggerFactory.getLogger(StaticJaxRsServer.class);
static final String PATH = "/";
@POST
@Path("/")
@Interceptors(JaxRsExceptionInterceptor.class)
public Response transaction(final String resource) {
ourLog.debug("calling transaction method");
return null;
}
@Transaction
public Bundle transaction(@TransactionParam Bundle theResources) {
ourLog.debug("transaction implemented");
return theResources;
}
}

View File

@ -8,6 +8,8 @@ import java.util.List;
import javax.ws.rs.core.HttpHeaders;
import org.apache.commons.lang3.StringUtils;
import ca.uhn.fhir.jaxrs.server.AbstractJaxRsProvider;
import ca.uhn.fhir.rest.api.RequestTypeEnum;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
@ -17,73 +19,72 @@ import ca.uhn.fhir.rest.server.IRestfulResponse;
public class JaxRsRequest extends RequestDetails {
private String theResourceString;
private HttpHeaders headers;
private AbstractJaxRsProvider myServer;
private String theResourceString;
private HttpHeaders headers;
private AbstractJaxRsProvider myServer;
public JaxRsRequest() {
}
public JaxRsRequest(AbstractJaxRsProvider server, String resourceString,
RequestTypeEnum requestType, RestOperationTypeEnum restOperation) {
this.headers = server.getHeaders();
this.theResourceString = resourceString;
this.setRestOperationType(restOperation);
setServer(server);
setFhirServerBase(server.getBaseUri());
setParameters(server.getQueryMap());
setRequestType(requestType);
}
public JaxRsRequest(AbstractJaxRsProvider server, String resourceString, RequestTypeEnum requestType,
RestOperationTypeEnum restOperation) {
this.headers = server.getHeaders();
this.theResourceString = resourceString;
this.setRestOperationType(restOperation);
setServer(server);
setFhirServerBase(server.getBaseForServer());
setParameters(server.getQueryMap());
setRequestType(requestType);
}
@Override
public AbstractJaxRsProvider getServer() {
return myServer;
}
return myServer;
}
public void setServer(AbstractJaxRsProvider theServer) {
this.myServer = theServer;
}
public void setServer(AbstractJaxRsProvider theServer) {
this.myServer = theServer;
}
@Override
public String getHeader(String headerKey) {
List<String> requestHeader = getHeaders(headerKey);
return requestHeader.isEmpty() ? null : requestHeader.get(0);
}
@Override
public String getHeader(String headerKey) {
List<String> requestHeader = getHeaders(headerKey);
return requestHeader.isEmpty() ? null : requestHeader.get(0);
}
@Override
public List<String> getHeaders(String name) {
List<String> requestHeader = headers.getRequestHeader(name);
return requestHeader == null ? Collections.<String> emptyList() : requestHeader;
}
@Override
public List<String> getHeaders(String name) {
List<String> requestHeader = headers.getRequestHeader(name);
return requestHeader == null ? Collections.<String> emptyList() : requestHeader;
}
@Override
public String getServerBaseForRequest() {
return getServer().getServerAddressStrategy().determineServerBase(null, null);
}
@Override
public String getServerBaseForRequest() {
return getServer().getServerAddressStrategy().determineServerBase(null, null);
}
@Override
protected byte[] getByteStreamRequestContents() {
return theResourceString.getBytes(ResourceParameter.determineRequestCharset(this));
return StringUtils.defaultIfEmpty(theResourceString, "").getBytes(ResourceParameter.determineRequestCharset(this));
}
@Override
@Override
public IRestfulResponse getResponse() {
if(super.getResponse() == null) {
setResponse(new JaxRsResponse(this));
if (super.getResponse() == null) {
setResponse(new JaxRsResponse(this));
}
return super.getResponse();
}
@Override
public Reader getReader()
throws IOException {
// not yet implemented
throw new UnsupportedOperationException();
}
}
@Override
public InputStream getInputStream() {
// not yet implemented
throw new UnsupportedOperationException();
}
@Override
public Reader getReader() throws IOException {
// not yet implemented
throw new UnsupportedOperationException();
}
@Override
public InputStream getInputStream() {
// not yet implemented
throw new UnsupportedOperationException();
}
}

View File

@ -1,13 +1,10 @@
package ca.uhn.fhir.jaxrs.server.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.Map.Entry;
import java.util.zip.GZIPOutputStream;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@ -26,60 +23,56 @@ import ca.uhn.fhir.rest.server.RestfulServerUtils;
public class JaxRsResponse extends RestfulResponse<JaxRsRequest> {
public JaxRsResponse(JaxRsRequest jaxRsRequestDetails) {
super(jaxRsRequestDetails);
}
public JaxRsResponse(JaxRsRequest jaxRsRequestDetails) {
super(jaxRsRequestDetails);
}
@Override
public Writer getResponseWriter(int statusCode, String contentType, String charset, boolean respondGzip)
throws UnsupportedEncodingException, IOException {
if (respondGzip) {
addHeader(Constants.HEADER_CONTENT_ENCODING, Constants.ENCODING_GZIP);
return new OutputStreamWriter(new GZIPOutputStream(new ByteArrayOutputStream()), Constants.CHARSET_NAME_UTF8);
} else {
return new StringWriter();
}
}
@Override
public Writer getResponseWriter(int statusCode, String contentType, String charset, boolean respondGzip)
throws UnsupportedEncodingException, IOException {
return new StringWriter();
}
@Override
public Response sendWriterResponse(int status, String contentType, String charset, Writer writer) {
Object entity = writer instanceof StringWriter ? writer.toString() : writer;
String charContentType = contentType+";charset="+StringUtils.defaultIfBlank(charset, Constants.CHARSET_NAME_UTF8);
return buildResponse(status).header(Constants.HEADER_CONTENT_TYPE, charContentType).entity(entity).build();
}
@Override
public Response sendWriterResponse(int status, String contentType, String charset, Writer writer) {
String charContentType = contentType + "; charset="
+ StringUtils.defaultIfBlank(charset, Constants.CHARSET_NAME_UTF8);
return buildResponse(status).header(Constants.HEADER_CONTENT_TYPE, charContentType).entity(writer.toString())
.build();
}
@Override
public Response sendAttachmentResponse(IBaseBinary bin, int statusCode, String contentType) throws IOException {
ResponseBuilder response = buildResponse(statusCode);
if (bin.getContent() != null && bin.getContent().length > 0) {
response.header(Constants.HEADER_CONTENT_TYPE, contentType).entity(bin.getContent());
}
return response.build();
}
@Override
public Response sendAttachmentResponse(IBaseBinary bin, int statusCode, String contentType) throws IOException {
ResponseBuilder response = buildResponse(statusCode);
if (bin.getContent() != null && bin.getContent().length > 0) {
response.header(Constants.HEADER_CONTENT_TYPE, contentType).entity(bin.getContent());
}
return response.build();
}
@Override
public Response returnResponse(ParseAction<?> outcome, int operationStatus, boolean allowPrefer,
MethodOutcome response, String resourceName) throws IOException {
StringWriter writer = new StringWriter();
if (outcome != null) {
IParser parser = RestfulServerUtils.getNewParser(getRequestDetails().getServer().getFhirContext(),
getRequestDetails());
outcome.execute(parser, writer);
}
return sendWriterResponse(operationStatus, getParserType(), null, writer);
}
protected String getParserType() {
EncodingEnum encodingEnum = RestfulServerUtils.determineResponseEncodingWithDefault(getRequestDetails());
return encodingEnum == EncodingEnum.JSON ? MediaType.APPLICATION_JSON : MediaType.APPLICATION_XML;
}
@Override
public Response returnResponse(ParseAction<?> outcome, int operationStatus, boolean allowPrefer, MethodOutcome response,
String resourceName)
throws IOException {
StringWriter writer = new StringWriter();
if(outcome != null) {
IParser parser = RestfulServerUtils.getNewParser(getRequestDetails().getServer().getFhirContext(), getRequestDetails());
outcome.execute(parser, writer);
}
return sendWriterResponse(operationStatus, getParserType(), null, writer);
}
protected String getParserType() {
EncodingEnum encodingEnum = RestfulServerUtils.determineResponseEncodingWithDefault(getRequestDetails());
return encodingEnum == EncodingEnum.JSON ? MediaType.APPLICATION_JSON : MediaType.APPLICATION_XML;
}
private ResponseBuilder buildResponse(int statusCode) {
ResponseBuilder response = Response.status(statusCode);
for (Entry<String, String> header : getHeaders().entrySet()) {
response.header(header.getKey(), header.getValue());
}
for (Entry<String, String> header : getHeaders().entrySet()) {
response.header(header.getKey(), header.getValue());
}
return response;
}
}
}

View File

@ -19,8 +19,8 @@ import org.glassfish.jersey.server.ContainerRequest;
import org.junit.Before;
import org.junit.Test;
import ca.uhn.fhir.jaxrs.server.example.TestJaxRsPatientRestProvider;
import ca.uhn.fhir.jaxrs.server.example.TestDummyPatientProvider;
import ca.uhn.fhir.jaxrs.server.example.TestJaxRsMockPatientRestProvider;
import ca.uhn.fhir.rest.server.Constants;
import ca.uhn.fhir.rest.server.IResourceProvider;
@ -57,11 +57,11 @@ public class AbstractJaxRsConformanceProviderTest {
@Test
public void testConformanceWithMethods() throws Exception {
providers.put(AbstractJaxRsConformanceProvider.class, provider);
providers.put(TestJaxRsPatientRestProvider.class, new TestJaxRsPatientRestProvider());
providers.put(TestJaxRsMockPatientRestProvider.class, new TestJaxRsMockPatientRestProvider());
Response response = createConformanceProvider(providers).conformance();
assertEquals(Constants.STATUS_HTTP_200_OK, response.getStatus());
assertTrue(response.getEntity().toString().contains("\"type\":\"Patient\""));
assertTrue(response.getEntity().toString().contains("\"$last"));
assertTrue(response.getEntity().toString().contains("\"$someCustomOperation"));
System.out.println(response);
System.out.println(response.getEntity());
}
@ -70,12 +70,12 @@ public class AbstractJaxRsConformanceProviderTest {
public void testConformanceInXml() throws Exception {
queryParameters.put(Constants.PARAM_FORMAT, Arrays.asList(Constants.CT_XML));
providers.put(AbstractJaxRsConformanceProvider.class, provider);
providers.put(TestJaxRsPatientRestProvider.class, new TestJaxRsPatientRestProvider());
providers.put(TestJaxRsMockPatientRestProvider.class, new TestJaxRsMockPatientRestProvider());
Response response = createConformanceProvider(providers).conformance();
assertEquals(Constants.STATUS_HTTP_200_OK, response.getStatus());
System.out.println(response.getEntity());
assertTrue(response.getEntity().toString().contains(" <type value=\"Patient\"/>"));
assertTrue(response.getEntity().toString().contains("\"$last"));
assertTrue(response.getEntity().toString().contains("\"$someCustomOperation"));
System.out.println(response.getEntity());
}

View File

@ -0,0 +1,417 @@
package ca.uhn.fhir.jaxrs.server;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.argThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.hamcrest.BaseMatcher;
import org.hamcrest.Description;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.jaxrs.server.example.RandomServerPortProvider;
import ca.uhn.fhir.jaxrs.server.example.TestJaxRsConformanceRestProvider;
import ca.uhn.fhir.jaxrs.server.example.TestJaxRsMockPatientRestProvider;
import ca.uhn.fhir.jaxrs.server.interceptor.JaxRsExceptionInterceptor;
import ca.uhn.fhir.model.api.BundleEntry;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.base.resource.BaseOperationOutcome;
import ca.uhn.fhir.model.dstu2.resource.Bundle;
import ca.uhn.fhir.model.dstu2.resource.Bundle.Entry;
import ca.uhn.fhir.model.dstu2.resource.Conformance;
import ca.uhn.fhir.model.dstu2.resource.Parameters;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.model.primitive.BoundCodeDt;
import ca.uhn.fhir.model.primitive.DateDt;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.model.primitive.UriDt;
import ca.uhn.fhir.model.valueset.BundleEntryTransactionMethodEnum;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.api.PreferReturnEnum;
import ca.uhn.fhir.rest.client.IGenericClient;
import ca.uhn.fhir.rest.client.ServerValidationModeEnum;
import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor;
import ca.uhn.fhir.rest.method.SearchStyleEnum;
import ca.uhn.fhir.rest.param.StringAndListParam;
import ca.uhn.fhir.rest.param.StringParam;
import ca.uhn.fhir.rest.server.EncodingEnum;
import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class AbstractJaxRsResourceProviderTest {
private TestJaxRsMockPatientRestProvider mock;
private ArgumentCaptor<IdDt> idCaptor;
private ArgumentCaptor<Patient> patientCaptor;
private static IGenericClient client;
private static final FhirContext ourCtx = FhirContext.forDstu2();
private static final String PATIENT_NAME = "Van Houte";
private static int ourPort;
private static Server jettyServer;
@BeforeClass
public static void setUpClass() throws Exception {
ourPort = RandomServerPortProvider.findFreePort();
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
System.out.println(ourPort);
jettyServer = new Server(ourPort);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
StringUtils.join(Arrays.asList(TestJaxRsMockPatientRestProvider.class.getCanonicalName(),
JaxRsExceptionInterceptor.class.getCanonicalName(),
TestJaxRsConformanceRestProvider.class.getCanonicalName()), ";"));
jettyServer.start();
final FhirContext ctx = FhirContext.forDstu2();
ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);
ourCtx.getRestfulClientFactory().setSocketTimeout(1200 * 1000);
client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/");
client.setEncoding(EncodingEnum.JSON);
client.registerInterceptor(new LoggingInterceptor(true));
}
@AfterClass
public static void tearDownClass() throws Exception {
try {
jettyServer.destroy();
} catch (Exception e) {
}
}
@Before
public void setUp() {
this.mock = TestJaxRsMockPatientRestProvider.mock;
idCaptor = ArgumentCaptor.forClass(IdDt.class);
patientCaptor = ArgumentCaptor.forClass(Patient.class);
reset(mock);
}
/** Search/Query - Type */
@Test
public void testSearchUsingGenericClientBySearch() {
// Perform a search
when(mock.search(any(StringParam.class), Matchers.isNull(StringAndListParam.class)))
.thenReturn(Arrays.asList(createPatient(1)));
final ca.uhn.fhir.model.api.Bundle results = client.search().forResource(Patient.class)
.where(Patient.NAME.matchesExactly().value(PATIENT_NAME)).execute();
verify(mock).search(any(StringParam.class), Matchers.isNull(StringAndListParam.class));
IResource resource = results.getEntries().get(0).getResource();
compareResultId(1, resource);
compareResultUrl("/Patient/1", resource);
}
/** Search - Multi-valued Parameters (ANY/OR) */
@Test
public void testSearchUsingGenericClientBySearchWithMultiValues() {
when(mock.search(any(StringParam.class), Matchers.isNotNull(StringAndListParam.class)))
.thenReturn(Arrays.asList(createPatient(1)));
final ca.uhn.fhir.model.api.Bundle results = client.search().forResource(Patient.class)
.where(Patient.ADDRESS.matches().values("Toronto")).and(Patient.ADDRESS.matches().values("Ontario"))
.and(Patient.ADDRESS.matches().values("Canada"))
.where(Patient.IDENTIFIER.exactly().systemAndIdentifier("SHORTNAME", "TOYS")).execute();
IResource resource = results.getEntries().get(0).getResource();
compareResultId(1, resource);
compareResultUrl("/Patient/1", resource);
}
/** Search - Paging */
@Test
public void testSearchWithPaging() {
// Perform a search
when(mock.search(any(StringParam.class), Matchers.isNull(StringAndListParam.class)))
.thenReturn(createPatients(1, 13));
final Bundle results = client.search().forResource(Patient.class).limitTo(8).returnBundle(Bundle.class)
.execute();
assertEquals(results.getEntry().size(), 8);
IResource resource = results.getEntry().get(0).getResource();
compareResultId(1, resource);
compareResultUrl("/Patient/1", resource);
compareResultId(8, results.getEntry().get(7).getResource());
// load next page
final Bundle nextPage = client.loadPage().next(results).execute();
resource = nextPage.getEntry().get(0).getResource();
compareResultId(9, resource);
compareResultUrl("/Patient/9", resource);
assertNull(nextPage.getLink(Bundle.LINK_NEXT));
}
/** Search using other query options */
public void testOther() {
// missing
}
/** */
@Test
public void testSearchPost() {
when(mock.search(any(StringParam.class), Matchers.isNull(StringAndListParam.class)))
.thenReturn(createPatients(1, 13));
Bundle result = client.search().forResource("Patient").usingStyle(SearchStyleEnum.POST)
.returnBundle(Bundle.class).execute();
IResource resource = result.getEntry().get(0).getResource();
compareResultId(1, resource);
compareResultUrl("/Patient/1", resource);
}
/** Search - Compartments */
@Test
public void testSearchCompartements() {
when(mock.searchCompartment(any(IdDt.class))).thenReturn(Arrays.asList((IResource) createPatient(1)));
Bundle response = client.search().forResource(Patient.class).withIdAndCompartment("1", "Condition")
.returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class).execute();
IResource resource = response.getEntry().get(0).getResource();
compareResultId(1, resource);
compareResultUrl("/Patient/1", resource);
}
/** Search - Subsetting (_summary and _elements) */
@Test
@Ignore
public void testSummary() {
Object response = client.search().forResource(Patient.class)
.returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class).execute();
}
@Test
public void testCreatePatient() throws Exception {
Patient toCreate = createPatient(1);
MethodOutcome outcome = new MethodOutcome();
toCreate.getIdentifierFirstRep().setValue("myIdentifier");
outcome.setResource(toCreate);
when(mock.create(patientCaptor.capture(), isNull(String.class))).thenReturn(outcome);
client.setEncoding(EncodingEnum.JSON);
final MethodOutcome response = client.create().resource(toCreate).prefer(PreferReturnEnum.REPRESENTATION)
.execute();
IResource resource = (IResource) response.getResource();
compareResultId(1, resource);
assertEquals("myIdentifier", patientCaptor.getValue().getIdentifierFirstRep().getValue());
}
/** Conditional Creates */
@Test
public void testConditionalCreate() throws Exception {
Patient toCreate = createPatient(1);
MethodOutcome outcome = new MethodOutcome();
toCreate.getIdentifierFirstRep().setValue("myIdentifier");
outcome.setResource(toCreate);
when(mock.create(patientCaptor.capture(), eq("Patient?_format=json&identifier=2"))).thenReturn(outcome);
client.setEncoding(EncodingEnum.JSON);
MethodOutcome response = client.create().resource(toCreate).conditional()
.where(Patient.IDENTIFIER.exactly().identifier("2")).prefer(PreferReturnEnum.REPRESENTATION).execute();
assertEquals("myIdentifier", patientCaptor.getValue().getIdentifierFirstRep().getValue());
IResource resource = (IResource) response.getResource();
compareResultId(1, resource);
}
/** Find By Id */
@Test
public void findUsingGenericClientById() {
when(mock.find(any(IdDt.class))).thenReturn(createPatient(1));
Patient result = client.read(Patient.class, "1");
compareResultId(1, result);
compareResultUrl("/Patient/1", result);
reset(mock);
when(mock.find(withId(result.getId()))).thenReturn(createPatient(1));
result = (Patient) client.read(new UriDt(result.getId().getValue()));
compareResultId(1, result);
compareResultUrl("/Patient/1", result);
}
@Test
public void testUpdateById() throws Exception {
when(mock.update(idCaptor.capture(), patientCaptor.capture())).thenReturn(new MethodOutcome());
client.update("1", createPatient(2));
assertEquals("1", idCaptor.getValue().getIdPart());
compareResultId(1, patientCaptor.getValue());
}
@Test
public void testDeletePatient() {
when(mock.delete(idCaptor.capture())).thenReturn(new MethodOutcome());
final BaseOperationOutcome results = client.delete().resourceById("Patient", "1").execute();
assertEquals("1", idCaptor.getValue().getIdPart());
}
/** Transaction - Server */
@Ignore
@Test
public void testTransaction() {
ca.uhn.fhir.model.api.Bundle bundle = new ca.uhn.fhir.model.api.Bundle();
BundleEntry entry = bundle.addEntry();
final Patient existing = new Patient();
existing.getNameFirstRep().addFamily("Created with bundle");
entry.setResource(existing);
BoundCodeDt<BundleEntryTransactionMethodEnum> theTransactionOperation = new BoundCodeDt(
BundleEntryTransactionMethodEnum.VALUESET_BINDER, BundleEntryTransactionMethodEnum.POST);
entry.setTransactionMethod(theTransactionOperation);
ca.uhn.fhir.model.api.Bundle response = client.transaction().withBundle(bundle).execute();
}
/** Conformance - Server */
@Test
public void testConformance() {
final Conformance conf = client.fetchConformance().ofType(Conformance.class).execute();
assertEquals(conf.getRest().get(0).getResource().get(0).getType().toString(), "Patient");
}
/** Extended Operations */
@Test
public void testExtendedOperations() {
// prepare mock
Parameters resultParameters = new Parameters();
resultParameters.addParameter().setName("return").setResource(createPatient(1)).setValue(new StringDt("outputValue"));
when(mock.someCustomOperation(eq(new StringDt("myAwesomeDummyValue")))).thenReturn(resultParameters);
// Create the input parameters to pass to the server
Parameters inParams = new Parameters();
inParams.addParameter().setName("start").setValue(new DateDt("2001-01-01"));
inParams.addParameter().setName("end").setValue(new DateDt("2015-03-01"));
inParams.addParameter().setName("dummy").setValue(new StringDt("myAwesomeDummyValue"));
//invoke
Parameters outParams = client.operation().onInstance(new IdDt("Patient", "1")).named("$someCustomOperation")
.withParameters(inParams).execute();
//verify
assertEquals("outputValue", ((StringDt)outParams.getParameter().get(0).getValue()).getValueAsString());
}
@Test
public void testExtendedOperationsUsingGet() {
// prepare mock
Parameters resultParameters = new Parameters();
resultParameters.addParameter().setName("return").setResource(createPatient(1)).setValue(new StringDt("outputValue"));
when(mock.someCustomOperation(eq(new StringDt("myAwesomeDummyValue")))).thenReturn(resultParameters);
// Create the input parameters to pass to the server
Parameters inParams = new Parameters();
inParams.addParameter().setName("start").setValue(new DateDt("2001-01-01"));
inParams.addParameter().setName("end").setValue(new DateDt("2015-03-01"));
inParams.addParameter().setName("dummy").setValue(new StringDt("myAwesomeDummyValue"));
// invoke
Parameters outParams = client.operation().onInstance(new IdDt("Patient", "1")).named("$someCustomOperation")
.withParameters(inParams).useHttpGet().execute();
// verify
assertEquals("outputValue", ((StringDt)outParams.getParameter().get(0).getValue()).getValueAsString());
}
@Test
public void testVRead() {
when(mock.findHistory(idCaptor.capture())).thenReturn(createPatient(1));
final Patient patient = client.vread(Patient.class, "1", "2");
compareResultId(1, patient);
compareResultUrl("/Patient/1", patient);
assertEquals("1", idCaptor.getValue().getIdPart());
assertEquals("2", idCaptor.getValue().getVersionIdPart());
}
@Test
public void testRead() {
when(mock.find(idCaptor.capture())).thenReturn(createPatient(1));
final Patient patient = client.read(Patient.class, "1");
compareResultId(1, patient);
compareResultUrl("/Patient/1", patient);
assertEquals("1", idCaptor.getValue().getIdPart());
}
@Test
public void testXFindUnknownPatient() {
try {
when(mock.find(idCaptor.capture())).thenThrow(new ResourceNotFoundException(new IdDt("999955541264")));
final Patient existing = client.read(Patient.class, "999955541264");
fail();
} catch (final Exception e) {
e.printStackTrace();
// assertEquals(e.getStatusCode(), 404);
}
}
private Bundle getPatientBundle(int size) {
Bundle result = new Bundle();
for (long i = 0; i < size; i++) {
Patient patient = createPatient(i);
Entry entry = new Entry().setResource(patient);
result.addEntry(entry);
}
return result;
}
private List<Patient> createPatients(int firstId, int lastId) {
List<Patient> result = new ArrayList<Patient>(lastId - firstId);
for (long i = firstId; i <= lastId; i++) {
result.add(createPatient(i));
}
return result;
}
private Patient createPatient(long id) {
Patient theResource = new Patient();
theResource.setId(new IdDt(id));
return theResource;
}
private void compareResultId(int id, IResource resource) {
assertEquals(id, resource.getId().getIdPartAsLong().intValue());
}
private void compareResultUrl(String url, IResource resource) {
assertEquals(url, resource.getId().getValueAsString().substring("http://localhost:55844".length()));
}
private <T> T withId(final T id) {
return argThat(new BaseMatcher<T>() {
@Override
public boolean matches(Object other) {
IdDt thisId;
IdDt otherId;
if (id instanceof IdDt) {
thisId = (IdDt) id;
otherId = (IdDt) other;
} else {
thisId = ((IResource) id).getId();
otherId = ((IResource) other).getId();
}
return thisId.getIdPartAsLong().equals(otherId.getIdPartAsLong());
}
@Override
public void describeTo(Description arg0) {
}
});
}
}

View File

@ -1,315 +0,0 @@
package ca.uhn.fhir.jaxrs.server.example;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.List;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.BundleEntry;
import ca.uhn.fhir.model.dstu2.composite.HumanNameDt;
import ca.uhn.fhir.model.dstu2.resource.Bundle;
import ca.uhn.fhir.model.dstu2.resource.Conformance;
import ca.uhn.fhir.model.dstu2.resource.Parameters;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.model.primitive.BoundCodeDt;
import ca.uhn.fhir.model.primitive.DateDt;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.model.valueset.BundleEntryTransactionMethodEnum;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.api.PreferReturnEnum;
import ca.uhn.fhir.rest.client.IGenericClient;
import ca.uhn.fhir.rest.client.ServerValidationModeEnum;
import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor;
import ca.uhn.fhir.rest.method.SearchStyleEnum;
import ca.uhn.fhir.rest.server.EncodingEnum;
public class JaxRsPatientProviderTest {
private static IGenericClient client;
private static final FhirContext ourCtx = FhirContext.forDstu2();
private static final String PATIENT_NAME = "Van Houte";
private static int ourPort;
private static Server jettyServer;
@BeforeClass
public static void setUpClass()
throws Exception {
ourPort = RandomServerPortProvider.findFreePort();
ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
context.setContextPath("/");
System.out.println(ourPort);
jettyServer = new Server(ourPort);
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", TestJaxRsPatientRestProvider.class.getCanonicalName() + "," +TestJaxRsConformanceRestProvider.class.getCanonicalName());
jettyServer.start();
ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);
ourCtx.getRestfulClientFactory().setSocketTimeout(1200 * 1000);
client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/");
client.setEncoding(EncodingEnum.JSON);
client.registerInterceptor(new LoggingInterceptor(true));
}
@AfterClass
public static void tearDownClass()
throws Exception {
try {
jettyServer.destroy();
}
catch (Exception e) {
}
}
/** Search/Query - Type */
@Test
public void findUsingGenericClientBySearch() {
// Perform a search
final ca.uhn.fhir.model.api.Bundle results = client.search().forResource(Patient.class)
.where(Patient.NAME.matchesExactly().value(PATIENT_NAME)).execute();
System.out.println(results.getEntries().get(0));
assertEquals(results.getEntries().size(), 1);
}
/** Search - Multi-valued Parameters (ANY/OR) */
@Test
public void findUsingGenericClientBySearchWithMultiValues() {
final ca.uhn.fhir.model.api.Bundle response = client.search().forResource(Patient.class)
.where(Patient.ADDRESS.matches().values("Toronto")).and(Patient.ADDRESS.matches().values("Ontario"))
.and(Patient.ADDRESS.matches().values("Canada"))
.where(Patient.IDENTIFIER.exactly().systemAndIdentifier("SHORTNAME", "TOYS")).execute();
System.out.println(response.getEntries().get(0));
}
/** Search - Paging */
@Test
public void findWithPaging() {
// Perform a search
final Bundle results = client.search().forResource(Patient.class).limitTo(8).returnBundle(Bundle.class).execute();
System.out.println(results.getEntry().size());
if (results.getLink(Bundle.LINK_NEXT) != null) {
// load next page
final Bundle nextPage = client.loadPage().next(results).execute();
System.out.println(nextPage.getEntry().size());
}
}
/** Search using other query options */
public void testOther() {
//missing
}
/** */
@Test
public void testSearchPost() {
Bundle response = client.search()
.forResource("Patient")
.usingStyle(SearchStyleEnum.POST)
.returnBundle(Bundle.class)
.execute();
assertTrue(response.getEntry().size() > 0);
}
/** Search - Compartments */
@Test
public void testSearchCompartements() {
Bundle response = client.search()
.forResource(Patient.class)
.withIdAndCompartment("1", "Condition")
.returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class)
.execute();
assertTrue(response.getEntry().size() > 0);
}
/** Search - Subsetting (_summary and _elements) */
@Test
@Ignore
public void testSummary() {
Object response = client.search()
.forResource(Patient.class)
.returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class)
.execute();
}
@Test
public void testCreatePatient() {
final Patient existing = new Patient();
existing.setId((IdDt) null);
existing.getNameFirstRep().addFamily("Created Patient 54");
client.setEncoding(EncodingEnum.JSON);
final MethodOutcome results = client.create().resource(existing).prefer(PreferReturnEnum.REPRESENTATION).execute();
System.out.println(results.getId());
final Patient patient = (Patient) results.getResource();
System.out.println(patient);
assertNotNull(client.read(patient.getId()));
client.setEncoding(EncodingEnum.JSON);
}
/** Conditional Creates */
@Test
public void testConditionalCreate() {
final Patient existing = new Patient();
existing.setId((IdDt) null);
existing.getNameFirstRep().addFamily("Created Patient 54");
client.setEncoding(EncodingEnum.XML);
final MethodOutcome results = client.create().resource(existing).prefer(PreferReturnEnum.REPRESENTATION).execute();
System.out.println(results.getId());
final Patient patient = (Patient) results.getResource();
client.create()
.resource(patient)
.conditional()
.where(Patient.IDENTIFIER.exactly().identifier(patient.getIdentifierFirstRep()))
.execute();
}
/** Find By Id */
@Test
public void findUsingGenericClientById() {
final Patient results = client.read(Patient.class, "1");
assertEquals(results.getId().getIdPartAsLong().longValue(), 1L);
}
@Test
public void testUpdateById() {
final Patient existing = client.read(Patient.class, "1");
final List<HumanNameDt> name = existing.getName();
name.get(0).addSuffix("The Second");
existing.setName(name);
client.setEncoding(EncodingEnum.XML);
final MethodOutcome results = client.update("1", existing);
}
@Test
public void testDeletePatient() {
final Patient existing = new Patient();
existing.getNameFirstRep().addFamily("Created Patient XYZ");
final MethodOutcome results = client.create().resource(existing).prefer(PreferReturnEnum.REPRESENTATION).execute();
System.out.println(results.getId());
final Patient patient = (Patient) results.getResource();
client.delete(Patient.class, patient.getId());
try {
client.read(patient.getId());
fail();
}
catch (final Exception e) {
//assertEquals(e.getStatusCode(), Constants.STATUS_HTTP_404_NOT_FOUND);
}
}
/** Transaction - Server */
@Ignore
@Test
public void testTransaction() {
ca.uhn.fhir.model.api.Bundle bundle = new ca.uhn.fhir.model.api.Bundle();
BundleEntry entry = bundle.addEntry();
final Patient existing = new Patient();
existing.getNameFirstRep().addFamily("Created with bundle");
entry.setResource(existing);
BoundCodeDt<BundleEntryTransactionMethodEnum> theTransactionOperation =
new BoundCodeDt(
BundleEntryTransactionMethodEnum.VALUESET_BINDER,
BundleEntryTransactionMethodEnum.POST);
entry.setTransactionMethod(theTransactionOperation);
ca.uhn.fhir.model.api.Bundle response = client.transaction().withBundle(bundle).execute();
}
/** Conformance - Server */
@Test
public void testConformance() {
final Conformance conf = client.fetchConformance().ofType(Conformance.class).execute();
System.out.println(conf.getRest().get(0).getResource().get(0).getType());
assertEquals(conf.getRest().get(0).getResource().get(0).getType().toString(), "Patient");
}
/** Extended Operations */
// Create a client to talk to the HeathIntersections server
@Test
public void testExtendedOperations() {
client.registerInterceptor(new LoggingInterceptor(true));
// Create the input parameters to pass to the server
Parameters inParams = new Parameters();
inParams.addParameter().setName("start").setValue(new DateDt("2001-01-01"));
inParams.addParameter().setName("end").setValue(new DateDt("2015-03-01"));
inParams.addParameter().setName("dummy").setValue(new StringDt("myAwesomeDummyValue"));
// Invoke $everything on "Patient/1"
Parameters outParams = client
.operation()
.onInstance(new IdDt("Patient", "1"))
.named("$last")
.withParameters(inParams)
//.useHttpGet() // Use HTTP GET instead of POST
.execute();
String resultValue = outParams.getParameter().get(0).getValue().toString();
System.out.println(resultValue);
assertEquals("expected but found : "+ resultValue, resultValue.contains("myAwesomeDummyValue"), true);
}
@Test
public void testExtendedOperationsUsingGet() {
client.registerInterceptor(new LoggingInterceptor(true));
// Create the input parameters to pass to the server
Parameters inParams = new Parameters();
inParams.addParameter().setName("start").setValue(new DateDt("2001-01-01"));
inParams.addParameter().setName("end").setValue(new DateDt("2015-03-01"));
inParams.addParameter().setName("dummy").setValue(new StringDt("myAwesomeDummyValue"));
// Invoke $everything on "Patient/1"
Parameters outParams = client
.operation()
.onInstance(new IdDt("Patient", "1"))
.named("$last")
.withParameters(inParams)
.useHttpGet() // Use HTTP GET instead of POST
.execute();
String resultValue = outParams.getParameter().get(0).getValue().toString();
System.out.println(resultValue);
assertEquals("expected but found : "+ resultValue, resultValue.contains("myAwesomeDummyValue"), true);
}
@Test
public void testFindUnknownPatient() {
try {
final Patient existing = client.read(Patient.class, "999955541264");
fail();
}
catch (final Exception e) {
e.printStackTrace();
//assertEquals(e.getStatusCode(), 404);
}
}
@Test
public void testVRead() {
final Patient patient = client.vread(Patient.class, "1", "1");
System.out.println(patient);
}
@Test
public void testRead() {
final Patient patient = client.read(Patient.class, "1");
System.out.println(patient);
}
}

View File

@ -13,22 +13,23 @@ import ca.uhn.fhir.rest.server.IResourceProvider;
/**
* Fhir Physician Rest Service
*
* @author axmpm
*
*/
@Path(TestJaxRsConformanceRestProvider.PATH)
@Stateless
@Produces({MediaType.APPLICATION_JSON, Constants.CT_FHIR_JSON, Constants.CT_FHIR_XML})
@Produces({ MediaType.APPLICATION_JSON, Constants.CT_FHIR_JSON, Constants.CT_FHIR_XML })
public class TestJaxRsConformanceRestProvider extends AbstractJaxRsConformanceProvider {
public TestJaxRsConformanceRestProvider() {
public TestJaxRsConformanceRestProvider() {
super("", "", "");
}
}
@Override
protected ConcurrentHashMap<Class<? extends IResourceProvider>, IResourceProvider> getProviders() throws Exception {
ConcurrentHashMap<Class<? extends IResourceProvider>, IResourceProvider> map = new ConcurrentHashMap<Class<? extends IResourceProvider>, IResourceProvider>();
map.put(TestJaxRsPatientRestProvider.class, new TestJaxRsPatientRestProvider());
map.put(TestJaxRsMockPatientRestProvider.class, new TestJaxRsMockPatientRestProvider());
map.put(TestJaxRsConformanceRestProvider.class, new TestJaxRsConformanceRestProvider());
return map;
}

View File

@ -0,0 +1,134 @@
package ca.uhn.fhir.jaxrs.server.example;
import java.util.List;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.mockito.Mockito;
import ca.uhn.fhir.jaxrs.server.AbstractJaxRsResourceProvider;
import ca.uhn.fhir.jaxrs.server.interceptor.JaxRsExceptionInterceptor;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.dstu2.resource.Parameters;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.StringDt;
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.IdParam;
import ca.uhn.fhir.rest.annotation.Operation;
import ca.uhn.fhir.rest.annotation.OperationParam;
import ca.uhn.fhir.rest.annotation.Read;
import ca.uhn.fhir.rest.annotation.RequiredParam;
import ca.uhn.fhir.rest.annotation.ResourceParam;
import ca.uhn.fhir.rest.annotation.Search;
import ca.uhn.fhir.rest.annotation.Update;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.api.RequestTypeEnum;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
import ca.uhn.fhir.rest.param.StringAndListParam;
import ca.uhn.fhir.rest.param.StringParam;
import ca.uhn.fhir.rest.server.Constants;
import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider;
import ca.uhn.fhir.rest.server.IPagingProvider;
/**
* Fhir Physician Rest Service
*
* @author axmpm
*
*/
@Path(TestJaxRsMockPatientRestProvider.PATH)
@Stateless
@Produces({ MediaType.APPLICATION_JSON, Constants.CT_FHIR_JSON, Constants.CT_FHIR_XML })
public class TestJaxRsMockPatientRestProvider extends AbstractJaxRsResourceProvider<Patient> {
static final String PATH = "/Patient";
private FifoMemoryPagingProvider pp;
public static final TestJaxRsMockPatientRestProvider mock = Mockito.mock(TestJaxRsMockPatientRestProvider.class);
public TestJaxRsMockPatientRestProvider() {
pp = new FifoMemoryPagingProvider(10);
pp.setDefaultPageSize(10);
pp.setMaximumPageSize(100);
}
@Search
public List<Patient> search(@RequiredParam(name = Patient.SP_NAME) final StringParam name, @RequiredParam(name=Patient.SP_ADDRESS) StringAndListParam theAddressParts) {
return mock.search(name, theAddressParts);
}
@Update
public MethodOutcome update(@IdParam final IdDt theId, @ResourceParam final Patient patient) throws Exception {
return mock.update(theId, patient);
}
@Read
public Patient find(@IdParam final IdDt theId) {
return mock.find(theId);
}
@Read(version = true)
public Patient findHistory(@IdParam final IdDt theId) {
return mock.findHistory(theId);
}
@Create
public MethodOutcome create(@ResourceParam final Patient patient, @ConditionalUrlParam String theConditional)
throws Exception {
return mock.create(patient, theConditional);
}
@Delete
public MethodOutcome delete(@IdParam final IdDt theId) {
return mock.delete(theId);
}
@GET
@Path("/{id}/$someCustomOperation")
@Interceptors(JaxRsExceptionInterceptor.class)
public Response someCustomOperationUsingGet(@PathParam("id") String id, String resource) throws Exception {
return customOperation(resource, RequestTypeEnum.GET, id, "$someCustomOperation",
RestOperationTypeEnum.EXTENDED_OPERATION_TYPE);
}
@Search(compartmentName = "Condition")
public List<IResource> searchCompartment(@IdParam IdDt thePatientId) {
return mock.searchCompartment(thePatientId);
}
@POST
@Path("/{id}/$someCustomOperation")
@Interceptors(JaxRsExceptionInterceptor.class)
public Response someCustomOperationUsingPost(@PathParam("id") String id, String resource) throws Exception {
return customOperation(resource, RequestTypeEnum.POST, id, "$someCustomOperation",
RestOperationTypeEnum.EXTENDED_OPERATION_TYPE);
}
@Operation(name = "someCustomOperation", idempotent = true, returnParameters = {
@OperationParam(name = "return", type = StringDt.class) })
public Parameters someCustomOperation(@OperationParam(name = "dummy") StringDt dummyInput) {
return mock.someCustomOperation(dummyInput);
}
@Override
public Class<Patient> getResourceType() {
return Patient.class;
}
@Override
public IPagingProvider getPagingProvider() {
return pp;
}
}

View File

@ -1,269 +0,0 @@
package ca.uhn.fhir.jaxrs.server.example;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import ca.uhn.fhir.jaxrs.server.AbstractJaxRsResourceProvider;
import ca.uhn.fhir.jaxrs.server.interceptor.JaxRsExceptionInterceptor;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.dstu2.resource.Condition;
import ca.uhn.fhir.model.dstu2.resource.Parameters;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.StringDt;
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.IdParam;
import ca.uhn.fhir.rest.annotation.Operation;
import ca.uhn.fhir.rest.annotation.OperationParam;
import ca.uhn.fhir.rest.annotation.Read;
import ca.uhn.fhir.rest.annotation.RequiredParam;
import ca.uhn.fhir.rest.annotation.ResourceParam;
import ca.uhn.fhir.rest.annotation.Search;
import ca.uhn.fhir.rest.annotation.Update;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.api.RequestTypeEnum;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
import ca.uhn.fhir.rest.param.StringParam;
import ca.uhn.fhir.rest.server.AddProfileTagEnum;
import ca.uhn.fhir.rest.server.BundleInclusionRule;
import ca.uhn.fhir.rest.server.Constants;
import ca.uhn.fhir.rest.server.ETagSupportEnum;
import ca.uhn.fhir.rest.server.FifoMemoryPagingProvider;
import ca.uhn.fhir.rest.server.IPagingProvider;
import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException;
import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor;
/**
* Fhir Physician Rest Service
* @author axmpm
*
*/
@Path(TestJaxRsPatientRestProvider.PATH)
@Stateless
@Produces({MediaType.APPLICATION_JSON, Constants.CT_FHIR_JSON, Constants.CT_FHIR_XML})
public class TestJaxRsPatientRestProvider extends AbstractJaxRsResourceProvider<Patient> {
static final String PATH = "/Patient";
private static Long counter = 1L;
private static final ConcurrentHashMap<String, List<Patient>> patients = new ConcurrentHashMap<String, List<Patient>>();
public TestJaxRsPatientRestProvider() throws Exception {
super(TestJaxRsPatientRestProvider.class);
}
static {
patients.put(""+counter, createPatient("Van Houte"));
patients.put(""+(counter), createPatient("Agnew"));
for(int i = 0 ; i<20 ; i++) {
patients.put(""+(counter), createPatient("Random Patient " + counter));
}
}
private static List<Patient> createPatient(final String name) {
final Patient patient = new Patient();
patient.getNameFirstRep().addFamily(name);
return createPatient(patient);
}
private static List<Patient> createPatient(final Patient patient) {
patient.setId(createId(counter, 1L));
final LinkedList<Patient> list = new LinkedList<Patient>();
list.add(patient);
counter++;
return list ;
}
private static IdDt createId(final Long id, final Long theVersionId) {
return new IdDt("Patient", "" + id, "" + theVersionId);
}
@Search
public List<Patient> search(@RequiredParam(name = Patient.SP_NAME) final StringParam name) {
final List<Patient> result = new LinkedList<Patient>();
for (final List<Patient> patientIterator : patients.values()) {
Patient single = null;
for (Patient patient : patientIterator) {
if (name == null || patient.getNameFirstRep().getFamilyFirstRep().getValueNotNull().equals(name.getValueNotNull())) {
single = patient;
}
}
if (single != null) {
result.add(single);
}
}
return result;
}
@Update
public MethodOutcome update(@IdParam final IdDt theId, @ResourceParam final Patient patient)
throws Exception {
final String idPart = theId.getIdPart();
if(patients.containsKey(idPart)) {
final List<Patient> patientList = patients.get(idPart);
final Patient lastPatient = getLast(patientList);
patient.setId(createId(theId.getIdPartAsLong(), lastPatient.getId().getVersionIdPartAsLong()+1));
patientList.add(patient);
final MethodOutcome result = new MethodOutcome().setCreated(false);
result.setResource(patient);
result.setId(patient.getId());
return result;
} else {
throw new ResourceNotFoundException(theId);
}
}
@Read
public Patient find(@IdParam final IdDt theId) {
if(patients.containsKey(theId.getIdPart())) {
return getLast(patients.get(theId.getIdPart()));
} else {
throw new ResourceNotFoundException(theId);
}
}
private Patient getLast(final List<Patient> list) {
return list.get(list.size()-1);
}
@Read(version = true)
public Patient findHistory(@IdParam final IdDt theId) {
if (patients.containsKey(theId.getIdPart())) {
final List<Patient> list = patients.get(theId.getIdPart());
for (final Patient patient : list) {
if (patient.getId().getVersionIdPartAsLong().equals(theId.getVersionIdPartAsLong())) {
return patient;
}
}
}
throw new ResourceNotFoundException(theId);
}
@Create
public MethodOutcome create(@ResourceParam final Patient patient, @ConditionalUrlParam String theConditional)
throws Exception {
patients.put(""+counter, createPatient(patient));
final MethodOutcome result = new MethodOutcome().setCreated(true);
result.setResource(patient);
result.setId(patient.getId());
return result;
}
@Delete
public MethodOutcome delete(@IdParam final IdDt theId) {
final Patient deletedPatient = find(theId);
patients.remove(deletedPatient.getId().getIdPart());
final MethodOutcome result = new MethodOutcome().setCreated(true);
result.setResource(deletedPatient);
return result;
}
@GET
@Path("/{id}/$last")
@Interceptors(JaxRsExceptionInterceptor.class)
public Response operationLastGet(@PathParam("id") String id)
throws Exception {
return customOperation(null, RequestTypeEnum.GET, id, "$last", RestOperationTypeEnum.EXTENDED_OPERATION_TYPE);
}
@Search(compartmentName="Condition")
public List<IResource> searchCompartment(@IdParam IdDt thePatientId) {
List<IResource> retVal=new ArrayList<IResource>();
Condition condition = new Condition();
condition.setId(new IdDt("665577"));
retVal.add(condition);
return retVal;
}
@POST
@Path("/{id}/$last")
@Interceptors(JaxRsExceptionInterceptor.class)
public Response operationLast(final String resource)
throws Exception {
return customOperation(resource, RequestTypeEnum.POST, null, "$last", RestOperationTypeEnum.EXTENDED_OPERATION_TYPE);
}
// @ca.uhn.fhir.rest.annotation.Validate
// public MethodOutcome validate(
// @ResourceParam T theResource,
// @ResourceParam String theRawResource,
// @ResourceParam EncodingEnum theEncoding,
// @ca.uhn.fhir.rest.annotation.Validate.Mode ValidationModeEnum theMode,
// @ca.uhn.fhir.rest.annotation.Validate.Profile String theProfile) {
// return validate(theResource, null, theRawResource, theEncoding, theMode, theProfile);
// }
@Operation(name="last", idempotent=true, returnParameters= {
@OperationParam(name="return", type=StringDt.class)
})
public Parameters last(@OperationParam(name = "dummy") StringDt dummyInput) {
System.out.println("inputparameter");
Parameters parameters = new Parameters();
Patient patient = find(new IdDt(counter.intValue()-1));
parameters
.addParameter()
.setName("return")
.setResource(patient)
.setValue(new StringDt((counter-1)+"" + "inputVariable [ " + dummyInput.getValue()+ "]"));
return parameters;
}
@Override
public Class<Patient> getResourceType() {
return Patient.class;
}
/** THE DEFAULTS */
@Override
public List<IServerInterceptor> getInterceptors() {
return Collections.emptyList();
}
@Override
public ETagSupportEnum getETagSupport() {
return ETagSupportEnum.DISABLED;
}
@Override
public boolean isDefaultPrettyPrint() {
return true;
}
@Override
public AddProfileTagEnum getAddProfileTag() {
return AddProfileTagEnum.NEVER;
}
@Override
public boolean isUseBrowserFriendlyContentTypes() {
return true;
}
@Override
public IPagingProvider getPagingProvider() {
return new FifoMemoryPagingProvider(10);
}
@Override
public BundleInclusionRule getBundleInclusionRule() {
return BundleInclusionRule.BASED_ON_INCLUDES;
}
}

View File

@ -112,7 +112,8 @@ public class JaxRsRequestTest {
//mocks
provider = spy(TestDummyPatientProvider.class);
doReturn(uriInfo).when(provider).getUriInfo();
doReturn(BASEURI).when(provider).getBaseUri();
doReturn(BASEURI).when(provider).getBaseForRequest();
doReturn(BASEURI).when(provider).getBaseForServer();
doReturn(headers).when(provider).getHeaders();
return new JaxRsRequest(provider, RESOURCE_STRING, RequestTypeEnum.GET, RestOperationTypeEnum.HISTORY_TYPE);

View File

@ -49,7 +49,7 @@ public class JaxRsResponseTest {
Set<SummaryEnum> theSummaryMode = Collections.<SummaryEnum>emptySet();
Response result = (Response) RestfulServerUtils.streamResponseAsBundle(request.getServer(), bundle, theSummaryMode, theRequestIsBrowser, respondGzip, request);
assertEquals(200, result.getStatus());
assertEquals(Constants.CT_FHIR_JSON, result.getHeaderString(Constants.HEADER_CONTENT_TYPE));
assertEquals(Constants.CT_FHIR_JSON+Constants.CHARSET_UTF8_CTSUFFIX, result.getHeaderString(Constants.HEADER_CONTENT_TYPE));
assertTrue(result.getEntity().toString().contains("Patient"));
assertTrue(result.getEntity().toString().contains("15"));
}
@ -60,23 +60,11 @@ public class JaxRsResponseTest {
boolean respondGzip = false;
Response result = (Response) RestfulServerUtils.streamResponseAsBundle(request.getServer(), bundle, theSummaryMode, theRequestIsBrowser, respondGzip, request);
assertEquals(200, result.getStatus());
assertEquals(Constants.CT_JSON, result.getHeaderString(Constants.HEADER_CONTENT_TYPE));
assertEquals(Constants.CT_JSON+Constants.CHARSET_UTF8_CTSUFFIX, result.getHeaderString(Constants.HEADER_CONTENT_TYPE));
assertTrue(result.getEntity().toString().contains("Patient"));
assertTrue(result.getEntity().toString().contains("15"));
}
@Test
public void testGetResponseWriterWithZip() throws IOException {
boolean theRequestIsBrowser = true;
boolean respondGzip = true;
Response result = (Response) RestfulServerUtils.streamResponseAsBundle(request.getServer(), bundle, theSummaryMode, theRequestIsBrowser, respondGzip, request);
assertEquals(200, result.getStatus());
assertEquals(Constants.CT_JSON, result.getHeaderString(Constants.HEADER_CONTENT_TYPE));
assertEquals(Constants.ENCODING_GZIP, result.getHeaderString(Constants.HEADER_CONTENT_ENCODING));
// assertTrue(unzip(result.getEntity()).contains("Patient"));
// assertTrue(result.getEntity().toString().contains("15"));
}
@Test
public void testSendAttachmentResponse() throws IOException {
boolean theRequestIsBrowser = true;
@ -129,7 +117,7 @@ public class JaxRsResponseTest {
MethodOutcome methodOutcome = new MethodOutcome(theId);
Response result = response.returnResponse(outcome, operationStatus, allowPrefer, methodOutcome, resourceName);
assertEquals(200, result.getStatus());
assertEquals(Constants.CT_JSON, result.getHeaderString(Constants.HEADER_CONTENT_TYPE));
assertEquals(Constants.CT_JSON+Constants.CHARSET_UTF8_CTSUFFIX, result.getHeaderString(Constants.HEADER_CONTENT_TYPE));
System.out.println(result.getEntity().toString());
assertTrue(result.getEntity().toString().contains("resourceType\":\"Patient"));
assertTrue(result.getEntity().toString().contains("15"));
@ -147,7 +135,7 @@ public class JaxRsResponseTest {
response.getRequestDetails().getParameters().put(Constants.PARAM_FORMAT, new String[]{Constants.CT_XML});
Response result = response.returnResponse(outcome, operationStatus, allowPrefer, methodOutcome, resourceName);
assertEquals(200, result.getStatus());
assertEquals(Constants.CT_XML, result.getHeaderString(Constants.HEADER_CONTENT_TYPE));
assertEquals(Constants.CT_XML+Constants.CHARSET_UTF8_CTSUFFIX, result.getHeaderString(Constants.HEADER_CONTENT_TYPE));
assertTrue(result.getEntity().toString().contains("<Patient"));
assertTrue(result.getEntity().toString().contains("15"));
}
@ -162,7 +150,7 @@ public class JaxRsResponseTest {
response.getRequestDetails().getParameters().put(Constants.PARAM_FORMAT, new String[]{Constants.CT_XML});
Response result = response.returnResponse(outcome, operationStatus, allowPrefer, methodOutcome, resourceName);
assertEquals(204, result.getStatus());
assertEquals(Constants.CT_XML, result.getHeaderString(Constants.HEADER_CONTENT_TYPE));
assertEquals(Constants.CT_XML+Constants.CHARSET_UTF8_CTSUFFIX, result.getHeaderString(Constants.HEADER_CONTENT_TYPE));
}
private String unzip(Object entity) throws IOException {

View File

@ -1,4 +1,4 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!-- Note: HAPI projects use the "hapi-fhir" POM as their base to provide easy management. You do not need to use this in your own projects, so the "parent" tag and it's contents below may be removed
@ -34,43 +34,53 @@
<version>1.3-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ejb</groupId>
<artifactId>ejb-api</artifactId>
<version>3.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>9.2.3.v20140905</version>
<version>${jetty_version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>9.2.3.v20140905</version>
<version>${jetty_version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.7</version>
<version>${jersey_version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet-core</artifactId>
<version>2.7</version>
<version>${jersey_version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-jetty-http</artifactId>
<version>2.7</version>
<version>${jersey_version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-moxy</artifactId>
<version>2.7</version>
<version>${jersey_version}</version>
</dependency>
</dependencies>
<build>
<!-- Tells Maven to name the generated WAR file as hapi-fhir-jpaserver-example.war -->
<finalName>hapi-fhir-jaxrsserver-example</finalName>
<!-- This is to run the integration tests -->
<plugins>
@ -90,36 +100,6 @@
</executions>
</plugin>
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack</id>
<phase>package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>${project.groupId}</groupId>
<artifactId>${project.artifactId}</artifactId>
<version>${project.version}</version>
<type>war</type>
<includes>*.war</includes>
</artifactItem>
</artifactItems>
<outputDirectory>C:\Agfa\ORBIS-AS\server\orbis-as-08.05.07.00.0009200-UK\standalone\deployments</outputDirectory>
<stripVersion>true</stripVersion>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>8.1.16.v20140903</version>
</plugin>
</plugins>
</build>

View File

@ -1,45 +0,0 @@
package ca.uhn.fhir.jaxrs.server.example;
import java.util.List;
import javax.ws.rs.core.Response;
import ca.uhn.fhir.jaxrs.server.IJaxRsResourceProvider;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.dstu2.resource.Parameters;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.param.StringParam;
public interface IJaxRsPatientProvider extends IJaxRsResourceProvider<Patient> {
public static final String JNDI_NAME = "IJaxRsPatientProvider";
List<Patient> search(StringParam name);
MethodOutcome update(IdDt theId, Patient patient)
throws Exception;
Patient find(IdDt theId);
Patient findHistory(IdDt theId);
MethodOutcome create(Patient patient, String theConditional)
throws Exception;
MethodOutcome delete(IdDt theId);
Response operationLastGet(String resource)
throws Exception;
Response operationLast(String resource)
throws Exception;
Parameters last(StringDt dummyInput);
List<IResource> searchCompartment(IdDt thePatientId);
}

View File

@ -1,43 +1,38 @@
package ca.uhn.fhir.jaxrs.server.example;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.Local;
import java.util.concurrent.ConcurrentHashMap;
import javax.ejb.Stateless;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import ca.uhn.fhir.jaxrs.server.AbstractJaxRsConformanceProvider;
import ca.uhn.fhir.rest.server.Constants;
import ca.uhn.fhir.rest.server.IResourceProvider;
/**
* Conformance Rest Service
*
* @author Peter Van Houte
*/
//@Local
//@Path(ConformanceRestServer.PATH)
//@Stateless
//@Produces({MediaType.APPLICATION_JSON, Constants.CT_FHIR_JSON, Constants.CT_FHIR_XML})
public class JaxRsConformanceProvider
{
private static final String SERVER_VERSION = "1.0.0";
private static final String SERVER_DESCRIPTION = "Jax-Rs Test Example Description";
private static final String SERVER_NAME = "Jax-Rs Test Example";
@EJB
private JaxRsConformanceProvider conformanceRestServer;
@EJB
private IJaxRsPatientProvider patientRestServer;
// public ConformanceRestServer() {
// super(SERVER_DESCRIPTION, SERVER_NAME, SERVER_VERSION);
// }
//
// @PostConstruct
// public void createMethod()
// throws Exception {
// findResourceMethods(conformanceRestServer, ConformanceRestServer.class);
// findResourceMethods(patientRestServer, FhirPatientRestServer.class);
// super.setUpPostConstruct();
// }
@Path("")
@Stateless
@Produces({ MediaType.APPLICATION_JSON, Constants.CT_FHIR_JSON, Constants.CT_FHIR_XML })
public class JaxRsConformanceProvider extends AbstractJaxRsConformanceProvider {
private static final String SERVER_VERSION = "1.0.0";
private static final String SERVER_DESCRIPTION = "Jax-Rs Test Example Description";
private static final String SERVER_NAME = "Jax-Rs Test Example";
public JaxRsConformanceProvider() {
super(SERVER_VERSION, SERVER_DESCRIPTION, SERVER_NAME);
}
@Override
protected ConcurrentHashMap<Class<? extends IResourceProvider>, IResourceProvider> getProviders() throws Exception {
ConcurrentHashMap<Class<? extends IResourceProvider>, IResourceProvider> map = new ConcurrentHashMap<Class<? extends IResourceProvider>, IResourceProvider>();
map.put(JaxRsConformanceProvider.class, new JaxRsConformanceProvider());
map.put(JaxRsPatientRestProvider.class, new JaxRsPatientRestProvider());
return map;
}
}

View File

@ -51,231 +51,207 @@ import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor;
/**
* Fhir Physician Rest Service
*
* @author axmpm
*
*/
@Local(IJaxRsPatientProvider.class)
@Local
@Path(JaxRsPatientRestProvider.PATH)
@Stateless(name = IJaxRsPatientProvider.JNDI_NAME, mappedName=IJaxRsPatientProvider.JNDI_NAME)
@Produces({MediaType.APPLICATION_JSON, Constants.CT_FHIR_JSON, Constants.CT_FHIR_XML})
public class JaxRsPatientRestProvider extends AbstractJaxRsResourceProvider<Patient> implements IJaxRsPatientProvider {
static final String PATH = "/Patient";
private static Long counter = 1L;
private static final ConcurrentHashMap<String, List<Patient>> patients = new ConcurrentHashMap<String, List<Patient>>();
public JaxRsPatientRestProvider() throws Exception {
super(JaxRsPatientRestProvider.class);
}
static {
patients.put(""+counter, createPatient("Van Houte"));
patients.put(""+(counter), createPatient("Agnew"));
for(int i = 0 ; i<20 ; i++) {
patients.put(""+(counter), createPatient("Random Patient " + counter));
}
}
@Stateless
@Produces({ MediaType.APPLICATION_JSON, Constants.CT_FHIR_JSON, Constants.CT_FHIR_XML })
public class JaxRsPatientRestProvider extends AbstractJaxRsResourceProvider<Patient> {
private static List<Patient> createPatient(final String name) {
final Patient patient = new Patient();
patient.getNameFirstRep().addFamily(name);
return createPatient(patient);
}
private static List<Patient> createPatient(final Patient patient) {
patient.setId(createId(counter, 1L));
final LinkedList<Patient> list = new LinkedList<Patient>();
list.add(patient);
counter++;
return list ;
}
static final String PATH = "/Patient";
private static IdDt createId(final Long id, final Long theVersionId) {
return new IdDt("Patient", "" + id, "" + theVersionId);
}
@Search
@Override
public List<Patient> search(@RequiredParam(name = Patient.SP_NAME) final StringParam name) {
final List<Patient> result = new LinkedList<Patient>();
for (final List<Patient> patientIterator : patients.values()) {
Patient single = null;
for (Patient patient : patientIterator) {
if (name == null || patient.getNameFirstRep().getFamilyFirstRep().getValueNotNull().equals(name.getValueNotNull())) {
single = patient;
}
}
if (single != null) {
result.add(single);
}
}
return result;
}
@Update
@Override
public MethodOutcome update(@IdParam final IdDt theId, @ResourceParam final Patient patient)
throws Exception {
final String idPart = theId.getIdPart();
if(patients.containsKey(idPart)) {
final List<Patient> patientList = patients.get(idPart);
final Patient lastPatient = getLast(patientList);
patient.setId(createId(theId.getIdPartAsLong(), lastPatient.getId().getVersionIdPartAsLong()+1));
patientList.add(patient);
final MethodOutcome result = new MethodOutcome().setCreated(false);
result.setResource(patient);
result.setId(patient.getId());
return result;
} else {
throw new ResourceNotFoundException(theId);
}
}
private static Long counter = 1L;
private static final ConcurrentHashMap<String, List<Patient>> patients = new ConcurrentHashMap<String, List<Patient>>();
@Override
@Read
public Patient find(@IdParam final IdDt theId) {
if(patients.containsKey(theId.getIdPart())) {
return getLast(patients.get(theId.getIdPart()));
} else {
throw new ResourceNotFoundException(theId);
}
}
private Patient getLast(final List<Patient> list) {
return list.get(list.size()-1);
}
public JaxRsPatientRestProvider() throws Exception {
super(JaxRsPatientRestProvider.class);
}
@Override
@Read(version = true)
public Patient findHistory(@IdParam final IdDt theId) {
if (patients.containsKey(theId.getIdPart())) {
final List<Patient> list = patients.get(theId.getIdPart());
for (final Patient patient : list) {
if (patient.getId().getVersionIdPartAsLong().equals(theId.getVersionIdPartAsLong())) {
return patient;
}
}
}
throw new ResourceNotFoundException(theId);
}
static {
patients.put("" + counter, createPatient("Van Houte"));
patients.put("" + (counter), createPatient("Agnew"));
for (int i = 0; i < 20; i++) {
patients.put("" + (counter), createPatient("Random Patient " + counter));
}
}
@Create
@Override
public MethodOutcome create(@ResourceParam final Patient patient, @ConditionalUrlParam String theConditional)
throws Exception {
patients.put(""+counter, createPatient(patient));
final MethodOutcome result = new MethodOutcome().setCreated(true);
result.setResource(patient);
result.setId(patient.getId());
return result;
}
@Delete
@Override
public MethodOutcome delete(@IdParam final IdDt theId) {
final Patient deletedPatient = find(theId);
patients.remove(deletedPatient.getId().getIdPart());
final MethodOutcome result = new MethodOutcome().setCreated(true);
result.setResource(deletedPatient);
return result;
}
@GET
@Path("/{id}/$last")
@Interceptors(JaxRsExceptionInterceptor.class)
@Override
public Response operationLastGet(@PathParam("id") String id)
throws Exception {
return customOperation(null, RequestTypeEnum.GET, id, "$last", RestOperationTypeEnum.EXTENDED_OPERATION_TYPE);
}
@Search(compartmentName="Condition")
@Override
public List<IResource> searchCompartment(@IdParam IdDt thePatientId) {
List<IResource> retVal=new ArrayList<IResource>();
Condition condition = new Condition();
condition.setId(new IdDt("665577"));
retVal.add(condition);
return retVal;
}
@POST
@Path("/{id}/$last")
@Interceptors(JaxRsExceptionInterceptor.class)
@Override
public Response operationLast(final String resource)
throws Exception {
return customOperation(resource, RequestTypeEnum.POST, null, "$last", RestOperationTypeEnum.EXTENDED_OPERATION_TYPE);
}
// @ca.uhn.fhir.rest.annotation.Validate
// public MethodOutcome validate(
// @ResourceParam T theResource,
// @ResourceParam String theRawResource,
// @ResourceParam EncodingEnum theEncoding,
// @ca.uhn.fhir.rest.annotation.Validate.Mode ValidationModeEnum theMode,
// @ca.uhn.fhir.rest.annotation.Validate.Profile String theProfile) {
// return validate(theResource, null, theRawResource, theEncoding, theMode, theProfile);
// }
private static List<Patient> createPatient(final String name) {
final Patient patient = new Patient();
patient.getNameFirstRep().addFamily(name);
return createPatient(patient);
}
@Operation(name="last", idempotent=true, returnParameters= {
@OperationParam(name="return", type=StringDt.class)
})
@Override
public Parameters last(@OperationParam(name = "dummy") StringDt dummyInput) {
System.out.println("inputparameter");
Parameters parameters = new Parameters();
Patient patient = find(new IdDt(counter.intValue()-1));
parameters
.addParameter()
.setName("return")
.setResource(patient)
.setValue(new StringDt((counter-1)+"" + "inputVariable [ " + dummyInput.getValue()+ "]"));
return parameters;
}
@Override
public Class<Patient> getResourceType() {
return Patient.class;
}
/** THE DEFAULTS */
@Override
public List<IServerInterceptor> getInterceptors() {
return Collections.emptyList();
}
private static List<Patient> createPatient(final Patient patient) {
patient.setId(createId(counter, 1L));
final LinkedList<Patient> list = new LinkedList<Patient>();
list.add(patient);
counter++;
return list;
}
@Override
public ETagSupportEnum getETagSupport() {
return ETagSupportEnum.DISABLED;
}
private static IdDt createId(final Long id, final Long theVersionId) {
return new IdDt("Patient", "" + id, "" + theVersionId);
}
@Override
public boolean isDefaultPrettyPrint() {
return true;
}
@Search
public List<Patient> search(@RequiredParam(name = Patient.SP_NAME) final StringParam name) {
final List<Patient> result = new LinkedList<Patient>();
for (final List<Patient> patientIterator : patients.values()) {
Patient single = null;
for (Patient patient : patientIterator) {
if (name == null || patient.getNameFirstRep().getFamilyFirstRep().getValueNotNull()
.equals(name.getValueNotNull())) {
single = patient;
}
}
if (single != null) {
result.add(single);
}
}
return result;
}
@Override
public AddProfileTagEnum getAddProfileTag() {
return AddProfileTagEnum.NEVER;
}
@Update
public MethodOutcome update(@IdParam final IdDt theId, @ResourceParam final Patient patient) throws Exception {
final String idPart = theId.getIdPart();
if (patients.containsKey(idPart)) {
final List<Patient> patientList = patients.get(idPart);
final Patient lastPatient = getLast(patientList);
patient.setId(createId(theId.getIdPartAsLong(), lastPatient.getId().getVersionIdPartAsLong() + 1));
patientList.add(patient);
final MethodOutcome result = new MethodOutcome().setCreated(false);
result.setResource(patient);
result.setId(patient.getId());
return result;
} else {
throw new ResourceNotFoundException(theId);
}
}
@Override
public boolean isUseBrowserFriendlyContentTypes() {
return true;
}
@Read
public Patient find(@IdParam final IdDt theId) {
if (patients.containsKey(theId.getIdPart())) {
return getLast(patients.get(theId.getIdPart()));
} else {
throw new ResourceNotFoundException(theId);
}
}
@Override
public IPagingProvider getPagingProvider() {
return new FifoMemoryPagingProvider(10);
}
private Patient getLast(final List<Patient> list) {
return list.get(list.size() - 1);
}
@Override
public BundleInclusionRule getBundleInclusionRule() {
return BundleInclusionRule.BASED_ON_INCLUDES;
}
@Read(version = true)
public Patient findHistory(@IdParam final IdDt theId) {
if (patients.containsKey(theId.getIdPart())) {
final List<Patient> list = patients.get(theId.getIdPart());
for (final Patient patient : list) {
if (patient.getId().getVersionIdPartAsLong().equals(theId.getVersionIdPartAsLong())) {
return patient;
}
}
}
throw new ResourceNotFoundException(theId);
}
@Create
public MethodOutcome create(@ResourceParam final Patient patient, @ConditionalUrlParam String theConditional)
throws Exception {
patients.put("" + counter, createPatient(patient));
final MethodOutcome result = new MethodOutcome().setCreated(true);
result.setResource(patient);
result.setId(patient.getId());
return result;
}
@Delete
public MethodOutcome delete(@IdParam final IdDt theId) {
final Patient deletedPatient = find(theId);
patients.remove(deletedPatient.getId().getIdPart());
final MethodOutcome result = new MethodOutcome().setCreated(true);
result.setResource(deletedPatient);
return result;
}
@GET
@Path("/{id}/$last")
@Interceptors(JaxRsExceptionInterceptor.class)
public Response operationLastGet(@PathParam("id") String id, String resource) throws Exception {
return customOperation(resource, RequestTypeEnum.GET, id, "$last",
RestOperationTypeEnum.EXTENDED_OPERATION_TYPE);
}
@Search(compartmentName = "Condition")
public List<IResource> searchCompartment(@IdParam IdDt thePatientId) {
List<IResource> retVal = new ArrayList<IResource>();
Condition condition = new Condition();
condition.setId(new IdDt("665577"));
retVal.add(condition);
return retVal;
}
@POST
@Path("/{id}/$last")
@Interceptors(JaxRsExceptionInterceptor.class)
public Response operationLast(final String resource) throws Exception {
return customOperation(resource, RequestTypeEnum.POST, null, "$last",
RestOperationTypeEnum.EXTENDED_OPERATION_TYPE);
}
@Operation(name = "last", idempotent = true, returnParameters = {
@OperationParam(name = "return", type = StringDt.class) })
public Parameters last(@OperationParam(name = "dummy") StringDt dummyInput) {
System.out.println("inputparameter");
Parameters parameters = new Parameters();
Patient patient = find(new IdDt(counter.intValue() - 1));
parameters.addParameter().setName("return").setResource(patient)
.setValue(new StringDt((counter - 1) + "" + "inputVariable [ " + dummyInput.getValue() + "]"));
return parameters;
}
@Override
public Class<Patient> getResourceType() {
return Patient.class;
}
/** THE DEFAULTS */
@Override
public List<IServerInterceptor> getInterceptors() {
return Collections.emptyList();
}
@Override
public ETagSupportEnum getETagSupport() {
return ETagSupportEnum.DISABLED;
}
@Override
public boolean isDefaultPrettyPrint() {
return true;
}
@Override
public AddProfileTagEnum getAddProfileTag() {
return AddProfileTagEnum.NEVER;
}
@Override
public boolean isUseBrowserFriendlyContentTypes() {
return true;
}
@Override
public IPagingProvider getPagingProvider() {
return new FifoMemoryPagingProvider(10);
}
@Override
public BundleInclusionRule getBundleInclusionRule() {
return BundleInclusionRule.BASED_ON_INCLUDES;
}
}

View File

@ -5,8 +5,10 @@ import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
@ -16,7 +18,6 @@ import org.junit.Ignore;
import org.junit.Test;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.jaxrs.server.example.JaxRsPatientRestProvider;
import ca.uhn.fhir.model.api.BundleEntry;
import ca.uhn.fhir.model.dstu2.composite.HumanNameDt;
import ca.uhn.fhir.model.dstu2.resource.Bundle;
@ -55,10 +56,11 @@ public class JaxRsPatientProviderTest {
jettyServer.setHandler(context);
ServletHolder jerseyServlet = context.addServlet(org.glassfish.jersey.servlet.ServletContainer.class, "/*");
jerseyServlet.setInitOrder(0);
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames", JaxRsPatientRestProvider.class.getCanonicalName());
jerseyServlet.setInitParameter("jersey.config.server.provider.classnames",
StringUtils.join(Arrays.asList(JaxRsConformanceProvider.class.getCanonicalName(),
JaxRsPatientRestProvider.class.getCanonicalName()), ";"));
jettyServer.start();
final FhirContext ctx = FhirContext.forDstu2();
ourCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.NEVER);
ourCtx.getRestfulClientFactory().setSocketTimeout(1200 * 1000);
client = ourCtx.newRestfulGenericClient("http://localhost:" + ourPort + "/");
@ -142,7 +144,7 @@ public class JaxRsPatientProviderTest {
@Test
@Ignore
public void testSummary() {
Object response = client.search()
client.search()
.forResource(Patient.class)
.returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class)
.execute();
@ -270,8 +272,6 @@ public class JaxRsPatientProviderTest {
@Test
public void testExtendedOperationsUsingGet() {
client.registerInterceptor(new LoggingInterceptor(true));
// Create the input parameters to pass to the server
Parameters inParams = new Parameters();
inParams.addParameter().setName("start").setValue(new DateDt("2001-01-01"));
@ -291,18 +291,6 @@ public class JaxRsPatientProviderTest {
assertEquals("expected but found : "+ resultValue, resultValue.contains("myAwesomeDummyValue"), true);
}
@Test
public void testFindUnknownPatient() {
try {
final Patient existing = client.read(Patient.class, "999955541264");
fail();
}
catch (final Exception e) {
e.printStackTrace();
//assertEquals(e.getStatusCode(), 404);
}
}
@Test
public void testVRead() {
final Patient patient = client.vread(Patient.class, "1", "1");