Remove some dead code and improve test coverage

This commit is contained in:
jamesagnew 2016-06-17 07:40:17 -04:00
parent dcecde5db9
commit 785ce1deb9
17 changed files with 240 additions and 355 deletions

View File

@ -354,11 +354,6 @@ public abstract class BaseRuntimeElementCompositeDefinition<T extends IBase> ext
RuntimeChildChoiceDefinition def = new RuntimeChildChoiceDefinition(next, elementName, childAnnotation, descriptionAnnotation, choiceTypes); RuntimeChildChoiceDefinition def = new RuntimeChildChoiceDefinition(next, elementName, childAnnotation, descriptionAnnotation, choiceTypes);
orderMap.put(order, def); orderMap.put(order, def);
} else if (next.getType().equals(ExtensionDt.class)) {
RuntimeChildExtensionDt def = new RuntimeChildExtensionDt(next, elementName, childAnnotation, descriptionAnnotation);
orderMap.put(order, def);
} else if (extensionAttr != null) { } else if (extensionAttr != null) {
/* /*
* Child is an extension * Child is an extension
@ -427,8 +422,6 @@ public abstract class BaseRuntimeElementCompositeDefinition<T extends IBase> ext
} else { } else {
def = new RuntimeChildPrimitiveDatatypeDefinition(next, elementName, descriptionAnnotation, childAnnotation, nextDatatype); def = new RuntimeChildPrimitiveDatatypeDefinition(next, elementName, descriptionAnnotation, childAnnotation, nextDatatype);
} }
} else if (IBaseXhtml.class.isAssignableFrom(nextElementType)) {
def = new RuntimeChildXhtmlDatatypeDefinition(next, elementName, descriptionAnnotation, childAnnotation, nextDatatype);
} else { } else {
if (IBoundCodeableConcept.class.isAssignableFrom(nextElementType)) { if (IBoundCodeableConcept.class.isAssignableFrom(nextElementType)) {
IValueSetEnumBinder<Enum<?>> binder = ModelScanner.getBoundCodeBinder(next); IValueSetEnumBinder<Enum<?>> binder = ModelScanner.getBoundCodeBinder(next);

View File

@ -1,40 +0,0 @@
package ca.uhn.fhir.context;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2016 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 java.lang.reflect.Field;
import ca.uhn.fhir.model.api.ExtensionDt;
import ca.uhn.fhir.model.api.IElement;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Description;
public class RuntimeChildExtensionDt extends RuntimeChildAny {
public RuntimeChildExtensionDt(Field theField, String theElementName, Child theChildAnnotation, Description theDescriptionAnnotation) {
super(theField, theElementName, theChildAnnotation, theDescriptionAnnotation);
}
public IElement newInstance() {
return new ExtensionDt();
}
}

View File

@ -1,40 +0,0 @@
package ca.uhn.fhir.context;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2016 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 java.lang.reflect.Field;
import org.hl7.fhir.instance.model.api.IBase;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Description;
/**
* HL7org XHTML type
*/
public class RuntimeChildXhtmlDatatypeDefinition extends RuntimeChildPrimitiveDatatypeDefinition {
public RuntimeChildXhtmlDatatypeDefinition(Field theField, String theElementName, Description theDescriptionAnnotation, Child theChildAnnotation, Class<? extends IBase> theDatatype) {
super(theField, theElementName, theDescriptionAnnotation, theChildAnnotation, theDatatype);
}
}

View File

@ -209,7 +209,7 @@ public abstract class BaseClient implements IRestfulClient {
// TODO: handle non 2xx status codes by throwing the correct exception, // TODO: handle non 2xx status codes by throwing the correct exception,
// and ensure it's passed upwards // and ensure it's passed upwards
IHttpRequest httpRequest; IHttpRequest httpRequest = null;
IHttpResponse response = null; IHttpResponse response = null;
try { try {
Map<String, List<String>> params = createExtraParams(); Map<String, List<String>> params = createExtraParams();
@ -355,11 +355,13 @@ public abstract class BaseClient implements IRestfulClient {
} }
} catch (DataFormatException e) { } catch (DataFormatException e) {
throw new FhirClientConnectionException(e); String msg = getFhirContext().getLocalizer().getMessage(BaseClient.class, "failedToParseResponse", httpRequest.getHttpVerbName(), httpRequest.getUri(), e.toString());
throw new FhirClientConnectionException(msg, e);
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
throw new FhirClientConnectionException(e); throw new FhirClientConnectionException(e);
} catch (IOException e) { } catch (IOException e) {
throw new FhirClientConnectionException(e); String msg = getFhirContext().getLocalizer().getMessage(BaseClient.class, "ioExceptionDuringOperation", httpRequest.getHttpVerbName(), httpRequest.getUri(), e.toString());
throw new FhirClientConnectionException(msg, e);
} catch (RuntimeException e) { } catch (RuntimeException e) {
throw e; throw e;
} catch (Exception e) { } catch (Exception e) {

View File

@ -300,7 +300,8 @@ public abstract class RestfulClientFactory implements IRestfulClientFactory {
Class implementingClass = myContext.getResourceDefinition("Conformance").getImplementingClass(); Class implementingClass = myContext.getResourceDefinition("Conformance").getImplementingClass();
conformance = (IBaseResource) client.fetchConformance().ofType(implementingClass).execute(); conformance = (IBaseResource) client.fetchConformance().ofType(implementingClass).execute();
} catch (FhirClientConnectionException e) { } catch (FhirClientConnectionException e) {
throw new FhirClientConnectionException(myContext.getLocalizer().getMessage(RestfulClientFactory.class, "failedToRetrieveConformance", theServerBase + Constants.URL_TOKEN_METADATA), e); String msg = myContext.getLocalizer().getMessage(RestfulClientFactory.class, "failedToRetrieveConformance", theServerBase + Constants.URL_TOKEN_METADATA);
throw new FhirClientConnectionException(msg, e);
} }
FhirTerser t = myContext.newTerser(); FhirTerser t = myContext.newTerser();

View File

@ -44,8 +44,8 @@ import ca.uhn.fhir.rest.client.api.IHttpResponse;
*/ */
public class ApacheHttpRequest implements IHttpRequest { public class ApacheHttpRequest implements IHttpRequest {
private HttpRequestBase myRequest;
private HttpClient myClient; private HttpClient myClient;
private HttpRequestBase myRequest;
public ApacheHttpRequest(HttpClient theClient, HttpRequestBase theApacheRequest) { public ApacheHttpRequest(HttpClient theClient, HttpRequestBase theApacheRequest) {
this.myClient = theClient; this.myClient = theClient;
@ -57,14 +57,6 @@ public class ApacheHttpRequest implements IHttpRequest {
myRequest.addHeader(theName, theValue); myRequest.addHeader(theName, theValue);
} }
/**
* Get the ApacheRequest
* @return the ApacheRequest
*/
public HttpRequestBase getApacheRequest() {
return myRequest;
}
@Override @Override
public IHttpResponse execute() throws IOException { public IHttpResponse execute() throws IOException {
return new ApacheHttpResponse(myClient.execute(myRequest)); return new ApacheHttpResponse(myClient.execute(myRequest));
@ -82,9 +74,17 @@ public class ApacheHttpRequest implements IHttpRequest {
return result; return result;
} }
/**
* Get the ApacheRequest
* @return the ApacheRequest
*/
public HttpRequestBase getApacheRequest() {
return myRequest;
}
@Override @Override
public String toString() { public String getHttpVerbName() {
return myRequest.toString(); return myRequest.getMethod();
} }
@Override @Override
@ -98,4 +98,14 @@ public class ApacheHttpRequest implements IHttpRequest {
return null; return null;
} }
@Override
public String getUri() {
return myRequest.getURI().toString();
}
@Override
public String toString() {
return myRequest.toString();
}
} }

View File

@ -56,4 +56,14 @@ public interface IHttpRequest {
*/ */
public String getRequestBodyFromStream() throws IOException; public String getRequestBodyFromStream() throws IOException;
/**
* Return the request URI, or null
*/
public String getUri();
/**
* Return the HTTP verb (e.g. "GET")
*/
public String getHttpVerbName();
} }

View File

@ -1,54 +0,0 @@
package ca.uhn.fhir.rest.method;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2016 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 java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
/**
* Created by dsotnikov on 2/25/2014.
*/
class Util {
// public static Integer findCountParameterIndex(Method theMethod) {
// return findParamIndex(theMethod, Count.class);
// }
public static Map<String, String> getQueryParams(String query) {
try {
Map<String, String> params = new HashMap<String, String>();
for (String param : query.split("&")) {
String[] pair = param.split("=");
String key = URLDecoder.decode(pair[0], "UTF-8");
String value = URLDecoder.decode(pair[1], "UTF-8");
params.put(key, value);
}
return params;
} catch (UnsupportedEncodingException ex) {
throw new AssertionError(ex);
}
}
}

View File

@ -7,11 +7,14 @@ ca.uhn.fhir.context.FhirContext.noStructuresForSpecifiedVersion=Could not find t
ca.uhn.fhir.context.RuntimeResourceDefinition.nonInstantiableType=Resource type "{0}" can not be instantiated. Check that this class has a no-argument constructor, and that it is static if it is a nested type. Error is: {1} ca.uhn.fhir.context.RuntimeResourceDefinition.nonInstantiableType=Resource type "{0}" can not be instantiated. Check that this class has a no-argument constructor, and that it is static if it is a nested type. Error is: {1}
ca.uhn.fhir.rest.client.BaseClient.ioExceptionDuringOperation=Encountered IOException when performing {0} to URL {1} - {2}
ca.uhn.fhir.rest.client.BaseClient.failedToParseResponse=Failed to parse response from server when performing {0} to URL {1} - {2}
ca.uhn.fhir.rest.client.GenericClient.noPagingLinkFoundInBundle=Can not perform paging operation because no link was found in Bundle with relation "{0}" ca.uhn.fhir.rest.client.GenericClient.noPagingLinkFoundInBundle=Can not perform paging operation because no link was found in Bundle with relation "{0}"
ca.uhn.fhir.rest.client.GenericClient.noVersionIdForVread=No version specified in URL for 'vread' operation: {0} ca.uhn.fhir.rest.client.GenericClient.noVersionIdForVread=No version specified in URL for 'vread' operation: {0}
ca.uhn.fhir.rest.client.GenericClient.incompleteUriForRead=The given URI is not an absolute URL and is not usable for this operation: {0} ca.uhn.fhir.rest.client.GenericClient.incompleteUriForRead=The given URI is not an absolute URL and is not usable for this operation: {0}
ca.uhn.fhir.rest.client.GenericClient.cannotDetermineResourceTypeFromUri=Unable to determine the resource type from the given URI: {0} ca.uhn.fhir.rest.client.GenericClient.cannotDetermineResourceTypeFromUri=Unable to determine the resource type from the given URI: {0}
ca.uhn.fhir.rest.client.RestfulClientFactory.failedToRetrieveConformance=Failed to retrieve the server's metadata statement during client initialization. URL used was: {0} ca.uhn.fhir.rest.client.RestfulClientFactory.failedToRetrieveConformance=Failed to retrieve the server metadata statement during client initialization. URL used was {0}
ca.uhn.fhir.rest.client.RestfulClientFactory.wrongVersionInConformance=The server at base URL "{0}" returned a conformance statement indicating that it supports FHIR version "{1}" which corresponds to {2}, but this client is configured to use {3} (via the FhirContext). ca.uhn.fhir.rest.client.RestfulClientFactory.wrongVersionInConformance=The server at base URL "{0}" returned a conformance statement indicating that it supports FHIR version "{1}" which corresponds to {2}, but this client is configured to use {3} (via the FhirContext).
ca.uhn.fhir.rest.method.BaseOutcomeReturningMethodBindingWithResourceParam.incorrectIdForUpdate=Can not update resource, resource body must contain an ID element which matches the request URL for update (PUT) operation - Resource body ID of "{0}" does not match URL ID of "{1}" ca.uhn.fhir.rest.method.BaseOutcomeReturningMethodBindingWithResourceParam.incorrectIdForUpdate=Can not update resource, resource body must contain an ID element which matches the request URL for update (PUT) operation - Resource body ID of "{0}" does not match URL ID of "{1}"

View File

@ -103,4 +103,14 @@ public class JaxRsHttpRequest implements IHttpRequest {
return null; return null;
} }
@Override
public String getUri() {
return ""; // TODO: can we get this from somewhere?
}
@Override
public String getHttpVerbName() {
return myRequestType.name();
}
} }

View File

@ -1,79 +0,0 @@
package ca.uhn.fhir.jpa.dao;
/*
* #%L
* HAPI FHIR JPA Server
* %%
* Copyright (C) 2014 - 2016 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 java.util.Date;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
class HistoryTuple implements Comparable<HistoryTuple> {
private Long myId;
private boolean myIsHistory;
private Date myUpdated;
public HistoryTuple(boolean theIsHistory, Date theUpdated, Long theId) {
super();
myIsHistory = theIsHistory;
myUpdated = theUpdated;
myId = theId;
}
@Override
public int compareTo(HistoryTuple theO) {
return myUpdated.compareTo(theO.myUpdated);
}
public Long getId() {
return myId;
}
public boolean isHistory() {
return myIsHistory;
}
public Date getUpdated() {
return myUpdated;
}
public void setId(Long theId) {
myId = theId;
}
public void setIsHistory(boolean theIsHistory) {
myIsHistory = theIsHistory;
}
public void setUpdated(Date theUpdated) {
myUpdated = theUpdated;
}
@Override
public String toString() {
ToStringBuilder b = new ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE);
b.append("id", myId);
b.append("history", myIsHistory);
b.append("updated", myUpdated);
return b.build();
}
}

View File

@ -1,42 +0,0 @@
package ca.uhn.fhir.jpa.subscription;
/*
* #%L
* HAPI FHIR JPA Server
* %%
* Copyright (C) 2014 - 2016 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 org.springframework.beans.factory.FactoryBean;
public class SubscriptionWebsocketHandlerFactoryDstu2 implements FactoryBean<ISubscriptionWebsocketHandler> {
static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SubscriptionWebsocketHandlerDstu2.class);
@Override
public ISubscriptionWebsocketHandler getObject() throws Exception {
return new SubscriptionWebsocketHandlerDstu2();
}
@Override
public Class<ISubscriptionWebsocketHandler> getObjectType() {
return ISubscriptionWebsocketHandler.class;
}
@Override
public boolean isSingleton() {
return false;
}
}

View File

@ -1,42 +0,0 @@
package ca.uhn.fhir.jpa.subscription;
/*
* #%L
* HAPI FHIR JPA Server
* %%
* Copyright (C) 2014 - 2016 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 org.springframework.beans.factory.FactoryBean;
public class SubscriptionWebsocketHandlerFactoryDstu3 implements FactoryBean<ISubscriptionWebsocketHandler> {
static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SubscriptionWebsocketHandlerDstu3.class);
@Override
public ISubscriptionWebsocketHandler getObject() throws Exception {
return new SubscriptionWebsocketHandlerDstu3();
}
@Override
public Class<ISubscriptionWebsocketHandler> getObjectType() {
return ISubscriptionWebsocketHandler.class;
}
@Override
public boolean isSingleton() {
return false;
}
}

View File

@ -10,11 +10,22 @@ import com.google.common.collect.ImmutableSet;
import com.google.common.reflect.ClassPath; import com.google.common.reflect.ClassPath;
import com.google.common.reflect.ClassPath.ClassInfo; import com.google.common.reflect.ClassPath.ClassInfo;
import ca.uhn.fhir.model.dstu.resource.OperationOutcome;
import ca.uhn.fhir.rest.client.exceptions.FhirClientConnectionException;
import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.TestUtil;
public class ExceptionPropertiesTest { public class ExceptionPropertiesTest {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ExceptionPropertiesTest.class); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ExceptionPropertiesTest.class);
@Test
public void testConstructors() {
new FhirClientConnectionException("");
new FhirClientConnectionException("", new Exception());
new FhirClientConnectionException(new Exception());
new NotImplementedOperationException("");
new NotImplementedOperationException(null, new OperationOutcome());
}
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Test @Test
public void testExceptionsAreGood() throws Exception { public void testExceptionsAreGood() throws Exception {

View File

@ -1,10 +1,13 @@
package ca.uhn.fhir.jpa.provider.dstu3; package ca.uhn.fhir.parser;
import org.hl7.fhir.dstu3.model.QuestionnaireResponse; import org.junit.Test;
import ca.uhn.fhir.parser.ErrorHandlerAdapter;
import ca.uhn.fhir.parser.IParserErrorHandler;
/* /*
* #%L * #%L
* HAPI FHIR JPA Server * HAPI FHIR - Core Library
* %% * %%
* Copyright (C) 2014 - 2016 University Health Network * Copyright (C) 2014 - 2016 University Health Network
* %% * %%
@ -22,8 +25,15 @@ import org.hl7.fhir.dstu3.model.QuestionnaireResponse;
* #L% * #L%
*/ */
public class BaseJpaResourceProviderQuestionnaireResponseDstu3 extends JpaResourceProviderDstu3<QuestionnaireResponse> { /**
* Adapter implementation with NOP implementations of all {@link IParserErrorHandler} methods.
// nothing yet */
public class ErrorHandlerAdapterTest {
@Test
public void testMethods() {
new ErrorHandlerAdapter().unexpectedRepeatingElement(null, null);
new ErrorHandlerAdapter().unknownAttribute(null, null);
new ErrorHandlerAdapter().unknownElement(null, null);
}
} }

View File

@ -1,6 +1,8 @@
package ca.uhn.fhir.rest.client; package ca.uhn.fhir.rest.client;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.either;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.Matchers.startsWith;
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
@ -14,6 +16,7 @@ import static org.mockito.Mockito.when;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.StringReader; import java.io.StringReader;
import java.net.SocketTimeoutException;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
@ -49,6 +52,9 @@ import org.mockito.internal.stubbing.defaultanswers.ReturnsDeepStubs;
import org.mockito.invocation.InvocationOnMock; import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer; import org.mockito.stubbing.Answer;
import com.google.common.base.Charsets;
import com.phloc.commons.io.streams.StringInputStream;
import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.FhirVersionEnum; import ca.uhn.fhir.context.FhirVersionEnum;
import ca.uhn.fhir.model.api.TemporalPrecisionEnum; import ca.uhn.fhir.model.api.TemporalPrecisionEnum;
@ -61,10 +67,12 @@ import ca.uhn.fhir.parser.CustomTypeDstu3Test.MyCustomPatient;
import ca.uhn.fhir.parser.IParser; import ca.uhn.fhir.parser.IParser;
import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.api.MethodOutcome;
import ca.uhn.fhir.rest.api.PreferReturnEnum; import ca.uhn.fhir.rest.api.PreferReturnEnum;
import ca.uhn.fhir.rest.client.exceptions.FhirClientConnectionException;
import ca.uhn.fhir.rest.client.interceptor.CookieInterceptor; import ca.uhn.fhir.rest.client.interceptor.CookieInterceptor;
import ca.uhn.fhir.rest.client.interceptor.UserInfoInterceptor; import ca.uhn.fhir.rest.client.interceptor.UserInfoInterceptor;
import ca.uhn.fhir.rest.param.ParamPrefixEnum; import ca.uhn.fhir.rest.param.ParamPrefixEnum;
import ca.uhn.fhir.rest.server.Constants; import ca.uhn.fhir.rest.server.Constants;
import ca.uhn.fhir.rest.server.exceptions.NotImplementedOperationException;
import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.TestUtil;
import ca.uhn.fhir.util.UrlUtil; import ca.uhn.fhir.util.UrlUtil;
import ca.uhn.fhir.util.VersionUtil; import ca.uhn.fhir.util.VersionUtil;
@ -114,6 +122,83 @@ public class GenericClientDstu3Test {
} }
} }
@Test
public void testReadWithUnparseableResponse() throws Exception {
String msg = "{\"resourceTypeeeee\":\"Patient\"}";
ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class);
when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"));
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_JSON + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8")));
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
try {
client.read().resource("Patient").withId("123").elementsSubset("name", "identifier").execute();
fail();
} catch (FhirClientConnectionException e) {
assertEquals("Failed to parse response from server when performing GET to URL http://example.com/fhir/Patient/123?_elements=identifier%2Cname - ca.uhn.fhir.parser.DataFormatException: Invalid JSON content detected, missing required element: 'resourceType'", e.getMessage());
}
}
@Test
public void testHttp501() throws Exception {
ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class);
when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 501, "Not Implemented"));
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<InputStream>() {
@Override
public StringInputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new StringInputStream("not implemented", Charsets.UTF_8);
}
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
try {
client.read().resource(Patient.class).withId("1").execute();
fail();
} catch (NotImplementedOperationException e) {
assertEquals("HTTP 501 Not Implemented", e.getMessage());
}
}
@SuppressWarnings("unchecked")
@Test
public void testClientFailures() throws Exception {
ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class);
when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse);
when(myHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"));
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).thenThrow(IllegalStateException.class, RuntimeException.class, Exception.class);
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
try {
client.read().resource(Patient.class).withId("1").execute();
fail();
} catch (FhirClientConnectionException e) {
assertEquals("java.lang.IllegalStateException", e.getMessage());
}
try {
client.read().resource(Patient.class).withId("1").execute();
fail();
} catch (RuntimeException e) {
assertEquals("java.lang.RuntimeException", e.toString());
}
try {
client.read().resource(Patient.class).withId("1").execute();
fail();
} catch (FhirClientConnectionException e) {
assertEquals("java.lang.Exception", e.getMessage());
}
}
@Test @Test
public void testBinaryCreateWithFhirContentType() throws Exception { public void testBinaryCreateWithFhirContentType() throws Exception {
IParser p = ourCtx.newXmlParser(); IParser p = ourCtx.newXmlParser();
@ -284,6 +369,7 @@ public class GenericClientDstu3Test {
assertEquals(myAnswerCount, capt.getAllValues().size()); assertEquals(myAnswerCount, capt.getAllValues().size());
assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(0).getURI().toASCIIString()); assertEquals("http://example.com/fhir/Patient", capt.getAllValues().get(0).getURI().toASCIIString());
} }
@Test @Test
public void testUserInfoInterceptor() throws Exception { public void testUserInfoInterceptor() throws Exception {
final String respString = CustomTypeDstu3Test.createBundle(CustomTypeDstu3Test.createResource(false)); final String respString = CustomTypeDstu3Test.createBundle(CustomTypeDstu3Test.createResource(false));
@ -592,7 +678,7 @@ public class GenericClientDstu3Test {
when(myHttpResponse.getAllHeaders()).thenAnswer(new Answer<Header[]>() { when(myHttpResponse.getAllHeaders()).thenAnswer(new Answer<Header[]>() {
@Override @Override
public Header[] answer(InvocationOnMock theInvocation) throws Throwable { public Header[] answer(InvocationOnMock theInvocation) throws Throwable {
return new Header[] { }; return new Header[] {};
} }
}); });
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8"));
@ -659,7 +745,6 @@ public class GenericClientDstu3Test {
assertEquals("http://example.com/fhir/Patient/222", capt.getAllValues().get(0).getURI().toASCIIString()); assertEquals("http://example.com/fhir/Patient/222", capt.getAllValues().get(0).getURI().toASCIIString());
} }
@Test @Test
public void testSearchForUnknownType() throws Exception { public void testSearchForUnknownType() throws Exception {
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
@ -671,7 +756,6 @@ public class GenericClientDstu3Test {
} }
} }
@Test @Test
public void testUserAgentForBinary() throws Exception { public void testUserAgentForBinary() throws Exception {
IParser p = ourCtx.newXmlParser(); IParser p = ourCtx.newXmlParser();
@ -805,6 +889,7 @@ public class GenericClientDstu3Test {
when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8")); when(myHttpResponse.getEntity().getContentType()).thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8"));
when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<ReaderInputStream>() { when(myHttpResponse.getEntity().getContent()).thenAnswer(new Answer<ReaderInputStream>() {
private int myCount = 0; private int myCount = 0;
@Override @Override
public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable { public ReaderInputStream answer(InvocationOnMock theInvocation) throws Throwable {
final String respString; final String respString;
@ -871,7 +956,8 @@ public class GenericClientDstu3Test {
@Override @Override
public InputStream answer(InvocationOnMock theInvocation) throws Throwable { public InputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8")); return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"));
}}); }
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0; int idx = 0;
@ -1010,7 +1096,8 @@ public class GenericClientDstu3Test {
@Override @Override
public InputStream answer(InvocationOnMock theInvocation) throws Throwable { public InputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8")); return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"));
}}); }
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0; int idx = 0;
@ -1038,7 +1125,6 @@ public class GenericClientDstu3Test {
} }
@Test @Test
public void testSearchByString() throws Exception { public void testSearchByString() throws Exception {
final String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}"; final String msg = "{\"resourceType\":\"Bundle\",\"id\":null,\"base\":\"http://localhost:57931/fhir/contextDev\",\"total\":1,\"link\":[{\"relation\":\"self\",\"url\":\"http://localhost:57931/fhir/contextDev/Patient?identifier=urn%3AMultiFhirVersionTest%7CtestSubmitPatient01&_format=json\"}],\"entry\":[{\"resource\":{\"resourceType\":\"Patient\",\"id\":\"1\",\"meta\":{\"versionId\":\"1\",\"lastUpdated\":\"2014-12-20T18:41:29.706-05:00\"},\"identifier\":[{\"system\":\"urn:MultiFhirVersionTest\",\"value\":\"testSubmitPatient01\"}]}}]}";
@ -1051,7 +1137,8 @@ public class GenericClientDstu3Test {
@Override @Override
public InputStream answer(InvocationOnMock theInvocation) throws Throwable { public InputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8")); return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"));
}}); }
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0; int idx = 0;
@ -1096,8 +1183,6 @@ public class GenericClientDstu3Test {
assertEquals("http://example.com/fhir/Patient?name=AAA,BBB", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString())); assertEquals("http://example.com/fhir/Patient?name=AAA,BBB", UrlUtil.unescape(capt.getAllValues().get(idx).getURI().toString()));
idx++; idx++;
//@formatter:off //@formatter:off
client.search() client.search()
.forResource("Patient") .forResource("Patient")
@ -1152,7 +1237,8 @@ public class GenericClientDstu3Test {
@Override @Override
public InputStream answer(InvocationOnMock theInvocation) throws Throwable { public InputStream answer(InvocationOnMock theInvocation) throws Throwable {
return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8")); return new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8"));
}}); }
});
IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir"); IGenericClient client = ourCtx.newRestfulGenericClient("http://example.com/fhir");
int idx = 0; int idx = 0;

View File

@ -21,14 +21,11 @@ import org.hl7.fhir.dstu3.model.HumanName;
import org.hl7.fhir.dstu3.model.Patient; import org.hl7.fhir.dstu3.model.Patient;
import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IBaseResource;
import org.junit.AfterClass; import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.rest.annotation.RequiredParam;
import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.annotation.Search;
import ca.uhn.fhir.rest.param.TokenParam;
import ca.uhn.fhir.util.PortUtil; import ca.uhn.fhir.util.PortUtil;
import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.TestUtil;
@ -55,6 +52,55 @@ public class SearchWithServerAddressStrategyDstu3Test {
assertThat(responseContent, containsString("<fullUrl value=\"http://localhost:" + ourPort + "/Patient/1\"/>")); assertThat(responseContent, containsString("<fullUrl value=\"http://localhost:" + ourPort + "/Patient/1\"/>"));
} }
@Test
public void testApacheProxyAddressStrategy() throws Exception {
ourServlet.setServerAddressStrategy(ApacheProxyAddressStrategy.forHttp());
HttpGet httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
HttpResponse status = ourClient.execute(httpGet);
String responseContent = IOUtils.toString(status.getEntity().getContent());
IOUtils.closeQuietly(status.getEntity().getContent());
ourLog.info(responseContent);
assertEquals(200, status.getStatusLine().getStatusCode());
assertThat(responseContent, containsString("<family value=\"FAMILY\""));
assertThat(responseContent, containsString("<fullUrl value=\"http://localhost:" + ourPort + "/Patient/1\"/>"));
ourServlet.setServerAddressStrategy(new ApacheProxyAddressStrategy(false));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
httpGet.addHeader("x-forwarded-host", "foo.com");
status = ourClient.execute(httpGet);
responseContent = IOUtils.toString(status.getEntity().getContent());
IOUtils.closeQuietly(status.getEntity().getContent());
ourLog.info(responseContent);
assertEquals(200, status.getStatusLine().getStatusCode());
assertThat(responseContent, containsString("<family value=\"FAMILY\""));
assertThat(responseContent, containsString("<fullUrl value=\"http://foo.com/Patient/1\"/>"));
ourServlet.setServerAddressStrategy(ApacheProxyAddressStrategy.forHttps());
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
httpGet.addHeader("x-forwarded-host", "foo.com");
status = ourClient.execute(httpGet);
responseContent = IOUtils.toString(status.getEntity().getContent());
IOUtils.closeQuietly(status.getEntity().getContent());
ourLog.info(responseContent);
assertEquals(200, status.getStatusLine().getStatusCode());
assertThat(responseContent, containsString("<family value=\"FAMILY\""));
assertThat(responseContent, containsString("<fullUrl value=\"https://foo.com/Patient/1\"/>"));
ourServlet.setServerAddressStrategy(new ApacheProxyAddressStrategy(false));
httpGet = new HttpGet("http://localhost:" + ourPort + "/Patient");
httpGet.addHeader("x-forwarded-host", "foo.com");
httpGet.addHeader("x-forwarded-proto", "https");
status = ourClient.execute(httpGet);
responseContent = IOUtils.toString(status.getEntity().getContent());
IOUtils.closeQuietly(status.getEntity().getContent());
ourLog.info(responseContent);
assertEquals(200, status.getStatusLine().getStatusCode());
assertThat(responseContent, containsString("<family value=\"FAMILY\""));
assertThat(responseContent, containsString("<fullUrl value=\"https://foo.com/Patient/1\"/>"));
}
@Test @Test
public void testHardcodedAddressStrategy() throws Exception { public void testHardcodedAddressStrategy() throws Exception {
ourServlet.setServerAddressStrategy(new HardcodedServerAddressStrategy("http://example.com/fhir/base")); ourServlet.setServerAddressStrategy(new HardcodedServerAddressStrategy("http://example.com/fhir/base"));