Merge pull request #1 from sekaijin/cleanup2

Cleanup2
This commit is contained in:
sekaijin 2017-02-08 17:06:53 +01:00 committed by GitHub
commit faececb246
136 changed files with 2053 additions and 2161 deletions

View File

@ -474,9 +474,8 @@ public abstract class BaseRuntimeElementCompositeDefinition<T extends IBase> ext
for (String nextName : next.getValidChildNames()) { for (String nextName : next.getValidChildNames()) {
if (myNameToChild.containsKey(nextName)) { if (myNameToChild.containsKey(nextName)) {
throw new ConfigurationException("Duplicate child name[" + nextName + "] in Element[" + getName() + "]"); throw new ConfigurationException("Duplicate child name[" + nextName + "] in Element[" + getName() + "]");
} else {
myNameToChild.put(nextName, next);
} }
myNameToChild.put(nextName, next);
} }
} }

View File

@ -148,10 +148,10 @@ public abstract class BaseRuntimeElementDefinition<T extends IBase> {
public T newInstance(Object theArgument) { public T newInstance(Object theArgument) {
try { try {
if (theArgument == null) { if (theArgument == null) {
return getConstructor(null).newInstance(null); return getConstructor(null).newInstance();
} else {
return getConstructor(theArgument).newInstance(theArgument);
} }
return getConstructor(theArgument).newInstance(theArgument);
} catch (Exception e) { } catch (Exception e) {
throw new ConfigurationException("Failed to instantiate type:" + getImplementingClass().getName(), e); throw new ConfigurationException("Failed to instantiate type:" + getImplementingClass().getName(), e);
} }
@ -171,9 +171,8 @@ public abstract class BaseRuntimeElementDefinition<T extends IBase> {
String extUrl = next.getExtensionUrl(); String extUrl = next.getExtensionUrl();
if (myUrlToExtension.containsKey(extUrl)) { if (myUrlToExtension.containsKey(extUrl)) {
throw new ConfigurationException("Duplicate extension URL[" + extUrl + "] in Element[" + getName() + "]"); throw new ConfigurationException("Duplicate extension URL[" + extUrl + "] in Element[" + getName() + "]");
} else {
myUrlToExtension.put(extUrl, next);
} }
myUrlToExtension.put(extUrl, next);
if (next.isModifier()) { if (next.isModifier()) {
myExtensionsModifier.add(next); myExtensionsModifier.add(next);
} else { } else {

View File

@ -1,7 +1,5 @@
package ca.uhn.fhir.context; package ca.uhn.fhir.context;
import java.util.concurrent.Callable;
/* /*
* #%L * #%L
* HAPI FHIR - Core Library * HAPI FHIR - Core Library

View File

@ -244,7 +244,9 @@ class ModelScanner {
} }
} }
if (blockDefinition == null && datatypeDefinition == null && resourceDefinition == null) { if (blockDefinition == null
//Redundant checking && datatypeDefinition == null && resourceDefinition == null
) {
throw new ConfigurationException("Resource class[" + theClass.getName() + "] does not contain any valid HAPI-FHIR annotations"); throw new ConfigurationException("Resource class[" + theClass.getName() + "] does not contain any valid HAPI-FHIR annotations");
} }
} }

View File

@ -114,9 +114,9 @@ public class RuntimeChildDeclaredExtensionDefinition extends RuntimeChildChoiceD
if (retVal == null) { if (retVal == null) {
if (myModifier) { if (myModifier) {
return "modifierExtension"; return "modifierExtension";
} else {
return "extension";
} }
return "extension";
} }
return retVal; return retVal;
} }

View File

@ -33,7 +33,7 @@ import ca.uhn.fhir.model.api.annotation.Description;
public class RuntimeChildDirectResource extends BaseRuntimeDeclaredChildDefinition { public class RuntimeChildDirectResource extends BaseRuntimeDeclaredChildDefinition {
private RuntimeElemContainedResources myElem; // private RuntimeElemContainedResources myElem;
private FhirContext myContext; private FhirContext myContext;
RuntimeChildDirectResource(Field theField, Child theChildAnnotation, Description theDescriptionAnnotation, String theElementName) throws ConfigurationException { RuntimeChildDirectResource(Field theField, Child theChildAnnotation, Description theDescriptionAnnotation, String theElementName) throws ConfigurationException {

View File

@ -31,7 +31,7 @@ import ca.uhn.fhir.model.api.annotation.Description;
public class RuntimeChildExtension extends RuntimeChildAny { public class RuntimeChildExtension extends RuntimeChildAny {
private RuntimeChildUndeclaredExtensionDefinition myExtensionElement; // private RuntimeChildUndeclaredExtensionDefinition myExtensionElement;
public RuntimeChildExtension(Field theField, String theElementName, Child theChildAnnotation, Description theDescriptionAnnotation) { public RuntimeChildExtension(Field theField, String theElementName, Child theChildAnnotation, Description theDescriptionAnnotation) {
super(theField, theElementName, theChildAnnotation, theDescriptionAnnotation); super(theField, theElementName, theChildAnnotation, theDescriptionAnnotation);

View File

@ -32,7 +32,7 @@ import ca.uhn.fhir.model.api.annotation.Description;
public class RuntimeChildResourceBlockDefinition extends BaseRuntimeDeclaredChildDefinition { public class RuntimeChildResourceBlockDefinition extends BaseRuntimeDeclaredChildDefinition {
private RuntimeResourceBlockDefinition myElementDef; // private RuntimeResourceBlockDefinition myElementDef;
private Class<? extends IBase> myResourceBlockType; private Class<? extends IBase> myResourceBlockType;
private FhirContext myContext; private FhirContext myContext;
@ -46,9 +46,8 @@ public class RuntimeChildResourceBlockDefinition extends BaseRuntimeDeclaredChil
public RuntimeResourceBlockDefinition getChildByName(String theName) { public RuntimeResourceBlockDefinition getChildByName(String theName) {
if (getElementName().equals(theName)) { if (getElementName().equals(theName)) {
return getDefinition(); return getDefinition();
}else {
return null;
} }
return null;
} }
private RuntimeResourceBlockDefinition getDefinition() { private RuntimeResourceBlockDefinition getDefinition() {

View File

@ -21,21 +21,16 @@ package ca.uhn.fhir.context;
*/ */
import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isBlank;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType; import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.Map; import java.util.Map;
import org.hl7.fhir.instance.model.api.IBase; import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.instance.model.api.IBaseDatatype; import org.hl7.fhir.instance.model.api.IBaseDatatype;
import org.hl7.fhir.instance.model.api.IPrimitiveType; import org.hl7.fhir.instance.model.api.IPrimitiveType;
import ca.uhn.fhir.model.api.BasePrimitive;
import ca.uhn.fhir.model.api.IPrimitiveDatatype;
import ca.uhn.fhir.model.api.annotation.DatatypeDef; import ca.uhn.fhir.model.api.annotation.DatatypeDef;
import ca.uhn.fhir.model.api.annotation.ResourceDef; import ca.uhn.fhir.model.api.annotation.ResourceDef;
import ca.uhn.fhir.util.CoverageIgnore;
public class RuntimePrimitiveDatatypeDefinition extends BaseRuntimeElementDefinition<IPrimitiveType<?>> implements IRuntimeDatatypeDefinition { public class RuntimePrimitiveDatatypeDefinition extends BaseRuntimeElementDefinition<IPrimitiveType<?>> implements IRuntimeDatatypeDefinition {

View File

@ -93,13 +93,11 @@ public class HapiLocalizer {
format = new MessageFormat(formatString.trim()); format = new MessageFormat(formatString.trim());
myKeyToMessageFormat.put(theQualifiedKey, format); myKeyToMessageFormat.put(theQualifiedKey, format);
return format.format(theParameters).toString(); return format.format(theParameters).toString();
} else {
String retVal = findFormatString(theQualifiedKey);
return retVal;
} }
String retVal = findFormatString(theQualifiedKey);
return retVal;
} }
public Set<String> getAllKeys(){ public Set<String> getAllKeys(){
HashSet<String> retVal = new HashSet<String>(); HashSet<String> retVal = new HashSet<String>();
for (ResourceBundle nextBundle : myBundle) { for (ResourceBundle nextBundle : myBundle) {

View File

@ -24,8 +24,9 @@ import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.StringDt; import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.util.ElementUtil; import ca.uhn.fhir.util.ElementUtil;
public class BaseBundle extends BaseElement implements IElement { public class BaseBundle extends BaseElement /*implements IElement*/ {
private static final long serialVersionUID = 3349586533271409727L;
private StringDt myAuthorName; private StringDt myAuthorName;
private StringDt myAuthorUri; private StringDt myAuthorUri;
private IdDt myId; private IdDt myId;

View File

@ -30,8 +30,9 @@ import org.hl7.fhir.instance.model.api.IBaseDatatype;
import ca.uhn.fhir.model.api.annotation.Child; import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Description; import ca.uhn.fhir.model.api.annotation.Description;
public abstract class BaseElement implements IElement, ISupportsUndeclaredExtensions { public abstract class BaseElement implements /*IElement, */ISupportsUndeclaredExtensions {
private static final long serialVersionUID = -3092659584634499332L;
private List<String> myFormatCommentsPost; private List<String> myFormatCommentsPost;
private List<String> myFormatCommentsPre; private List<String> myFormatCommentsPre;

View File

@ -26,6 +26,7 @@ import ca.uhn.fhir.util.CoverageIgnore;
public abstract class BaseIdentifiableElement extends BaseElement implements IIdentifiableElement { public abstract class BaseIdentifiableElement extends BaseElement implements IIdentifiableElement {
private static final long serialVersionUID = -7816838417076777914L;
private String myElementSpecificId; private String myElementSpecificId;
@Override @Override
@ -43,9 +44,8 @@ public abstract class BaseIdentifiableElement extends BaseElement implements IId
public IdDt getId() { public IdDt getId() {
if (myElementSpecificId == null) { if (myElementSpecificId == null) {
return new LockedId(); return new LockedId();
} else {
return new LockedId(myElementSpecificId);
} }
return new LockedId(myElementSpecificId);
} }
@Override @Override

View File

@ -27,7 +27,6 @@ import java.io.ObjectOutput;
import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.hl7.fhir.instance.model.api.IPrimitiveType;
import ca.uhn.fhir.parser.DataFormatException; import ca.uhn.fhir.parser.DataFormatException;

View File

@ -30,7 +30,6 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.commons.lang3.builder.ToStringStyle;
import org.hl7.fhir.instance.model.api.IBase;
import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.RuntimeResourceDefinition; import ca.uhn.fhir.context.RuntimeResourceDefinition;
@ -47,8 +46,9 @@ import ca.uhn.fhir.model.valueset.BundleTypeEnum;
import ca.uhn.fhir.rest.server.Constants; import ca.uhn.fhir.rest.server.Constants;
import ca.uhn.fhir.util.UrlUtil; import ca.uhn.fhir.util.UrlUtil;
public class Bundle extends BaseBundle implements IBase /* implements IElement */{ public class Bundle extends BaseBundle /* implements IBase implements IElement */{
private static final long serialVersionUID = 5811989173275366745L;
private ResourceMetadataMap myResourceMetadata; private ResourceMetadataMap myResourceMetadata;
private BoundCodeDt<BundleTypeEnum> myType; private BoundCodeDt<BundleTypeEnum> myType;
private StringDt myBundleId; private StringDt myBundleId;
@ -127,6 +127,7 @@ public class Bundle extends BaseBundle implements IBase /* implements IElement *
if (theResource.getId().isAbsolute()) { if (theResource.getId().isAbsolute()) {
entry.getLinkSelf().setValue(theResource.getId().getValue()); entry.getLinkSelf().setValue(theResource.getId().getValue());
//TODO: Use of a deprecated method should be resolved.
entry.getId().setValue(theResource.getId().toVersionless().getValue()); entry.getId().setValue(theResource.getId().toVersionless().getValue());
} else if (StringUtils.isNotBlank(theResource.getId().getValue())) { } else if (StringUtils.isNotBlank(theResource.getId().getValue())) {
@ -141,6 +142,7 @@ public class Bundle extends BaseBundle implements IBase /* implements IElement *
String resId = theResource.getId().getIdPart(); String resId = theResource.getId().getIdPart();
b.append(resId); b.append(resId);
//TODO: Use of a deprecated method should be resolved.
entry.getId().setValue(b.toString()); entry.getId().setValue(b.toString());
if (isNotBlank(theResource.getId().getVersionIdPart())) { if (isNotBlank(theResource.getId().getVersionIdPart())) {
@ -149,6 +151,7 @@ public class Bundle extends BaseBundle implements IBase /* implements IElement *
b.append('/'); b.append('/');
b.append(theResource.getId().getVersionIdPart()); b.append(theResource.getId().getVersionIdPart());
} else { } else {
//TODO: Use of a deprecated method should be resolved.
IdDt versionId = (IdDt) ResourceMetadataKeyEnum.VERSION_ID.get(theResource); IdDt versionId = (IdDt) ResourceMetadataKeyEnum.VERSION_ID.get(theResource);
if (versionId != null) { if (versionId != null) {
b.append('/'); b.append('/');
@ -176,6 +179,7 @@ public class Bundle extends BaseBundle implements IBase /* implements IElement *
InstantDt updated = ResourceMetadataKeyEnum.UPDATED.get(theResource); InstantDt updated = ResourceMetadataKeyEnum.UPDATED.get(theResource);
if (updated != null) { if (updated != null) {
//TODO: Use of a deprecated method should be resolved.
entry.setUpdated(updated); entry.setUpdated(updated);
} }
@ -323,6 +327,7 @@ public class Bundle extends BaseBundle implements IBase /* implements IElement *
if (map == null) { if (map == null) {
map = new HashMap<IdDt, IResource>(); map = new HashMap<IdDt, IResource>();
for (BundleEntry next : this.getEntries()) { for (BundleEntry next : this.getEntries()) {
//TODO: Use of a deprecated method should be resolved.
if (next.getId().isEmpty() == false) { if (next.getId().isEmpty() == false) {
map.put(next.getId().toUnqualified(), next.getResource()); map.put(next.getId().toUnqualified(), next.getResource());
} }

View File

@ -37,6 +37,7 @@ import ca.uhn.fhir.util.ElementUtil;
public class BundleEntry extends BaseBundle { public class BundleEntry extends BaseBundle {
private static final long serialVersionUID = 2635639739195593736L;
//@formatter:off //@formatter:off
/* **************************************************** /* ****************************************************
* NB: add any new fields to the isEmpty() method!!! * NB: add any new fields to the isEmpty() method!!!

View File

@ -36,6 +36,8 @@ import ca.uhn.fhir.model.primitive.StringDt;
@DatatypeDef(name = "Extension") @DatatypeDef(name = "Extension")
public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDatatype, IBaseExtension<ExtensionDt, IDatatype> { public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDatatype, IBaseExtension<ExtensionDt, IDatatype> {
private static final long serialVersionUID = 6399491332783085935L;
private boolean myModifier; private boolean myModifier;
@Child(name="url", type=StringDt.class, order=0, min=1, max=1) @Child(name="url", type=StringDt.class, order=0, min=1, max=1)
@ -75,6 +77,7 @@ public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDa
* since the URL itself can not contain extensions and it was therefore misleading. * since the URL itself can not contain extensions and it was therefore misleading.
* </p> * </p>
*/ */
@Override
public String getUrl() { public String getUrl() {
return myUrl != null ? myUrl.getValue() : null; return myUrl != null ? myUrl.getValue() : null;
} }
@ -95,6 +98,7 @@ public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDa
* {@link #getUndeclaredModifierExtensions()} to retrieve the child extensions. * {@link #getUndeclaredModifierExtensions()} to retrieve the child extensions.
* </p> * </p>
*/ */
@Override
public IBaseDatatype getValue() { public IBaseDatatype getValue() {
return myValue; return myValue;
} }
@ -148,6 +152,7 @@ public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDa
} }
@Override @Override
@Deprecated //override deprecated method
public <T extends IElement> List<T> getAllPopulatedChildElementsOfType(Class<T> theType) { public <T extends IElement> List<T> getAllPopulatedChildElementsOfType(Class<T> theType) {
return new ArrayList<T>(); return new ArrayList<T>();
} }

View File

@ -71,6 +71,7 @@ public interface IResource extends ICompositeElement, org.hl7.fhir.instance.mode
* *
* @since 1.5 * @since 1.5
*/ */
@Override
IBaseMetaType getMeta(); IBaseMetaType getMeta();
/** /**

View File

@ -142,9 +142,8 @@ public class Include {
int secondColon = myValue.indexOf(':', firstColon + 1); int secondColon = myValue.indexOf(':', firstColon + 1);
if (secondColon != -1) { if (secondColon != -1) {
return myValue.substring(firstColon + 1, secondColon); return myValue.substring(firstColon + 1, secondColon);
} else {
return myValue.substring(firstColon + 1);
} }
return myValue.substring(firstColon + 1);
} }
/** /**
@ -158,9 +157,8 @@ public class Include {
int secondColon = myValue.indexOf(':', firstColon + 1); int secondColon = myValue.indexOf(':', firstColon + 1);
if (secondColon != -1) { if (secondColon != -1) {
return myValue.substring(secondColon + 1); return myValue.substring(secondColon + 1);
} else {
return null;
} }
return null;
} }

View File

@ -307,21 +307,19 @@ public abstract class ResourceMetadataKeyEnum<T> implements Serializable {
Object obj = resource.getResourceMetadata().get(SECURITY_LABELS); Object obj = resource.getResourceMetadata().get(SECURITY_LABELS);
if (obj == null) { if (obj == null) {
return null; return null;
} else {
try {
@SuppressWarnings("unchecked")
List<BaseCodingDt> securityLabels = (List<BaseCodingDt>) obj;
if (securityLabels.isEmpty())
return null;
else
return securityLabels;
} catch (ClassCastException e) {
throw new InternalErrorException("Found an object of type '" + obj.getClass().getCanonicalName() + "' in resource metadata for key SECURITY_LABELS - Expected "
+ BaseCodingDt.class.getCanonicalName());
}
} }
try {
@SuppressWarnings("unchecked")
List<BaseCodingDt> securityLabels = (List<BaseCodingDt>) obj;
if (securityLabels.isEmpty()) {
return null;
}
return securityLabels;
} catch (ClassCastException e) {
throw new InternalErrorException("Found an object of type '" + obj.getClass().getCanonicalName() + "' in resource metadata for key SECURITY_LABELS - Expected "
+ BaseCodingDt.class.getCanonicalName());
}
} }
@Override @Override
@ -349,9 +347,8 @@ public abstract class ResourceMetadataKeyEnum<T> implements Serializable {
} else if (retValObj instanceof TagList) { } else if (retValObj instanceof TagList) {
if (((TagList) retValObj).isEmpty()) { if (((TagList) retValObj).isEmpty()) {
return null; return null;
} else {
return (TagList) retValObj;
} }
return (TagList) retValObj;
} }
throw new InternalErrorException("Found an object of type '" + retValObj.getClass().getCanonicalName() + "' in resource metadata for key " + TAG_LIST.name() + " - Expected " throw new InternalErrorException("Found an object of type '" + retValObj.getClass().getCanonicalName() + "' in resource metadata for key " + TAG_LIST.name() + " - Expected "
+ TagList.class.getCanonicalName()); + TagList.class.getCanonicalName());
@ -496,9 +493,8 @@ public abstract class ResourceMetadataKeyEnum<T> implements Serializable {
} else if (retValObj instanceof DecimalDt) { } else if (retValObj instanceof DecimalDt) {
if (((DecimalDt) retValObj).isEmpty()) { if (((DecimalDt) retValObj).isEmpty()) {
return null; return null;
} else {
return (DecimalDt) retValObj;
} }
return (DecimalDt) retValObj;
} else if (retValObj instanceof String) { } else if (retValObj instanceof String) {
if (StringUtils.isBlank((String) retValObj)) { if (StringUtils.isBlank((String) retValObj)) {
return null; return null;
@ -562,9 +558,8 @@ public abstract class ResourceMetadataKeyEnum<T> implements Serializable {
} else if (retValObj instanceof InstantDt) { } else if (retValObj instanceof InstantDt) {
if (((InstantDt) retValObj).isEmpty()) { if (((InstantDt) retValObj).isEmpty()) {
return null; return null;
} else { }
return (InstantDt) retValObj; return (InstantDt) retValObj;
}
} }
throw new InternalErrorException("Found an object of type '" + retValObj.getClass().getCanonicalName() + "' in resource metadata for key " + theKey.name() + " - Expected " throw new InternalErrorException("Found an object of type '" + retValObj.getClass().getCanonicalName() + "' in resource metadata for key " + theKey.name() + " - Expected "
+ InstantDt.class.getCanonicalName()); + InstantDt.class.getCanonicalName());
@ -577,9 +572,8 @@ public abstract class ResourceMetadataKeyEnum<T> implements Serializable {
} else if (retValObj instanceof String) { } else if (retValObj instanceof String) {
if (StringUtils.isBlank(((String) retValObj))) { if (StringUtils.isBlank(((String) retValObj))) {
return null; return null;
} else { }
return (String) retValObj; return (String) retValObj;
}
} }
throw new InternalErrorException("Found an object of type '" + retValObj.getClass().getCanonicalName() + "' in resource metadata for key " + theKey.name() + " - Expected " throw new InternalErrorException("Found an object of type '" + retValObj.getClass().getCanonicalName() + "' in resource metadata for key " + theKey.name() + " - Expected "
+ String.class.getCanonicalName()); + String.class.getCanonicalName());
@ -591,15 +585,13 @@ public abstract class ResourceMetadataKeyEnum<T> implements Serializable {
} else if (retValObj instanceof String) { } else if (retValObj instanceof String) {
if (isNotBlank((String) retValObj)) { if (isNotBlank((String) retValObj)) {
return new IdDt((String) retValObj); return new IdDt((String) retValObj);
} else {
return null;
} }
return null;
} else if (retValObj instanceof IdDt) { } else if (retValObj instanceof IdDt) {
if (((IdDt) retValObj).isEmpty()) { if (((IdDt) retValObj).isEmpty()) {
return null; return null;
} else {
return (IdDt) retValObj;
} }
return (IdDt) retValObj;
} else if (retValObj instanceof Number) { } else if (retValObj instanceof Number) {
return new IdDt(((Number) retValObj).toString()); return new IdDt(((Number) retValObj).toString());
} }

View File

@ -39,5 +39,5 @@ import java.lang.annotation.RetentionPolicy;
*/ */
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface ProvidesResources { public @interface ProvidesResources {
Class[] resources(); Class<?>[] resources();
} }

View File

@ -34,6 +34,8 @@ import ca.uhn.fhir.rest.param.TokenParam;
public abstract class BaseCodingDt extends BaseIdentifiableElement implements ICompositeDatatype, IQueryParameterType { public abstract class BaseCodingDt extends BaseIdentifiableElement implements ICompositeDatatype, IQueryParameterType {
private static final long serialVersionUID = 4425182816398730643L;
/** /**
* Gets the value(s) for <b>code</b> (Symbol in syntax defined by the system). creating it if it does not exist. Will not return <code>null</code>. * Gets the value(s) for <b>code</b> (Symbol in syntax defined by the system). creating it if it does not exist. Will not return <code>null</code>.
* *
@ -85,9 +87,8 @@ public abstract class BaseCodingDt extends BaseIdentifiableElement implements IC
public String getValueAsQueryToken(FhirContext theContext) { public String getValueAsQueryToken(FhirContext theContext) {
if (getSystemElement().getValueAsString() != null) { if (getSystemElement().getValueAsString() != null) {
return ParameterUtil.escape(StringUtils.defaultString(getSystemElement().getValueAsString())) + '|' + ParameterUtil.escape(getCodeElement().getValueAsString()); return ParameterUtil.escape(StringUtils.defaultString(getSystemElement().getValueAsString())) + '|' + ParameterUtil.escape(getCodeElement().getValueAsString());
} else { }
return ParameterUtil.escape(getCodeElement().getValueAsString()); return ParameterUtil.escape(getCodeElement().getValueAsString());
}
} }
/** /**

View File

@ -32,6 +32,8 @@ import ca.uhn.fhir.util.DatatypeUtil;
public abstract class BaseHumanNameDt extends BaseIdentifiableElement { public abstract class BaseHumanNameDt extends BaseIdentifiableElement {
private static final long serialVersionUID = 2765500013165698259L;
/** /**
* Gets the value(s) for <b>family</b> (Family name (often called 'Surname')). creating it if it does not exist. Will not return <code>null</code>. * Gets the value(s) for <b>family</b> (Family name (often called 'Surname')). creating it if it does not exist. Will not return <code>null</code>.
* *
@ -146,9 +148,8 @@ public abstract class BaseHumanNameDt extends BaseIdentifiableElement {
nameParts.addAll(getSuffix()); nameParts.addAll(getSuffix());
if (nameParts.size() > 0) { if (nameParts.size() > 0) {
return ca.uhn.fhir.util.DatatypeUtil.joinStringsSpaceSeparated(nameParts); return ca.uhn.fhir.util.DatatypeUtil.joinStringsSpaceSeparated(nameParts);
} else {
return getTextElement().getValue();
} }
return getTextElement().getValue();
} }
} }

View File

@ -33,6 +33,8 @@ import ca.uhn.fhir.rest.param.StringParam;
public abstract class BaseIdentifierDt extends BaseIdentifiableElement implements ICompositeDatatype, IQueryParameterType { public abstract class BaseIdentifierDt extends BaseIdentifiableElement implements ICompositeDatatype, IQueryParameterType {
private static final long serialVersionUID = 4400972469749953077L;
@Override @Override
public String getQueryParameterQualifier() { public String getQueryParameterQualifier() {
return null; return null;
@ -61,13 +63,12 @@ public abstract class BaseIdentifierDt extends BaseIdentifiableElement implement
*/ */
@Override @Override
public String getValueAsQueryToken(FhirContext theContext) { public String getValueAsQueryToken(FhirContext theContext) {
UriDt system = (UriDt) getSystemElement(); UriDt system = getSystemElement();
StringDt value = (StringDt) getValueElement(); StringDt value = getValueElement();
if (system.getValueAsString() != null) { if (system.getValueAsString() != null) {
return ParameterUtil.escape(StringUtils.defaultString(system.getValueAsString())) + '|' + ParameterUtil.escape(value.getValueAsString()); return ParameterUtil.escape(StringUtils.defaultString(system.getValueAsString())) + '|' + ParameterUtil.escape(value.getValueAsString());
} else { }
return ParameterUtil.escape(value.getValueAsString()); return ParameterUtil.escape(value.getValueAsString());
}
} }
/** /**

View File

@ -32,6 +32,8 @@ import ca.uhn.fhir.model.primitive.XhtmlDt;
*/ */
public abstract class BaseNarrativeDt<T extends Enum<?>> extends BaseIdentifiableElement implements ICompositeDatatype, INarrative { public abstract class BaseNarrativeDt<T extends Enum<?>> extends BaseIdentifiableElement implements ICompositeDatatype, INarrative {
private static final long serialVersionUID = -525238683230100077L;
public abstract BoundCodeDt<T> getStatus(); public abstract BoundCodeDt<T> getStatus();
@Override @Override

View File

@ -28,6 +28,7 @@ import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.BaseIdentifiableElement; import ca.uhn.fhir.model.api.BaseIdentifiableElement;
import ca.uhn.fhir.model.api.ICompositeDatatype; import ca.uhn.fhir.model.api.ICompositeDatatype;
import ca.uhn.fhir.model.api.IQueryParameterType; import ca.uhn.fhir.model.api.IQueryParameterType;
//TODO: Use of a deprecated method should be resolved.
import ca.uhn.fhir.model.dstu.valueset.QuantityCompararatorEnum; import ca.uhn.fhir.model.dstu.valueset.QuantityCompararatorEnum;
import ca.uhn.fhir.model.primitive.BoundCodeDt; import ca.uhn.fhir.model.primitive.BoundCodeDt;
import ca.uhn.fhir.model.primitive.CodeDt; import ca.uhn.fhir.model.primitive.CodeDt;
@ -38,7 +39,8 @@ import ca.uhn.fhir.rest.param.QuantityParam;
public abstract class BaseQuantityDt extends BaseIdentifiableElement implements ICompositeDatatype, IQueryParameterType { public abstract class BaseQuantityDt extends BaseIdentifiableElement implements ICompositeDatatype, IQueryParameterType {
private static final long serialVersionUID = -925486613033086056L;
/** /**
* Sets the value(s) for <b>value</b> (Numerical value (with implicit precision)) * Sets the value(s) for <b>value</b> (Numerical value (with implicit precision))
* *
@ -64,15 +66,19 @@ public abstract class BaseQuantityDt extends BaseIdentifiableElement implements
String[] parts = theValue.split("\\|"); String[] parts = theValue.split("\\|");
if (parts.length > 0 && StringUtils.isNotBlank(parts[0])) { if (parts.length > 0 && StringUtils.isNotBlank(parts[0])) {
if (parts[0].startsWith("<=")) { if (parts[0].startsWith("<=")) {
//TODO: Use of a deprecated method should be resolved.
getComparatorElement().setValue(QuantityCompararatorEnum.LESSTHAN_OR_EQUALS.getCode()); getComparatorElement().setValue(QuantityCompararatorEnum.LESSTHAN_OR_EQUALS.getCode());
setValue(new BigDecimal(parts[0].substring(2))); setValue(new BigDecimal(parts[0].substring(2)));
} else if (parts[0].startsWith("<")) { } else if (parts[0].startsWith("<")) {
//TODO: Use of a deprecated method should be resolved.
getComparatorElement().setValue(QuantityCompararatorEnum.LESSTHAN.getCode()); getComparatorElement().setValue(QuantityCompararatorEnum.LESSTHAN.getCode());
setValue(new BigDecimal(parts[0].substring(1))); setValue(new BigDecimal(parts[0].substring(1)));
} else if (parts[0].startsWith(">=")) { } else if (parts[0].startsWith(">=")) {
//TODO: Use of a deprecated method should be resolved.
getComparatorElement().setValue(QuantityCompararatorEnum.GREATERTHAN_OR_EQUALS.getCode()); getComparatorElement().setValue(QuantityCompararatorEnum.GREATERTHAN_OR_EQUALS.getCode());
setValue(new BigDecimal(parts[0].substring(2))); setValue(new BigDecimal(parts[0].substring(2)));
} else if (parts[0].startsWith(">")) { } else if (parts[0].startsWith(">")) {
//TODO: Use of a deprecated method should be resolved.
getComparatorElement().setValue(QuantityCompararatorEnum.GREATERTHAN.getCode()); getComparatorElement().setValue(QuantityCompararatorEnum.GREATERTHAN.getCode());
setValue(new BigDecimal(parts[0].substring(1))); setValue(new BigDecimal(parts[0].substring(1)));
} else { } else {

View File

@ -40,6 +40,8 @@ public interface BaseOperationOutcome extends IResource, IBaseOperationOutcome {
public static abstract class BaseIssue extends BaseIdentifiableElement implements IResourceBlock { public static abstract class BaseIssue extends BaseIdentifiableElement implements IResourceBlock {
private static final long serialVersionUID = 6700020892151450738L;
public abstract CodeDt getSeverityElement(); public abstract CodeDt getSeverityElement();
public abstract StringDt getDetailsElement(); public abstract StringDt getDetailsElement();

View File

@ -119,6 +119,7 @@ public enum QuantityCompararatorEnum {
/** /**
* Converts codes to their respective enumerated values * Converts codes to their respective enumerated values
*/ */
@SuppressWarnings("serial")
public static final IValueSetEnumBinder<QuantityCompararatorEnum> VALUESET_BINDER = new IValueSetEnumBinder<QuantityCompararatorEnum>() { public static final IValueSetEnumBinder<QuantityCompararatorEnum> VALUESET_BINDER = new IValueSetEnumBinder<QuantityCompararatorEnum>() {
@Override @Override
public String toCodeString(QuantityCompararatorEnum theEnum) { public String toCodeString(QuantityCompararatorEnum theEnum) {

View File

@ -98,65 +98,64 @@ public abstract class BaseDateTimeDt extends BasePrimitive<Date> {
protected String encode(Date theValue) { protected String encode(Date theValue) {
if (theValue == null) { if (theValue == null) {
return null; return null;
}
GregorianCalendar cal;
if (myTimeZoneZulu) {
cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
} else if (myTimeZone != null) {
cal = new GregorianCalendar(myTimeZone);
} else { } else {
GregorianCalendar cal; cal = new GregorianCalendar();
if (myTimeZoneZulu) { }
cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); cal.setTime(theValue);
} else if (myTimeZone != null) {
cal = new GregorianCalendar(myTimeZone);
} else {
cal = new GregorianCalendar();
}
cal.setTime(theValue);
StringBuilder b = new StringBuilder(); StringBuilder b = new StringBuilder();
leftPadWithZeros(cal.get(Calendar.YEAR), 4, b); leftPadWithZeros(cal.get(Calendar.YEAR), 4, b);
if (myPrecision.ordinal() > TemporalPrecisionEnum.YEAR.ordinal()) { if (myPrecision.ordinal() > TemporalPrecisionEnum.YEAR.ordinal()) {
b.append('-');
leftPadWithZeros(cal.get(Calendar.MONTH) + 1, 2, b);
if (myPrecision.ordinal() > TemporalPrecisionEnum.MONTH.ordinal()) {
b.append('-'); b.append('-');
leftPadWithZeros(cal.get(Calendar.MONTH) + 1, 2, b); leftPadWithZeros(cal.get(Calendar.DATE), 2, b);
if (myPrecision.ordinal() > TemporalPrecisionEnum.MONTH.ordinal()) { if (myPrecision.ordinal() > TemporalPrecisionEnum.DAY.ordinal()) {
b.append('-'); b.append('T');
leftPadWithZeros(cal.get(Calendar.DATE), 2, b); leftPadWithZeros(cal.get(Calendar.HOUR_OF_DAY), 2, b);
if (myPrecision.ordinal() > TemporalPrecisionEnum.DAY.ordinal()) { b.append(':');
b.append('T'); leftPadWithZeros(cal.get(Calendar.MINUTE), 2, b);
leftPadWithZeros(cal.get(Calendar.HOUR_OF_DAY), 2, b); if (myPrecision.ordinal() > TemporalPrecisionEnum.MINUTE.ordinal()) {
b.append(':'); b.append(':');
leftPadWithZeros(cal.get(Calendar.MINUTE), 2, b); leftPadWithZeros(cal.get(Calendar.SECOND), 2, b);
if (myPrecision.ordinal() > TemporalPrecisionEnum.MINUTE.ordinal()) { if (myPrecision.ordinal() > TemporalPrecisionEnum.SECOND.ordinal()) {
b.append(':'); b.append('.');
leftPadWithZeros(cal.get(Calendar.SECOND), 2, b); b.append(myFractionalSeconds);
if (myPrecision.ordinal() > TemporalPrecisionEnum.SECOND.ordinal()) { for (int i = myFractionalSeconds.length(); i < 3; i++) {
b.append('.'); b.append('0');
b.append(myFractionalSeconds);
for (int i = myFractionalSeconds.length(); i < 3; i++) {
b.append('0');
}
} }
} }
}
if (myTimeZoneZulu) { if (myTimeZoneZulu) {
b.append('Z'); b.append('Z');
} else if (myTimeZone != null) { } else if (myTimeZone != null) {
int offset = myTimeZone.getOffset(theValue.getTime()); int offset = myTimeZone.getOffset(theValue.getTime());
if (offset >= 0) { if (offset >= 0) {
b.append('+'); b.append('+');
} else { } else {
b.append('-'); b.append('-');
offset = Math.abs(offset); offset = Math.abs(offset);
}
int hoursOffset = (int) (offset / DateUtils.MILLIS_PER_HOUR);
leftPadWithZeros(hoursOffset, 2, b);
b.append(':');
int minutesOffset = (int) (offset % DateUtils.MILLIS_PER_HOUR);
minutesOffset = (int) (minutesOffset / DateUtils.MILLIS_PER_MINUTE);
leftPadWithZeros(minutesOffset, 2, b);
} }
int hoursOffset = (int) (offset / DateUtils.MILLIS_PER_HOUR);
leftPadWithZeros(hoursOffset, 2, b);
b.append(':');
int minutesOffset = (int) (offset % DateUtils.MILLIS_PER_HOUR);
minutesOffset = (int) (minutesOffset / DateUtils.MILLIS_PER_MINUTE);
leftPadWithZeros(minutesOffset, 2, b);
} }
} }
} }
return b.toString();
} }
return b.toString();
} }
/** /**
@ -671,7 +670,7 @@ public abstract class BaseDateTimeDt extends BasePrimitive<Date> {
public BaseDateTimeDt setNanos(long theNanos) { public BaseDateTimeDt setNanos(long theNanos) {
validateValueInRange(theNanos, 0, NANOS_PER_SECOND-1); validateValueInRange(theNanos, 0, NANOS_PER_SECOND-1);
String fractionalSeconds = StringUtils.leftPad(Long.toString(theNanos), 9, '0'); String fractionalSeconds = StringUtils.leftPad(Long.toString(theNanos), 9, '0');
// Strip trailing 0s // Strip trailing 0s
for (int i = fractionalSeconds.length(); i > 0; i--) { for (int i = fractionalSeconds.length(); i > 0; i--) {
if (fractionalSeconds.charAt(i-1) != '0') { if (fractionalSeconds.charAt(i-1) != '0') {

View File

@ -60,9 +60,8 @@ public class BooleanDt extends BasePrimitive<Boolean> implements IBaseBooleanDat
protected String encode(Boolean theValue) { protected String encode(Boolean theValue) {
if (Boolean.TRUE.equals(theValue)) { if (Boolean.TRUE.equals(theValue)) {
return "true"; return "true";
} else {
return "false";
} }
return "false";
} }
} }

View File

@ -34,7 +34,6 @@ import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.instance.model.api.IIdType;
import ca.uhn.fhir.model.api.IPrimitiveDatatype;
import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.api.annotation.DatatypeDef; import ca.uhn.fhir.model.api.annotation.DatatypeDef;
import ca.uhn.fhir.model.api.annotation.SimpleSetter; import ca.uhn.fhir.model.api.annotation.SimpleSetter;
@ -54,7 +53,7 @@ import ca.uhn.fhir.util.UrlUtil;
* </p> * </p>
*/ */
@DatatypeDef(name = "id", profileOf = StringDt.class) @DatatypeDef(name = "id", profileOf = StringDt.class)
public class IdDt extends UriDt implements IPrimitiveDatatype<String>, IIdType { public class IdDt extends UriDt implements /*IPrimitiveDatatype<String>, */IIdType {
private String myBaseUrl; private String myBaseUrl;
private boolean myHaveComponentParts; private boolean myHaveComponentParts;
@ -183,6 +182,7 @@ public class IdDt extends UriDt implements IPrimitiveDatatype<String>, IIdType {
setValue(theUrl.getValueAsString()); setValue(theUrl.getValueAsString());
} }
@Override
public void applyTo(IBaseResource theResouce) { public void applyTo(IBaseResource theResouce) {
if (theResouce == null) { if (theResouce == null) {
throw new NullPointerException("theResource can not be null"); throw new NullPointerException("theResource can not be null");
@ -332,12 +332,12 @@ public class IdDt extends UriDt implements IPrimitiveDatatype<String>, IIdType {
return myUnqualifiedVersionId; return myUnqualifiedVersionId;
} }
@Override
public Long getVersionIdPartAsLong() { public Long getVersionIdPartAsLong() {
if (!hasVersionIdPart()) { if (!hasVersionIdPart()) {
return null; return null;
} else {
return Long.parseLong(getVersionIdPart());
} }
return Long.parseLong(getVersionIdPart());
} }
/** /**
@ -345,6 +345,7 @@ public class IdDt extends UriDt implements IPrimitiveDatatype<String>, IIdType {
* *
* @see #getBaseUrl() * @see #getBaseUrl()
*/ */
@Override
public boolean hasBaseUrl() { public boolean hasBaseUrl() {
return isNotBlank(myBaseUrl); return isNotBlank(myBaseUrl);
} }
@ -440,7 +441,9 @@ public class IdDt extends UriDt implements IPrimitiveDatatype<String>, IIdType {
/** /**
* Copies the value from the given IdDt to <code>this</code> IdDt. It is generally not neccesary to use this method but it is provided for consistency with the rest of the API. * Copies the value from the given IdDt to <code>this</code> IdDt. It is generally not neccesary to use this method but it is provided for consistency with the rest of the API.
* @deprecated
*/ */
@Deprecated //override deprecated method
@Override @Override
public void setId(IdDt theId) { public void setId(IdDt theId) {
setValue(theId.getValue()); setValue(theId.getValue());
@ -666,15 +669,14 @@ public class IdDt extends UriDt implements IPrimitiveDatatype<String>, IIdType {
public static IdDt of(IBaseResource theResouce) { public static IdDt of(IBaseResource theResouce) {
if (theResouce == null) { if (theResouce == null) {
throw new NullPointerException("theResource can not be null"); throw new NullPointerException("theResource can not be null");
}
IIdType retVal = theResouce.getIdElement();
if (retVal == null) {
return null;
} else if (retVal instanceof IdDt) {
return (IdDt) retVal;
} else { } else {
IIdType retVal = theResouce.getIdElement(); return new IdDt(retVal.getValue());
if (retVal == null) {
return null;
} else if (retVal instanceof IdDt) {
return (IdDt) retVal;
} else {
return new IdDt(retVal.getValue());
}
} }
} }

View File

@ -90,6 +90,9 @@ public enum BundleEntrySearchModeEnum {
* Converts codes to their respective enumerated values * Converts codes to their respective enumerated values
*/ */
public static final IValueSetEnumBinder<BundleEntrySearchModeEnum> VALUESET_BINDER = new IValueSetEnumBinder<BundleEntrySearchModeEnum>() { public static final IValueSetEnumBinder<BundleEntrySearchModeEnum> VALUESET_BINDER = new IValueSetEnumBinder<BundleEntrySearchModeEnum>() {
private static final long serialVersionUID = -3836039426814809083L;
@Override @Override
public String toCodeString(BundleEntrySearchModeEnum theEnum) { public String toCodeString(BundleEntrySearchModeEnum theEnum) {
return theEnum.getCode(); return theEnum.getCode();

View File

@ -97,6 +97,9 @@ public enum BundleEntryTransactionMethodEnum {
* Converts codes to their respective enumerated values * Converts codes to their respective enumerated values
*/ */
public static final IValueSetEnumBinder<BundleEntryTransactionMethodEnum> VALUESET_BINDER = new IValueSetEnumBinder<BundleEntryTransactionMethodEnum>() { public static final IValueSetEnumBinder<BundleEntryTransactionMethodEnum> VALUESET_BINDER = new IValueSetEnumBinder<BundleEntryTransactionMethodEnum>() {
private static final long serialVersionUID = 7569681479045998433L;
@Override @Override
public String toCodeString(BundleEntryTransactionMethodEnum theEnum) { public String toCodeString(BundleEntryTransactionMethodEnum theEnum) {
return theEnum.getCode(); return theEnum.getCode();

View File

@ -102,6 +102,9 @@ public enum BundleTypeEnum {
* Converts codes to their respective enumerated values * Converts codes to their respective enumerated values
*/ */
public static final IValueSetEnumBinder<BundleTypeEnum> VALUESET_BINDER = new IValueSetEnumBinder<BundleTypeEnum>() { public static final IValueSetEnumBinder<BundleTypeEnum> VALUESET_BINDER = new IValueSetEnumBinder<BundleTypeEnum>() {
private static final long serialVersionUID = -305725916208867517L;
@Override @Override
public String toCodeString(BundleTypeEnum theEnum) { public String toCodeString(BundleTypeEnum theEnum) {
return theEnum.getCode(); return theEnum.getCode();

View File

@ -85,10 +85,7 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener
initialize(theContext); initialize(theContext);
} }
String name = null; String name = myClassToName.get(theResource.getClass());
if (name == null) {
name = myClassToName.get(theResource.getClass());
}
if (name == null) { if (name == null) {
name = theContext.getResourceDefinition(theResource).getName().toLowerCase(); name = theContext.getResourceDefinition(theResource).getName().toLowerCase();
} }
@ -97,9 +94,8 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener
if (myIgnoreMissingTemplates) { if (myIgnoreMissingTemplates) {
ourLog.debug("No narrative template available for resorce: {}", name); ourLog.debug("No narrative template available for resorce: {}", name);
return; return;
} else {
throw new DataFormatException("No narrative template for class " + theResource.getClass().getCanonicalName());
} }
throw new DataFormatException("No narrative template for class " + theResource.getClass().getCanonicalName());
} }
try { try {
@ -132,10 +128,9 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener
} }
theNarrative.setStatusAsString("empty"); theNarrative.setStatusAsString("empty");
return; return;
} else { }
throw new DataFormatException(e); throw new DataFormatException(e);
} }
}
} }
protected abstract List<String> getPropertyFile(); protected abstract List<String> getPropertyFile();
@ -229,6 +224,7 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener
String narrativePropName = name + ".narrative"; String narrativePropName = name + ".narrative";
String narrativeName = file.getProperty(narrativePropName); String narrativeName = file.getProperty(narrativePropName);
if (isBlank(narrativeName)) { if (isBlank(narrativeName)) {
//FIXME resource leak
throw new ConfigurationException("Found property '" + nextKey + "' but no corresponding property '" + narrativePropName + "' in file " + propFileName); throw new ConfigurationException("Found property '" + nextKey + "' but no corresponding property '" + narrativePropName + "' in file " + propFileName);
} }
@ -289,6 +285,7 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener
throw new IOException("Can not find '" + cpName + "' on classpath"); throw new IOException("Can not find '" + cpName + "' on classpath");
} }
} }
//FIXME resource leak
return resource; return resource;
} else if (name.startsWith("file:")) { } else if (name.startsWith("file:")) {
File file = new File(name.substring("file:".length())); File file = new File(name.substring("file:".length()));
@ -418,31 +415,30 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener
context.setVariable("resource", value); context.setVariable("resource", value);
String name = null; String name = null;
if (value != null) {
Class<? extends Object> nextClass = value.getClass();
do {
name = myClassToName.get(nextClass);
nextClass = nextClass.getSuperclass();
} while (name == null && nextClass.equals(Object.class) == false);
if (name == null) { Class<? extends Object> nextClass = value.getClass();
if (value instanceof IBaseResource) { do {
name = myContext.getResourceDefinition((Class<? extends IBaseResource>) value).getName(); name = myClassToName.get(nextClass);
} else if (value instanceof IDatatype) { nextClass = nextClass.getSuperclass();
name = value.getClass().getSimpleName(); } while (name == null && nextClass.equals(Object.class) == false);
name = name.substring(0, name.length() - 2);
} else if (value instanceof IBaseDatatype) { if (name == null) {
name = value.getClass().getSimpleName(); if (value instanceof IBaseResource) {
if (name.endsWith("Type")) { name = myContext.getResourceDefinition((Class<? extends IBaseResource>) value).getName();
name = name.substring(0, name.length() - 4); } else if (value instanceof IDatatype) {
} name = value.getClass().getSimpleName();
} else { name = name.substring(0, name.length() - 2);
throw new DataFormatException("Don't know how to determine name for type: " + value.getClass()); } else if (value instanceof IBaseDatatype) {
} name = value.getClass().getSimpleName();
name = name.toLowerCase(); if (name.endsWith("Type")) {
if (!myNameToNarrativeTemplate.containsKey(name)) { name = name.substring(0, name.length() - 4);
name = null;
} }
} else {
throw new DataFormatException("Don't know how to determine name for type: " + value.getClass());
}
name = name.toLowerCase();
if (!myNameToNarrativeTemplate.containsKey(name)) {
name = null;
} }
} }
@ -450,9 +446,8 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener
if (myIgnoreMissingTemplates) { if (myIgnoreMissingTemplates) {
ourLog.debug("No narrative template available for type: {}", value.getClass()); ourLog.debug("No narrative template available for type: {}", value.getClass());
return; return;
} else {
throw new DataFormatException("No narrative template for class " + value.getClass());
} }
throw new DataFormatException("No narrative template for class " + value.getClass());
} }
String result = myProfileTemplateEngine.process(name, context); String result = myProfileTemplateEngine.process(name, context);

View File

@ -305,24 +305,20 @@ public abstract class BaseParser implements IParser {
} }
} }
return reference; return reference;
} else {
if (!ref.hasResourceType() && !ref.isLocal() && theRef.getResource() != null) {
ref = ref.withResourceType(myContext.getResourceDefinition(theRef.getResource()).getName());
}
if (isNotBlank(myServerBaseUrl) && StringUtils.equals(myServerBaseUrl, ref.getBaseUrl())) {
if (isStripVersionsFromReferences(theCompositeChildElement)) {
return ref.toUnqualifiedVersionless().getValue();
} else {
return ref.toUnqualified().getValue();
}
} else {
if (isStripVersionsFromReferences(theCompositeChildElement)) {
return ref.toVersionless().getValue();
} else {
return ref.getValue();
}
}
} }
if (!ref.hasResourceType() && !ref.isLocal() && theRef.getResource() != null) {
ref = ref.withResourceType(myContext.getResourceDefinition(theRef.getResource()).getName());
}
if (isNotBlank(myServerBaseUrl) && StringUtils.equals(myServerBaseUrl, ref.getBaseUrl())) {
if (isStripVersionsFromReferences(theCompositeChildElement)) {
return ref.toUnqualifiedVersionless().getValue();
}
return ref.toUnqualified().getValue();
}
if (isStripVersionsFromReferences(theCompositeChildElement)) {
return ref.toVersionless().getValue();
}
return ref.getValue();
} }
private boolean isStripVersionsFromReferences(CompositeChildElement theCompositeChildElement) { private boolean isStripVersionsFromReferences(CompositeChildElement theCompositeChildElement) {
@ -1112,9 +1108,8 @@ public abstract class BaseParser implements IParser {
} }
if (theElements.contains(thePathBuilder.toString())) { if (theElements.contains(thePathBuilder.toString())) {
return true; return true;
} else {
return false;
} }
return false;
} else if (myParent != null) { } else if (myParent != null) {
boolean parentCheck; boolean parentCheck;
if (theCheckingForWhitelist) { if (theCheckingForWhitelist) {

View File

@ -25,37 +25,74 @@ import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.apache.commons.lang3.StringUtils.isNotBlank;
import java.io.IOException; import java.io.IOException;
import java.io.PushbackReader;
import java.io.Reader; import java.io.Reader;
import java.io.Writer; import java.io.Writer;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.*; import java.util.ArrayList;
import java.util.Map.Entry; import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.text.WordUtils; import org.apache.commons.lang3.text.WordUtils;
import org.hl7.fhir.instance.model.api.*; import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.instance.model.api.IBaseBinary;
import org.hl7.fhir.instance.model.api.IBaseBooleanDatatype;
import org.hl7.fhir.instance.model.api.IBaseDecimalDatatype;
import org.hl7.fhir.instance.model.api.IBaseExtension;
import org.hl7.fhir.instance.model.api.IBaseHasExtensions;
import org.hl7.fhir.instance.model.api.IBaseHasModifierExtensions;
import org.hl7.fhir.instance.model.api.IBaseIntegerDatatype;
import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IDomainResource;
import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.instance.model.api.INarrative;
import org.hl7.fhir.instance.model.api.IPrimitiveType;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.GsonBuilder; import com.google.gson.GsonBuilder;
import ca.uhn.fhir.context.*; import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementDefinition.ChildTypeEnum; import ca.uhn.fhir.context.BaseRuntimeElementDefinition.ChildTypeEnum;
import ca.uhn.fhir.model.api.*; import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.FhirVersionEnum;
import ca.uhn.fhir.context.RuntimeChildContainedResources;
import ca.uhn.fhir.context.RuntimeChildDeclaredExtensionDefinition;
import ca.uhn.fhir.context.RuntimeChildNarrativeDefinition;
import ca.uhn.fhir.context.RuntimeChildUndeclaredExtensionDefinition;
import ca.uhn.fhir.context.RuntimeResourceDefinition;
import ca.uhn.fhir.model.api.BaseBundle;
import ca.uhn.fhir.model.api.Bundle;
import ca.uhn.fhir.model.api.BundleEntry;
import ca.uhn.fhir.model.api.ExtensionDt;
import ca.uhn.fhir.model.api.IPrimitiveDatatype;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.api.ISupportsUndeclaredExtensions;
import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
import ca.uhn.fhir.model.api.Tag;
import ca.uhn.fhir.model.api.TagList;
import ca.uhn.fhir.model.api.annotation.Child; import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.base.composite.BaseCodingDt; import ca.uhn.fhir.model.base.composite.BaseCodingDt;
import ca.uhn.fhir.model.base.composite.BaseContainedDt; import ca.uhn.fhir.model.base.composite.BaseContainedDt;
import ca.uhn.fhir.model.primitive.*; import ca.uhn.fhir.model.primitive.DecimalDt;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.InstantDt;
import ca.uhn.fhir.model.primitive.IntegerDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.narrative.INarrativeGenerator; import ca.uhn.fhir.narrative.INarrativeGenerator;
import ca.uhn.fhir.parser.json.GsonStructure; import ca.uhn.fhir.parser.json.GsonStructure;
import ca.uhn.fhir.parser.json.JsonLikeArray; import ca.uhn.fhir.parser.json.JsonLikeArray;
import ca.uhn.fhir.parser.json.JsonLikeObject; import ca.uhn.fhir.parser.json.JsonLikeObject;
import ca.uhn.fhir.parser.json.JsonLikeStructure; import ca.uhn.fhir.parser.json.JsonLikeStructure;
import ca.uhn.fhir.parser.json.JsonLikeValue; import ca.uhn.fhir.parser.json.JsonLikeValue;
import ca.uhn.fhir.parser.json.JsonLikeWriter;
import ca.uhn.fhir.parser.json.JsonLikeValue.ScalarType; import ca.uhn.fhir.parser.json.JsonLikeValue.ScalarType;
import ca.uhn.fhir.parser.json.JsonLikeValue.ValueType; import ca.uhn.fhir.parser.json.JsonLikeValue.ValueType;
import ca.uhn.fhir.parser.json.JsonLikeWriter;
import ca.uhn.fhir.rest.server.EncodingEnum; import ca.uhn.fhir.rest.server.EncodingEnum;
import ca.uhn.fhir.util.ElementUtil; import ca.uhn.fhir.util.ElementUtil;
@ -110,9 +147,8 @@ public class JsonParser extends BaseParser implements IJsonLikeParser {
} }
theListToAddTo.get(valueIdx).addAll(theCommentsToAdd); theListToAddTo.get(valueIdx).addAll(theCommentsToAdd);
return true; return true;
} else {
return false;
} }
return false;
} }
private boolean addToHeldExtensions(int valueIdx, List<? extends IBaseExtension<?, ?>> ext, ArrayList<ArrayList<HeldExtension>> list, boolean theIsModifier, CompositeChildElement theChildElem) { private boolean addToHeldExtensions(int valueIdx, List<? extends IBaseExtension<?, ?>> ext, ArrayList<ArrayList<HeldExtension>> list, boolean theIsModifier, CompositeChildElement theChildElem) {
@ -128,9 +164,8 @@ public class JsonParser extends BaseParser implements IJsonLikeParser {
list.get(valueIdx).add(new HeldExtension(next, theIsModifier, theChildElem)); list.get(valueIdx).add(new HeldExtension(next, theIsModifier, theChildElem));
} }
return true; return true;
} else {
return false;
} }
return false;
} }
private void addToHeldIds(int theValueIdx, ArrayList<String> theListToAddTo, String theId) { private void addToHeldIds(int theValueIdx, ArrayList<String> theListToAddTo, String theId) {
@ -143,7 +178,7 @@ public class JsonParser extends BaseParser implements IJsonLikeParser {
} }
} }
private void assertObjectOfType(JsonLikeValue theResourceTypeObj, Object theValueType, String thePosition) { // private void assertObjectOfType(JsonLikeValue theResourceTypeObj, Object theValueType, String thePosition) {
// if (theResourceTypeObj == null) { // if (theResourceTypeObj == null) {
// throw new DataFormatException("Invalid JSON content detected, missing required element: '" + thePosition + "'"); // throw new DataFormatException("Invalid JSON content detected, missing required element: '" + thePosition + "'");
// } // }
@ -151,7 +186,7 @@ public class JsonParser extends BaseParser implements IJsonLikeParser {
// if (theResourceTypeObj.getValueType() != theValueType) { // if (theResourceTypeObj.getValueType() != theValueType) {
// throw new DataFormatException("Invalid content of element " + thePosition + ", expected " + theValueType); // throw new DataFormatException("Invalid content of element " + thePosition + ", expected " + theValueType);
// } // }
} // }
private void beginArray(JsonLikeWriter theEventWriter, String arrayName) throws IOException { private void beginArray(JsonLikeWriter theEventWriter, String arrayName) throws IOException {
theEventWriter.beginArray(arrayName); theEventWriter.beginArray(arrayName);
@ -281,6 +316,7 @@ public class JsonParser extends BaseParser implements IJsonLikeParser {
writeTagWithTextNode(theEventWriter, "deleted", nextEntry.getDeletedAt()); writeTagWithTextNode(theEventWriter, "deleted", nextEntry.getDeletedAt());
} }
writeTagWithTextNode(theEventWriter, "title", nextEntry.getTitle()); writeTagWithTextNode(theEventWriter, "title", nextEntry.getTitle());
//TODO: Use of a deprecated method should be resolved.
writeTagWithTextNode(theEventWriter, "id", nextEntry.getId()); writeTagWithTextNode(theEventWriter, "id", nextEntry.getId());
linkStarted = false; linkStarted = false;
@ -291,6 +327,7 @@ public class JsonParser extends BaseParser implements IJsonLikeParser {
theEventWriter.endArray(); theEventWriter.endArray();
} }
//TODO: Use of a deprecated method should be resolved.
writeOptionalTagWithTextNode(theEventWriter, "updated", nextEntry.getUpdated()); writeOptionalTagWithTextNode(theEventWriter, "updated", nextEntry.getUpdated());
writeOptionalTagWithTextNode(theEventWriter, "published", nextEntry.getPublished()); writeOptionalTagWithTextNode(theEventWriter, "published", nextEntry.getPublished());
@ -575,7 +612,7 @@ public class JsonParser extends BaseParser implements IJsonLikeParser {
} }
if (narr != null && narr.isEmpty()) { if (narr != null && narr.isEmpty()) {
gen.generateNarrative(myContext, theResource, narr); gen.generateNarrative(myContext, theResource, narr);
if (narr != null && !narr.isEmpty()) { if (!narr.isEmpty()) {
RuntimeChildNarrativeDefinition child = (RuntimeChildNarrativeDefinition) nextChild; RuntimeChildNarrativeDefinition child = (RuntimeChildNarrativeDefinition) nextChild;
String childName = nextChild.getChildNameByDatatype(child.getDatatype()); String childName = nextChild.getChildNameByDatatype(child.getDatatype());
BaseRuntimeElementDefinition<?> type = child.getChildByName(childName); BaseRuntimeElementDefinition<?> type = child.getChildByName(childName);
@ -980,7 +1017,7 @@ public class JsonParser extends BaseParser implements IJsonLikeParser {
for (RuntimeChildDeclaredExtensionDefinition nextDef : resDef.getExtensionsNonModifier()) { for (RuntimeChildDeclaredExtensionDefinition nextDef : resDef.getExtensionsNonModifier()) {
for (IBase nextValue : nextDef.getAccessor().getValues(theResource)) { for (IBase nextValue : nextDef.getAccessor().getValues(theResource)) {
if (nextValue != null) { if (nextValue != null) {
if (nextValue == null || nextValue.isEmpty()) { if (nextValue.isEmpty()) {
continue; continue;
} }
extensions.add(new HeldExtension(nextDef, nextValue, theChildElem)); extensions.add(new HeldExtension(nextDef, nextValue, theChildElem));
@ -990,7 +1027,7 @@ public class JsonParser extends BaseParser implements IJsonLikeParser {
for (RuntimeChildDeclaredExtensionDefinition nextDef : resDef.getExtensionsModifier()) { for (RuntimeChildDeclaredExtensionDefinition nextDef : resDef.getExtensionsModifier()) {
for (IBase nextValue : nextDef.getAccessor().getValues(theResource)) { for (IBase nextValue : nextDef.getAccessor().getValues(theResource)) {
if (nextValue != null) { if (nextValue != null) {
if (nextValue == null || nextValue.isEmpty()) { if (nextValue.isEmpty()) {
continue; continue;
} }
modifierExtensions.add(new HeldExtension(nextDef, nextValue, theChildElem)); modifierExtensions.add(new HeldExtension(nextDef, nextValue, theChildElem));
@ -1106,7 +1143,7 @@ public class JsonParser extends BaseParser implements IJsonLikeParser {
} }
JsonLikeValue alternateVal = theAlternateVal; JsonLikeValue alternateVal = theAlternateVal;
if (alternateVal != null && alternateVal.isObject() == false) { if (alternateVal.isObject() == false) {
getErrorHandler().incorrectJsonType(null, theAlternateName, ValueType.OBJECT, null, alternateVal.getJsonType(), null); getErrorHandler().incorrectJsonType(null, theAlternateName, ValueType.OBJECT, null, alternateVal.getJsonType(), null);
return; return;
} }

View File

@ -142,6 +142,7 @@ class ParserState<T> {
if (entry.getLinkSelf() != null && entry.getLinkSelf().isEmpty() == false) { if (entry.getLinkSelf() != null && entry.getLinkSelf().isEmpty() == false) {
id = new IdDt(entry.getLinkSelf().getValue()); id = new IdDt(entry.getLinkSelf().getValue());
} else { } else {
//TODO: Use of a deprecated method should be resolved.
id = entry.getId(); id = entry.getId();
} }
@ -159,6 +160,7 @@ class ParserState<T> {
if (resource != null) { if (resource != null) {
resource.getResourceMetadata().put(ResourceMetadataKeyEnum.DELETED_AT, entry.getDeletedAt()); resource.getResourceMetadata().put(ResourceMetadataKeyEnum.DELETED_AT, entry.getDeletedAt());
//TODO: Use of a deprecated method should be resolved.
resource.getResourceMetadata().put(ResourceMetadataKeyEnum.VERSION_ID, id); resource.getResourceMetadata().put(ResourceMetadataKeyEnum.VERSION_ID, id);
} }
} }
@ -364,6 +366,7 @@ class ParserState<T> {
@Override @Override
public void attributeValue(String theName, String theValue) throws DataFormatException { public void attributeValue(String theName, String theValue) throws DataFormatException {
if ("ref".equals(theName)) { if ("ref".equals(theName)) {
//TODO: Use of a deprecated method should be resolved.
getEntry().setId(new IdDt(theValue)); getEntry().setId(new IdDt(theValue));
} else if ("when".equals(theName)) { } else if ("when".equals(theName)) {
getEntry().setDeleted(new InstantDt(theValue)); getEntry().setDeleted(new InstantDt(theValue));
@ -451,10 +454,12 @@ class ParserState<T> {
if ("title".equals(theLocalPart)) { if ("title".equals(theLocalPart)) {
push(new AtomPrimitiveState(myEntry.getTitle())); push(new AtomPrimitiveState(myEntry.getTitle()));
} else if ("id".equals(theLocalPart)) { } else if ("id".equals(theLocalPart)) {
//TODO: Use of a deprecated method should be resolved.
push(new AtomPrimitiveState(myEntry.getId())); push(new AtomPrimitiveState(myEntry.getId()));
} else if ("link".equals(theLocalPart)) { } else if ("link".equals(theLocalPart)) {
push(new AtomLinkState(myEntry)); push(new AtomLinkState(myEntry));
} else if ("updated".equals(theLocalPart)) { } else if ("updated".equals(theLocalPart)) {
//TODO: Use of a deprecated method should be resolved.
push(new AtomPrimitiveState(myEntry.getUpdated())); push(new AtomPrimitiveState(myEntry.getUpdated()));
} else if ("published".equals(theLocalPart)) { } else if ("published".equals(theLocalPart)) {
push(new AtomPrimitiveState(myEntry.getPublished())); push(new AtomPrimitiveState(myEntry.getPublished()));
@ -771,7 +776,7 @@ class ParserState<T> {
myErrorHandler.unknownAttribute(null, theName); myErrorHandler.unknownAttribute(null, theName);
} }
public boolean elementIsRepeating(@SuppressWarnings("unused") String theChildName) { public boolean elementIsRepeating(String theChildName) {
return false; return false;
} }
@ -790,7 +795,6 @@ class ParserState<T> {
/** /**
* Default implementation just handles undeclared extensions * Default implementation just handles undeclared extensions
*/ */
@SuppressWarnings("unused")
public void enteringNewElementExtension(StartElement theElement, String theUrlAttr, boolean theIsModifier) { public void enteringNewElementExtension(StartElement theElement, String theUrlAttr, boolean theIsModifier) {
if (myPreResourceState != null && getCurrentElement() instanceof ISupportsUndeclaredExtensions) { if (myPreResourceState != null && getCurrentElement() instanceof ISupportsUndeclaredExtensions) {
ExtensionDt newExtension = new ExtensionDt(theIsModifier); ExtensionDt newExtension = new ExtensionDt(theIsModifier);
@ -1031,6 +1035,7 @@ class ParserState<T> {
@Override @Override
public void enteringNewElement(String theNamespaceUri, String theLocalPart) throws DataFormatException { public void enteringNewElement(String theNamespaceUri, String theLocalPart) throws DataFormatException {
if ("base".equals(theLocalPart)) { if ("base".equals(theLocalPart)) {
//TODO: Use of a deprecated method should be resolved.
push(new PrimitiveState(getPreResourceState(), myEntry.getLinkBase())); push(new PrimitiveState(getPreResourceState(), myEntry.getLinkBase()));
} else if ("request".equals(theLocalPart)) { } else if ("request".equals(theLocalPart)) {
push(new BundleEntryTransactionState(myEntry)); push(new BundleEntryTransactionState(myEntry));
@ -1302,6 +1307,7 @@ class ParserState<T> {
} }
String bundleBaseUrl = myInstance.getLinkBase().getValue(); String bundleBaseUrl = myInstance.getLinkBase().getValue();
//TODO: Use of a deprecated method should be resolved.
String entryBaseUrl = nextEntry.getLinkBase().getValue(); String entryBaseUrl = nextEntry.getLinkBase().getValue();
String version = ResourceMetadataKeyEnum.VERSION.get(nextResource); String version = ResourceMetadataKeyEnum.VERSION.get(nextResource);
String resourceName = myContext.getResourceDefinition(nextResource).getName(); String resourceName = myContext.getResourceDefinition(nextResource).getName();
@ -2030,9 +2036,8 @@ class ParserState<T> {
private PreResourceState getRootPreResourceState() { private PreResourceState getRootPreResourceState() {
if (getPreResourceState() != null) { if (getPreResourceState() != null) {
return getPreResourceState(); return getPreResourceState();
} else {
return this;
} }
return this;
} }
@Override @Override
@ -2590,8 +2595,7 @@ class ParserState<T> {
public void attributeValue(String theName, String theValue) throws DataFormatException { public void attributeValue(String theName, String theValue) throws DataFormatException {
if (myJsonMode) { if (myJsonMode) {
myDt.setValueAsString(theValue); myDt.setValueAsString(theValue);
return; } else {
} else {
// IGNORE - don't handle this as an error, we process these as XML events // IGNORE - don't handle this as an error, we process these as XML events
} }
} }

View File

@ -45,17 +45,14 @@ import javax.xml.stream.events.Namespace;
import javax.xml.stream.events.StartElement; import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent; import javax.xml.stream.events.XMLEvent;
import ca.uhn.fhir.model.api.BaseBundle;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.hl7.fhir.instance.model.api.IAnyResource; import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBase; import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.instance.model.api.IBaseBinary; import org.hl7.fhir.instance.model.api.IBaseBinary;
import org.hl7.fhir.instance.model.api.IBaseDatatype; import org.hl7.fhir.instance.model.api.IBaseDatatype;
import org.hl7.fhir.instance.model.api.IBaseElement;
import org.hl7.fhir.instance.model.api.IBaseExtension; import org.hl7.fhir.instance.model.api.IBaseExtension;
import org.hl7.fhir.instance.model.api.IBaseHasExtensions; import org.hl7.fhir.instance.model.api.IBaseHasExtensions;
import org.hl7.fhir.instance.model.api.IBaseHasModifierExtensions; import org.hl7.fhir.instance.model.api.IBaseHasModifierExtensions;
import org.hl7.fhir.instance.model.api.IBaseReference;
import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IBaseXhtml; import org.hl7.fhir.instance.model.api.IBaseXhtml;
import org.hl7.fhir.instance.model.api.IDomainResource; import org.hl7.fhir.instance.model.api.IDomainResource;
@ -65,17 +62,16 @@ import org.hl7.fhir.instance.model.api.IPrimitiveType;
import ca.uhn.fhir.context.BaseRuntimeChildDefinition; import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.context.BaseRuntimeDeclaredChildDefinition; import ca.uhn.fhir.context.BaseRuntimeDeclaredChildDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementDefinition; import ca.uhn.fhir.context.BaseRuntimeElementDefinition;
import ca.uhn.fhir.context.ConfigurationException; import ca.uhn.fhir.context.ConfigurationException;
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.context.RuntimeChildContainedResources; import ca.uhn.fhir.context.RuntimeChildContainedResources;
import ca.uhn.fhir.context.RuntimeChildDeclaredExtensionDefinition;
import ca.uhn.fhir.context.RuntimeChildExtension; import ca.uhn.fhir.context.RuntimeChildExtension;
import ca.uhn.fhir.context.RuntimeChildNarrativeDefinition; import ca.uhn.fhir.context.RuntimeChildNarrativeDefinition;
import ca.uhn.fhir.context.RuntimeChildUndeclaredExtensionDefinition; import ca.uhn.fhir.context.RuntimeChildUndeclaredExtensionDefinition;
import ca.uhn.fhir.context.RuntimeResourceDefinition; import ca.uhn.fhir.context.RuntimeResourceDefinition;
import ca.uhn.fhir.model.api.BaseBundle;
import ca.uhn.fhir.model.api.Bundle; import ca.uhn.fhir.model.api.Bundle;
import ca.uhn.fhir.model.api.BundleEntry; import ca.uhn.fhir.model.api.BundleEntry;
import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.api.IResource;
@ -101,7 +97,7 @@ import ca.uhn.fhir.util.XmlUtil;
* This class is the FHIR XML parser/encoder. Users should not interact with this class directly, but should use * This class is the FHIR XML parser/encoder. Users should not interact with this class directly, but should use
* {@link FhirContext#newXmlParser()} to get an instance. * {@link FhirContext#newXmlParser()} to get an instance.
*/ */
public class XmlParser extends BaseParser implements IParser { public class XmlParser extends BaseParser /*implements IParser */{
static final String ATOM_NS = "http://www.w3.org/2005/Atom"; static final String ATOM_NS = "http://www.w3.org/2005/Atom";
static final String FHIR_NS = "http://hl7.org/fhir"; static final String FHIR_NS = "http://hl7.org/fhir";
@ -149,10 +145,9 @@ public class XmlParser extends BaseParser implements IParser {
if (myPrettyPrint) { if (myPrettyPrint) {
PrettyPrintWriterWrapper retVal = new PrettyPrintWriterWrapper(eventWriter); PrettyPrintWriterWrapper retVal = new PrettyPrintWriterWrapper(eventWriter);
return retVal; return retVal;
} else {
NonPrettyPrintWriterWrapper retVal = new NonPrettyPrintWriterWrapper(eventWriter);
return retVal;
} }
NonPrettyPrintWriterWrapper retVal = new NonPrettyPrintWriterWrapper(eventWriter);
return retVal;
} }
@Override @Override
@ -330,6 +325,7 @@ public class XmlParser extends BaseParser implements IParser {
eventWriter.writeNamespace("at", TOMBSTONES_NS); eventWriter.writeNamespace("at", TOMBSTONES_NS);
if (nextEntry.getDeletedResourceId().isEmpty()) { if (nextEntry.getDeletedResourceId().isEmpty()) {
//TODO: Use of a deprecated method should be resolved.
writeOptionalAttribute(eventWriter, "ref", nextEntry.getId().getValueAsString()); writeOptionalAttribute(eventWriter, "ref", nextEntry.getId().getValueAsString());
} else { } else {
writeOptionalAttribute(eventWriter, "ref", nextEntry.getDeletedResourceId().getValueAsString()); writeOptionalAttribute(eventWriter, "ref", nextEntry.getDeletedResourceId().getValueAsString());
@ -361,12 +357,15 @@ public class XmlParser extends BaseParser implements IParser {
writeOptionalTagWithTextNode(eventWriter, "title", nextEntry.getTitle()); writeOptionalTagWithTextNode(eventWriter, "title", nextEntry.getTitle());
if (!deleted) { if (!deleted) {
//TODO: Use of a deprecated method should be resolved.
if (nextEntry.getId().isEmpty() == false) { if (nextEntry.getId().isEmpty() == false) {
//TODO: Use of a deprecated method should be resolved.
writeTagWithTextNode(eventWriter, "id", nextEntry.getId()); writeTagWithTextNode(eventWriter, "id", nextEntry.getId());
} else { } else {
writeTagWithTextNode(eventWriter, "id", nextEntry.getResource().getId()); writeTagWithTextNode(eventWriter, "id", nextEntry.getResource().getId());
} }
} }
//TODO: Use of a deprecated method should be resolved.
writeOptionalTagWithTextNode(eventWriter, "updated", nextEntry.getUpdated()); writeOptionalTagWithTextNode(eventWriter, "updated", nextEntry.getUpdated());
writeOptionalTagWithTextNode(eventWriter, "published", nextEntry.getPublished()); writeOptionalTagWithTextNode(eventWriter, "published", nextEntry.getPublished());
@ -420,6 +419,7 @@ public class XmlParser extends BaseParser implements IParser {
IdDt bundleId = theBundle.getId(); IdDt bundleId = theBundle.getId();
if (bundleId != null && isNotBlank(bundleId.getVersionIdPart()) || (updated != null && !updated.isEmpty())) { if (bundleId != null && isNotBlank(bundleId.getVersionIdPart()) || (updated != null && !updated.isEmpty())) {
theEventWriter.writeStartElement("meta"); theEventWriter.writeStartElement("meta");
//FIXME potential null acces bundleId may be null at this time due to the OR clause
writeOptionalTagWithValue(theEventWriter, "versionId", bundleId.getVersionIdPart()); writeOptionalTagWithValue(theEventWriter, "versionId", bundleId.getVersionIdPart());
if (updated != null) { if (updated != null) {
writeOptionalTagWithValue(theEventWriter, "lastUpdated", updated.getValueAsString()); writeOptionalTagWithValue(theEventWriter, "lastUpdated", updated.getValueAsString());
@ -476,8 +476,11 @@ public class XmlParser extends BaseParser implements IParser {
if (deleted) { if (deleted) {
theEventWriter.writeStartElement("deleted"); theEventWriter.writeStartElement("deleted");
//TODO: Use of a deprecated method should be resolved.
writeOptionalTagWithValue(theEventWriter, "type", nextEntry.getId().getResourceType()); writeOptionalTagWithValue(theEventWriter, "type", nextEntry.getId().getResourceType());
//TODO: Use of a deprecated method should be resolved.
writeOptionalTagWithValue(theEventWriter, "id", nextEntry.getId().getIdPart()); writeOptionalTagWithValue(theEventWriter, "id", nextEntry.getId().getIdPart());
//TODO: Use of a deprecated method should be resolved.
writeOptionalTagWithValue(theEventWriter, "versionId", nextEntry.getId().getVersionIdPart()); writeOptionalTagWithValue(theEventWriter, "versionId", nextEntry.getId().getVersionIdPart());
writeOptionalTagWithValue(theEventWriter, "instant", nextEntry.getDeletedAt().getValueAsString()); writeOptionalTagWithValue(theEventWriter, "instant", nextEntry.getDeletedAt().getValueAsString());
theEventWriter.writeEndElement(); theEventWriter.writeEndElement();
@ -504,18 +507,16 @@ public class XmlParser extends BaseParser implements IParser {
switch (childDef.getChildType()) { switch (childDef.getChildType()) {
case ID_DATATYPE: { case ID_DATATYPE: {
IIdType value = (IIdType) theElement; IIdType value = IIdType.class.cast(theElement);
String encodedValue = "id".equals(childName) ? value.getIdPart() : value.getValue(); String encodedValue = "id".equals(childName) ? value.getIdPart() : value.getValue();
if (value != null) { theEventWriter.writeStartElement(childName);
theEventWriter.writeStartElement(childName); theEventWriter.writeAttribute("value", encodedValue);
theEventWriter.writeAttribute("value", encodedValue); encodeExtensionsIfPresent(theResource, theEventWriter, theElement, theIncludedResource);
encodeExtensionsIfPresent(theResource, theEventWriter, theElement, theIncludedResource); theEventWriter.writeEndElement();
theEventWriter.writeEndElement();
}
break; break;
} }
case PRIMITIVE_DATATYPE: { case PRIMITIVE_DATATYPE: {
IPrimitiveType<?> pd = (IPrimitiveType<?>) theElement; IPrimitiveType<?> pd = IPrimitiveType.class.cast(theElement);
String value = pd.getValueAsString(); String value = pd.getValueAsString();
if (value != null || super.hasExtensions(pd)) { if (value != null || super.hasExtensions(pd)) {
theEventWriter.writeStartElement(childName); theEventWriter.writeStartElement(childName);
@ -568,23 +569,21 @@ public class XmlParser extends BaseParser implements IParser {
break; break;
} }
case PRIMITIVE_XHTML: { case PRIMITIVE_XHTML: {
XhtmlDt dt = (XhtmlDt) theElement; XhtmlDt dt = XhtmlDt.class.cast(theElement);
if (dt.hasContent()) { if (dt.hasContent()) {
encodeXhtml(dt, theEventWriter); encodeXhtml(dt, theEventWriter);
} }
break; break;
} }
case PRIMITIVE_XHTML_HL7ORG: { case PRIMITIVE_XHTML_HL7ORG: {
IBaseXhtml dt = (IBaseXhtml) theElement; IBaseXhtml dt = IBaseXhtml.class.cast(theElement);
if (dt.isEmpty()) { if (!dt.isEmpty()) {
break;
} else {
// TODO: this is probably not as efficient as it could be // TODO: this is probably not as efficient as it could be
XhtmlDt hdt = new XhtmlDt(); XhtmlDt hdt = new XhtmlDt();
hdt.setValueAsString(dt.getValueAsString()); hdt.setValueAsString(dt.getValueAsString());
encodeXhtml(hdt, theEventWriter); encodeXhtml(hdt, theEventWriter);
break;
} }
break;
} }
case EXTENSION_DECLARED: case EXTENSION_DECLARED:
case UNDECL_EXT: { case UNDECL_EXT: {
@ -621,6 +620,7 @@ public class XmlParser extends BaseParser implements IParser {
} else { } else {
narr = null; narr = null;
} }
//FIXME potential null access on narr see line 623
if (gen != null && narr.isEmpty()) { if (gen != null && narr.isEmpty()) {
gen.generateNarrative(myContext, theResource, narr); gen.generateNarrative(myContext, theResource, narr);
} }
@ -914,9 +914,8 @@ public class XmlParser extends BaseParser implements IParser {
childDef = myContext.getElementDefinition(value.getClass()); childDef = myContext.getElementDefinition(value.getClass());
if (childDef == null) { if (childDef == null) {
throw new ConfigurationException("Unable to encode extension, unrecognized child element type: " + value.getClass().getCanonicalName()); throw new ConfigurationException("Unable to encode extension, unrecognized child element type: " + value.getClass().getCanonicalName());
} else { }
childName = RuntimeChildUndeclaredExtensionDefinition.createExtensionChildName(childDef); childName = RuntimeChildUndeclaredExtensionDefinition.createExtensionChildName(childDef);
}
} else { } else {
childDef = extDef.getChildElementDefinitionByDatatype(value.getClass()); childDef = extDef.getChildElementDefinitionByDatatype(value.getClass());
if (childDef == null) { if (childDef == null) {

View File

@ -27,8 +27,6 @@ import java.lang.annotation.Target;
import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IBaseResource;
import ca.uhn.fhir.model.api.IResource;
/** /**
* RESTful method annotation to be used for the FHIR * RESTful method annotation to be used for the FHIR
* <a href="http://hl7.org/implement/standards/fhir/http.html#delete">delete</a> method. * <a href="http://hl7.org/implement/standards/fhir/http.html#delete">delete</a> method.

View File

@ -323,6 +323,7 @@ public abstract class BaseClient implements IRestfulClient {
} }
} catch (DataFormatException e) { } catch (DataFormatException e) {
//FIXME potential null access on httpResquest
String msg = getFhirContext().getLocalizer().getMessage(BaseClient.class, "failedToParseResponse", httpRequest.getHttpVerbName(), httpRequest.getUri(), e.toString()); String msg = getFhirContext().getLocalizer().getMessage(BaseClient.class, "failedToParseResponse", httpRequest.getHttpVerbName(), httpRequest.getUri(), e.toString());
throw new FhirClientConnectionException(msg, e); throw new FhirClientConnectionException(msg, e);
} catch (IllegalStateException e) { } catch (IllegalStateException e) {

View File

@ -87,6 +87,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
myContext = theContext; myContext = theContext;
} }
@Deprecated //override deprecated method
@Override @Override
public IBaseConformance conformance() { public IBaseConformance conformance() {
if (myContext.getVersion().getVersion().isRi()) { if (myContext.getVersion().getVersion().isRi()) {
@ -111,6 +112,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
return new CreateInternal(); return new CreateInternal();
} }
@Deprecated //overide deprecated method
@Override @Override
public MethodOutcome create(IBaseResource theResource) { public MethodOutcome create(IBaseResource theResource) {
BaseHttpClientInvocation invocation = MethodUtil.createCreateInvocation(theResource, myContext); BaseHttpClientInvocation invocation = MethodUtil.createCreateInvocation(theResource, myContext);
@ -133,6 +135,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
return new DeleteInternal(); return new DeleteInternal();
} }
@Deprecated //override deprecated method
@Override @Override
public MethodOutcome delete(final Class<? extends IBaseResource> theType, IdDt theId) { public MethodOutcome delete(final Class<? extends IBaseResource> theType, IdDt theId) {
HttpDeleteClientInvocation invocation = DeleteMethodBinding.createDeleteInvocation(getFhirContext(), theId.withResourceType(toResourceName(theType))); HttpDeleteClientInvocation invocation = DeleteMethodBinding.createDeleteInvocation(getFhirContext(), theId.withResourceType(toResourceName(theType)));
@ -146,6 +149,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
return resp; return resp;
} }
@Deprecated //override deprecated method
@Override @Override
public MethodOutcome delete(Class<? extends IBaseResource> theType, String theId) { public MethodOutcome delete(Class<? extends IBaseResource> theType, String theId) {
return delete(theType, new IdDt(theId)); return delete(theType, new IdDt(theId));
@ -186,12 +190,11 @@ public class GenericClient extends BaseClient implements IGenericClient {
if (theNotModifiedHandler == null) { if (theNotModifiedHandler == null) {
return invokeClient(myContext, binding, invocation, theEncoding, thePrettyPrint, myLogRequestAndResponse, theSummary, theSubsetElements); return invokeClient(myContext, binding, invocation, theEncoding, thePrettyPrint, myLogRequestAndResponse, theSummary, theSubsetElements);
} else { }
try { try {
return invokeClient(myContext, binding, invocation, theEncoding, thePrettyPrint, myLogRequestAndResponse, theSummary, theSubsetElements); return invokeClient(myContext, binding, invocation, theEncoding, thePrettyPrint, myLogRequestAndResponse, theSummary, theSubsetElements);
} catch (NotModifiedException e) { } catch (NotModifiedException e) {
return theNotModifiedHandler.call(); return theNotModifiedHandler.call();
}
} }
} }
@ -245,6 +248,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
return new HistoryInternal(); return new HistoryInternal();
} }
@Deprecated //override deprecated method
@Override @Override
public <T extends IBaseResource> Bundle history(final Class<T> theType, IdDt theIdDt, DateTimeDt theSince, Integer theLimit) { public <T extends IBaseResource> Bundle history(final Class<T> theType, IdDt theIdDt, DateTimeDt theSince, Integer theLimit) {
String resourceName = theType != null ? toResourceName(theType) : null; String resourceName = theType != null ? toResourceName(theType) : null;
@ -260,6 +264,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
} }
@Deprecated //override deprecated method
@Override @Override
public <T extends IBaseResource> Bundle history(Class<T> theType, String theId, DateTimeDt theSince, Integer theLimit) { public <T extends IBaseResource> Bundle history(Class<T> theType, String theId, DateTimeDt theSince, Integer theLimit) {
return history(theType, new IdDt(theId), theSince, theLimit); return history(theType, new IdDt(theId), theSince, theLimit);
@ -409,6 +414,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
myLastRequest = theLastRequest; myLastRequest = theLastRequest;
} }
@Deprecated //override deprecated method
@Override @Override
public void setLogRequestAndResponse(boolean theLogRequestAndResponse) { public void setLogRequestAndResponse(boolean theLogRequestAndResponse) {
myLogRequestAndResponse = theLogRequestAndResponse; myLogRequestAndResponse = theLogRequestAndResponse;
@ -423,6 +429,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
return new TransactionInternal(); return new TransactionInternal();
} }
@Deprecated //override deprecated method
@Override @Override
public List<IBaseResource> transaction(List<IBaseResource> theResources) { public List<IBaseResource> transaction(List<IBaseResource> theResources) {
BaseHttpClientInvocation invocation = TransactionMethodBinding.createTransactionInvocation(theResources, myContext); BaseHttpClientInvocation invocation = TransactionMethodBinding.createTransactionInvocation(theResources, myContext);
@ -569,6 +576,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
protected SummaryEnum mySummaryMode; protected SummaryEnum mySummaryMode;
@Deprecated //override deprecated method
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public T andLogRequestAndResponse(boolean theLogRequestAndResponse) { public T andLogRequestAndResponse(boolean theLogRequestAndResponse) {
@ -612,9 +620,8 @@ public class GenericClient extends BaseClient implements IGenericClient {
public List<Class<? extends IBaseResource>> getPreferResponseTypes(Class<? extends IBaseResource> theDefault) { public List<Class<? extends IBaseResource>> getPreferResponseTypes(Class<? extends IBaseResource> theDefault) {
if (myPreferResponseTypes != null) { if (myPreferResponseTypes != null) {
return myPreferResponseTypes; return myPreferResponseTypes;
} else {
return toTypeList(theDefault);
} }
return toTypeList(theDefault);
} }
protected HashSet<String> getSubsetElements() { protected HashSet<String> getSubsetElements() {
@ -1207,6 +1214,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
return nextOrPrevious(PREVIOUS, theBundle); return nextOrPrevious(PREVIOUS, theBundle);
} }
@Deprecated //override deprecated method
@Override @Override
public IGetPageTyped url(String thePageUrl) { public IGetPageTyped url(String thePageUrl) {
return new GetPageInternal(thePageUrl); return new GetPageInternal(thePageUrl);
@ -1446,29 +1454,27 @@ public class GenericClient extends BaseClient implements IGenericClient {
handler = new ResourceResponseHandler(myReturnResourceType); handler = new ResourceResponseHandler(myReturnResourceType);
Object retVal = invoke(null, handler, invocation); Object retVal = invoke(null, handler, invocation);
return retVal; return retVal;
} else {
ResourceResponseHandler handler;
handler = new ResourceResponseHandler();
handler.setPreferResponseTypes(getPreferResponseTypes(myType));
Object retVal = invoke(null, handler, invocation);
if (myContext.getResourceDefinition((IBaseResource) retVal).getName().equals("Parameters")) {
return retVal;
} else {
RuntimeResourceDefinition def = myContext.getResourceDefinition("Parameters");
IBaseResource parameters = def.newInstance();
BaseRuntimeChildDefinition paramChild = def.getChildByName("parameter");
BaseRuntimeElementCompositeDefinition<?> paramChildElem = (BaseRuntimeElementCompositeDefinition<?>) paramChild.getChildByName("parameter");
IBase parameter = paramChildElem.newInstance();
paramChild.getMutator().addValue(parameters, parameter);
BaseRuntimeChildDefinition resourceElem = paramChildElem.getChildByName("resource");
resourceElem.getMutator().addValue(parameter, (IBase) retVal);
return parameters;
}
} }
ResourceResponseHandler handler;
handler = new ResourceResponseHandler();
handler.setPreferResponseTypes(getPreferResponseTypes(myType));
Object retVal = invoke(null, handler, invocation);
if (myContext.getResourceDefinition((IBaseResource) retVal).getName().equals("Parameters")) {
return retVal;
}
RuntimeResourceDefinition def = myContext.getResourceDefinition("Parameters");
IBaseResource parameters = def.newInstance();
BaseRuntimeChildDefinition paramChild = def.getChildByName("parameter");
BaseRuntimeElementCompositeDefinition<?> paramChildElem = (BaseRuntimeElementCompositeDefinition<?>) paramChild.getChildByName("parameter");
IBase parameter = paramChildElem.newInstance();
paramChild.getMutator().addValue(parameters, parameter);
BaseRuntimeChildDefinition resourceElem = paramChildElem.getChildByName("resource");
resourceElem.getMutator().addValue(parameter, (IBase) retVal);
return parameters;
} }
@Override @Override
@ -1591,10 +1597,10 @@ public class GenericClient extends BaseClient implements IGenericClient {
private final class OutcomeResponseHandler implements IClientResponseHandler<MethodOutcome> { private final class OutcomeResponseHandler implements IClientResponseHandler<MethodOutcome> {
private PreferReturnEnum myPrefer; private PreferReturnEnum myPrefer;
private final String myResourceName; // private final String myResourceName;
private OutcomeResponseHandler(String theResourceName) { private OutcomeResponseHandler(String theResourceName) {
myResourceName = theResourceName; // myResourceName = theResourceName;
} }
private OutcomeResponseHandler(String theResourceName, PreferReturnEnum thePrefer) { private OutcomeResponseHandler(String theResourceName, PreferReturnEnum thePrefer) {
@ -1634,9 +1640,8 @@ public class GenericClient extends BaseClient implements IGenericClient {
public Object execute() {// AAA public Object execute() {// AAA
if (myId.hasVersionIdPart()) { if (myId.hasVersionIdPart()) {
return doReadOrVRead(myType.getImplementingClass(), myId, true, myNotModifiedHandler, myIfVersionMatches, myPrettyPrint, mySummaryMode, myParamEncoding, getSubsetElements()); return doReadOrVRead(myType.getImplementingClass(), myId, true, myNotModifiedHandler, myIfVersionMatches, myPrettyPrint, mySummaryMode, myParamEncoding, getSubsetElements());
} else {
return doReadOrVRead(myType.getImplementingClass(), myId, false, myNotModifiedHandler, myIfVersionMatches, myPrettyPrint, mySummaryMode, myParamEncoding, getSubsetElements());
} }
return doReadOrVRead(myType.getImplementingClass(), myId, false, myNotModifiedHandler, myIfVersionMatches, myPrettyPrint, mySummaryMode, myParamEncoding, getSubsetElements());
} }
@Override @Override
@ -1774,9 +1779,8 @@ public class GenericClient extends BaseClient implements IGenericClient {
IVersionSpecificBundleFactory bundleFactory = myContext.newBundleFactory(); IVersionSpecificBundleFactory bundleFactory = myContext.newBundleFactory();
bundleFactory.initializeWithBundleResource(response); bundleFactory.initializeWithBundleResource(response);
return bundleFactory.toListOfResources(); return bundleFactory.toListOfResources();
} else {
return new ArrayList<IBaseResource>(new BundleResponseHandler(myType).invokeClient(theResponseMimeType, theResponseReader, theResponseStatusCode, theHeaders).toListOfResources());
} }
return new ArrayList<IBaseResource>(new BundleResponseHandler(myType).invokeClient(theResponseMimeType, theResponseReader, theResponseStatusCode, theHeaders).toListOfResources());
} }
} }
@ -1850,6 +1854,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
return this; return this;
} }
@Deprecated //override deprecated method
@Override @Override
public IBase execute() { public IBase execute() {
@ -1906,8 +1911,11 @@ public class GenericClient extends BaseClient implements IGenericClient {
if (rootSs == null) { if (rootSs == null) {
rootSs = nextSortSpec; rootSs = nextSortSpec;
} else { } else {
//FIXME lastSs is null never set
//TODO unused assignment
lastSs.setChain(nextSortSpec); lastSs.setChain(nextSortSpec);
} }
//TODO unused assignment
lastSs = nextSortSpec; lastSs = nextSortSpec;
} }
if (rootSs != null) { if (rootSs != null) {
@ -1983,6 +1991,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
return this; return this;
} }
@Deprecated //override deprecated method
@Override @Override
public IQuery limitTo(int theLimitTo) { public IQuery limitTo(int theLimitTo) {
return count(theLimitTo); return count(theLimitTo);

View File

@ -318,12 +318,13 @@ public abstract class RestfulClientFactory implements IRestfulClientFactory {
String serverFhirVersionString = null; String serverFhirVersionString = null;
Object value = t.getSingleValueOrNull(conformance, "fhirVersion"); Object value = t.getSingleValueOrNull(conformance, "fhirVersion");
if (value instanceof IPrimitiveType) { if (value instanceof IPrimitiveType) {
serverFhirVersionString = ((IPrimitiveType<?>) value).getValueAsString(); serverFhirVersionString = IPrimitiveType.class.cast(value).getValueAsString();
} }
FhirVersionEnum serverFhirVersionEnum = null; FhirVersionEnum serverFhirVersionEnum = null;
if (StringUtils.isBlank(serverFhirVersionString)) { if (StringUtils.isBlank(serverFhirVersionString)) {
// we'll be lenient and accept this // we'll be lenient and accept this
} else { } else {
//FIXME null access on serverFhirVersionString
if (serverFhirVersionString.startsWith("0.80") || serverFhirVersionString.startsWith("0.0.8")) { if (serverFhirVersionString.startsWith("0.80") || serverFhirVersionString.startsWith("0.0.8")) {
serverFhirVersionEnum = FhirVersionEnum.DSTU1; serverFhirVersionEnum = FhirVersionEnum.DSTU1;
} else if (serverFhirVersionString.startsWith("0.4")) { } else if (serverFhirVersionString.startsWith("0.4")) {
@ -347,11 +348,13 @@ public abstract class RestfulClientFactory implements IRestfulClientFactory {
} }
@Deprecated //override deprecated method
@Override @Override
public ServerValidationModeEnum getServerValidationModeEnum() { public ServerValidationModeEnum getServerValidationModeEnum() {
return getServerValidationMode(); return getServerValidationMode();
} }
@Deprecated //override deprecated method
@Override @Override
public void setServerValidationModeEnum(ServerValidationModeEnum theServerValidationMode) { public void setServerValidationModeEnum(ServerValidationModeEnum theServerValidationMode) {
setServerValidationMode(theServerValidationMode); setServerValidationMode(theServerValidationMode);

View File

@ -30,7 +30,13 @@ import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair; import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient; import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*; import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpOptions;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.message.BasicNameValuePair; import org.apache.http.message.BasicNameValuePair;
import org.hl7.fhir.instance.model.api.IBaseBinary; import org.hl7.fhir.instance.model.api.IBaseBinary;
@ -47,7 +53,6 @@ import ca.uhn.fhir.rest.server.EncodingEnum;
import ca.uhn.fhir.rest.server.RestfulServerUtils; import ca.uhn.fhir.rest.server.RestfulServerUtils;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.util.CoverageIgnore; import ca.uhn.fhir.util.CoverageIgnore;
import ca.uhn.fhir.util.VersionUtil;
/** /**
* A Http Client based on Apache. This is an adapter around the class * A Http Client based on Apache. This is an adapter around the class

View File

@ -21,6 +21,7 @@ package ca.uhn.fhir.rest.client.apache;
*/ */
import java.io.IOException; import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
@ -92,7 +93,8 @@ public class ApacheHttpRequest implements IHttpRequest {
if (myRequest instanceof HttpEntityEnclosingRequest) { if (myRequest instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) myRequest).getEntity(); HttpEntity entity = ((HttpEntityEnclosingRequest) myRequest).getEntity();
if (entity.isRepeatable()) { if (entity.isRepeatable()) {
return IOUtils.toString(entity.getContent()); //TODO verify the charset
return IOUtils.toString(entity.getContent(), Charset.defaultCharset());
} }
} }
return null; return null;

View File

@ -61,6 +61,7 @@ public class ApacheHttpResponse implements IHttpResponse {
this.myResponse = theResponse; this.myResponse = theResponse;
} }
@Deprecated //override deprecated method
@Override @Override
public void bufferEntitity() throws IOException { public void bufferEntitity() throws IOException {
bufferEntity(); bufferEntity();
@ -77,6 +78,7 @@ public class ApacheHttpResponse implements IHttpResponse {
try { try {
this.myEntityBytes = IOUtils.toByteArray(respEntity); this.myEntityBytes = IOUtils.toByteArray(respEntity);
} catch (IllegalStateException e) { } catch (IllegalStateException e) {
//FIXME resouce leak
throw new InternalErrorException(e); throw new InternalErrorException(e);
} }
} }

View File

@ -73,12 +73,14 @@ public class ApacheRestfulClientFactory extends RestfulClientFactory {
public synchronized HttpClient getNativeHttpClient() { public synchronized HttpClient getNativeHttpClient() {
if (myHttpClient == null) { if (myHttpClient == null) {
//FIXME potential resoource leak
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000,
TimeUnit.MILLISECONDS); TimeUnit.MILLISECONDS);
connectionManager.setMaxTotal(getPoolMaxTotal()); connectionManager.setMaxTotal(getPoolMaxTotal());
connectionManager.setDefaultMaxPerRoute(getPoolMaxPerRoute()); connectionManager.setDefaultMaxPerRoute(getPoolMaxPerRoute());
// @formatter:off // @formatter:off
//TODO: Use of a deprecated method should be resolved.
RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(getSocketTimeout()) RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(getSocketTimeout())
.setConnectTimeout(getConnectTimeout()).setConnectionRequestTimeout(getConnectionRequestTimeout()) .setConnectTimeout(getConnectTimeout()).setConnectionRequestTimeout(getConnectionRequestTimeout())
.setStaleConnectionCheckEnabled(true).setProxy(myProxy).build(); .setStaleConnectionCheckEnabled(true).setProxy(myProxy).build();

View File

@ -120,6 +120,7 @@ public class LoggingInterceptor implements IClientInterceptor {
} }
if (myLogResponseBody) { if (myLogResponseBody) {
//TODO: Use of a deprecated method should be resolved.
theResponse.bufferEntitity(); theResponse.bufferEntitity();
InputStream respEntity = null; InputStream respEntity = null;
try { try {

View File

@ -27,7 +27,6 @@ import java.util.Date;
import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.TemporalPrecisionEnum; import ca.uhn.fhir.model.api.TemporalPrecisionEnum;
import ca.uhn.fhir.model.primitive.DateTimeDt; import ca.uhn.fhir.model.primitive.DateTimeDt;
import ca.uhn.fhir.rest.gclient.DateClientParam.IDateSpecifier;
import ca.uhn.fhir.rest.param.ParamPrefixEnum; import ca.uhn.fhir.rest.param.ParamPrefixEnum;
/** /**

View File

@ -3,7 +3,6 @@ package ca.uhn.fhir.rest.gclient;
import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isBlank;
import java.util.Collection; import java.util.Collection;
import java.util.List;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;

View File

@ -21,7 +21,6 @@ package ca.uhn.fhir.rest.method;
*/ */
import java.lang.reflect.Constructor; import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.List; import java.util.List;
import ca.uhn.fhir.context.ConfigurationException; import ca.uhn.fhir.context.ConfigurationException;

View File

@ -200,12 +200,11 @@ abstract class BaseHttpClientInvocationWithContents extends BaseHttpClientInvoca
if (myParams != null) { if (myParams != null) {
return httpClient.createParamRequest(getContext(), myParams, encoding); return httpClient.createParamRequest(getContext(), myParams, encoding);
} else {
encoding = ObjectUtils.defaultIfNull(encoding, EncodingEnum.XML);
String contents = encodeContents(thePrettyPrint, encoding);
String contentType = getContentType(encoding);
return httpClient.createByteRequest(getContext(), contents, contentType, encoding);
} }
encoding = ObjectUtils.defaultIfNull(encoding, EncodingEnum.XML);
String contents = encodeContents(thePrettyPrint, encoding);
String contentType = getContentType(encoding);
return httpClient.createByteRequest(getContext(), contents, contentType, encoding);
} }
private String getContentType(EncodingEnum encoding) { private String getContentType(EncodingEnum encoding) {
@ -253,10 +252,9 @@ abstract class BaseHttpClientInvocationWithContents extends BaseHttpClientInvoca
Bundle bundle = bundleFactory.getDstu1Bundle(); Bundle bundle = bundleFactory.getDstu1Bundle();
if (bundle != null) { if (bundle != null) {
return parser.encodeBundleToString(bundle); return parser.encodeBundleToString(bundle);
} else {
IBaseResource bundleRes = bundleFactory.getResourceBundle();
return parser.encodeResourceToString(bundleRes);
} }
IBaseResource bundleRes = bundleFactory.getResourceBundle();
return parser.encodeResourceToString(bundleRes);
} else if (myContents != null) { } else if (myContents != null) {
return myContents; return myContents;
} else { } else {

View File

@ -259,9 +259,8 @@ public abstract class BaseMethodBinding<T> implements IClientResponseHandler<T>
} catch (InvocationTargetException e) { } catch (InvocationTargetException e) {
if (e.getCause() instanceof BaseServerResponseException) { if (e.getCause() instanceof BaseServerResponseException) {
throw (BaseServerResponseException) e.getCause(); throw (BaseServerResponseException) e.getCause();
} else {
throw new InternalErrorException("Failed to call access method", e);
} }
throw new InternalErrorException("Failed to call access method", e);
} catch (Exception e) { } catch (Exception e) {
throw new InternalErrorException("Failed to call access method", e); throw new InternalErrorException("Failed to call access method", e);
} }
@ -455,6 +454,7 @@ public abstract class BaseMethodBinding<T> implements IClientResponseHandler<T>
if (returnTypeFromRp != null) { if (returnTypeFromRp != null) {
if (returnTypeFromAnnotation != null && !isResourceInterface(returnTypeFromAnnotation)) { if (returnTypeFromAnnotation != null && !isResourceInterface(returnTypeFromAnnotation)) {
if (!returnTypeFromRp.isAssignableFrom(returnTypeFromAnnotation)) { if (!returnTypeFromRp.isAssignableFrom(returnTypeFromAnnotation)) {
//FIXME potential null access on retunrTypeFromMethod
throw new ConfigurationException("Method '" + theMethod.getName() + "' in type " + theMethod.getDeclaringClass().getCanonicalName() + " returns type " throw new ConfigurationException("Method '" + theMethod.getName() + "' in type " + theMethod.getDeclaringClass().getCanonicalName() + " returns type "
+ returnTypeFromMethod.getCanonicalName() + " - Must return " + returnTypeFromRp.getCanonicalName() + " (or a subclass of it) per IResourceProvider contract"); + returnTypeFromMethod.getCanonicalName() + " - Must return " + returnTypeFromRp.getCanonicalName() + " (or a subclass of it) per IResourceProvider contract");
} }
@ -492,9 +492,8 @@ public abstract class BaseMethodBinding<T> implements IClientResponseHandler<T>
if (search.dynamic()) { if (search.dynamic()) {
IDynamicSearchResourceProvider provider = (IDynamicSearchResourceProvider) theProvider; IDynamicSearchResourceProvider provider = (IDynamicSearchResourceProvider) theProvider;
return new DynamicSearchMethodBinding(returnType, theMethod, theContext, provider); return new DynamicSearchMethodBinding(returnType, theMethod, theContext, provider);
} else {
return new SearchMethodBinding(returnType, theMethod, theContext, theProvider);
} }
return new SearchMethodBinding(returnType, theMethod, theContext, theProvider);
} else if (conformance != null) { } else if (conformance != null) {
return new ConformanceMethodBinding(theMethod, theContext, theProvider); return new ConformanceMethodBinding(theMethod, theContext, theProvider);
} else if (create != null) { } else if (create != null) {
@ -510,9 +509,8 @@ public abstract class BaseMethodBinding<T> implements IClientResponseHandler<T>
} else if (validate != null) { } else if (validate != null) {
if (theContext.getVersion().getVersion() == FhirVersionEnum.DSTU1) { if (theContext.getVersion().getVersion() == FhirVersionEnum.DSTU1) {
return new ValidateMethodBindingDstu1(theMethod, theContext, theProvider); return new ValidateMethodBindingDstu1(theMethod, theContext, theProvider);
} else {
return new ValidateMethodBindingDstu2Plus(returnType, returnTypeFromRp, theMethod, theContext, theProvider, validate);
} }
return new ValidateMethodBindingDstu2Plus(returnType, returnTypeFromRp, theMethod, theContext, theProvider, validate);
} else if (getTags != null) { } else if (getTags != null) {
return new GetTagsMethodBinding(theMethod, theContext, theProvider, getTags); return new GetTagsMethodBinding(theMethod, theContext, theProvider, getTags);
} else if (addTags != null) { } else if (addTags != null) {

View File

@ -101,16 +101,14 @@ abstract class BaseOutcomeReturningMethodBinding extends BaseMethodBinding<Metho
} }
if (response.getCreated() == null || Boolean.TRUE.equals(response.getCreated())) { if (response.getCreated() == null || Boolean.TRUE.equals(response.getCreated())) {
return Constants.STATUS_HTTP_201_CREATED; return Constants.STATUS_HTTP_201_CREATED;
} else {
return Constants.STATUS_HTTP_200_OK;
} }
return Constants.STATUS_HTTP_200_OK;
case UPDATE: case UPDATE:
if (response == null || response.getCreated() == null || Boolean.FALSE.equals(response.getCreated())) { if (response == null || response.getCreated() == null || Boolean.FALSE.equals(response.getCreated())) {
return Constants.STATUS_HTTP_200_OK; return Constants.STATUS_HTTP_200_OK;
} else {
return Constants.STATUS_HTTP_201_CREATED;
} }
return Constants.STATUS_HTTP_201_CREATED;
case VALIDATE: case VALIDATE:
case DELETE: case DELETE:
@ -120,13 +118,11 @@ abstract class BaseOutcomeReturningMethodBinding extends BaseMethodBinding<Metho
throw new InternalErrorException("Method " + getMethod().getName() + " in type " + getMethod().getDeclaringClass().getCanonicalName() + " returned null"); throw new InternalErrorException("Method " + getMethod().getName() + " in type " + getMethod().getDeclaringClass().getCanonicalName() + " returned null");
} }
return Constants.STATUS_HTTP_204_NO_CONTENT; return Constants.STATUS_HTTP_204_NO_CONTENT;
} else {
if (response.getOperationOutcome() == null) {
return Constants.STATUS_HTTP_204_NO_CONTENT;
} else {
return Constants.STATUS_HTTP_200_OK;
}
} }
if (response.getOperationOutcome() == null) {
return Constants.STATUS_HTTP_204_NO_CONTENT;
}
return Constants.STATUS_HTTP_200_OK;
} }
} }
@ -168,9 +164,8 @@ abstract class BaseOutcomeReturningMethodBinding extends BaseMethodBinding<Metho
} }
MethodOutcome retVal = MethodUtil.process2xxResponse(getContext(), theResponseStatusCode, theResponseMimeType, theResponseReader, theHeaders); MethodOutcome retVal = MethodUtil.process2xxResponse(getContext(), theResponseStatusCode, theResponseMimeType, theResponseReader, theHeaders);
return retVal; return retVal;
} else {
throw processNon2xxResponseAndReturnExceptionToThrow(theResponseStatusCode, theResponseMimeType, theResponseReader);
} }
throw processNon2xxResponseAndReturnExceptionToThrow(theResponseStatusCode, theResponseMimeType, theResponseReader);
} }
@Override @Override

View File

@ -27,9 +27,9 @@ import org.hl7.fhir.instance.model.api.IBaseResource;
import ca.uhn.fhir.context.ConfigurationException; import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.RuntimeResourceDefinition; import ca.uhn.fhir.context.RuntimeResourceDefinition;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.rest.annotation.Delete; import ca.uhn.fhir.rest.annotation.Delete;
import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.IdParam;
//TODO Use of a deprecated method should be resolved
import ca.uhn.fhir.rest.annotation.VersionIdParam; import ca.uhn.fhir.rest.annotation.VersionIdParam;
import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.IResourceProvider;
@ -62,6 +62,7 @@ public abstract class BaseOutcomeReturningMethodBindingWithResourceIdButNoResour
Integer versionIdParameterIndex = MethodUtil.findVersionIdParameterIndex(theMethod); Integer versionIdParameterIndex = MethodUtil.findVersionIdParameterIndex(theMethod);
if (versionIdParameterIndex != null) { if (versionIdParameterIndex != null) {
//TODO Use of a deprecated method should be resolved
throw new ConfigurationException("Method '" + theMethod.getName() + "' on type '" + theMethod.getDeclaringClass().getCanonicalName() + "' has a parameter annotated with the @" + VersionIdParam.class.getSimpleName() + " annotation but delete methods may not have this annotation"); throw new ConfigurationException("Method '" + theMethod.getName() + "' on type '" + theMethod.getDeclaringClass().getCanonicalName() + "' has a parameter annotated with the @" + VersionIdParam.class.getSimpleName() + " annotation but delete methods may not have this annotation");
} }

View File

@ -152,9 +152,8 @@ abstract class BaseOutcomeReturningMethodBindingWithResourceParam extends BaseOu
/** /**
* Subclasses may override * Subclasses may override
*/ */
@SuppressWarnings("unused")
protected void validateResourceIdAndUrlIdForNonConditionalOperation(IBaseResource theResource, String theResourceId, String theUrlId, String theMatchUrl) { protected void validateResourceIdAndUrlIdForNonConditionalOperation(IBaseResource theResource, String theResourceId, String theUrlId, String theMatchUrl) {
// nothing by default return;
} }
} }

View File

@ -190,6 +190,7 @@ public abstract class BaseResourceReturningMethodBinding extends BaseMethodBindi
} }
return listOfResources; return listOfResources;
case RESOURCE: case RESOURCE:
//FIXME null access on dstu1bundle
List<IResource> list = dstu1bundle.toListOfResources(); List<IResource> list = dstu1bundle.toListOfResources();
if (list.size() == 0) { if (list.size() == 0) {
return null; return null;
@ -272,25 +273,24 @@ public abstract class BaseResourceReturningMethodBinding extends BaseMethodBindi
return theRequest.getResponse().streamResponseAsResource(responseObject.getResource(), prettyPrint, summaryMode, Constants.STATUS_HTTP_200_OK, null, theRequest.isRespondGzip(), return theRequest.getResponse().streamResponseAsResource(responseObject.getResource(), prettyPrint, summaryMode, Constants.STATUS_HTTP_200_OK, null, theRequest.isRespondGzip(),
isAddContentLocationHeader()); isAddContentLocationHeader());
} else { }
// Is this request coming from a browser // Is this request coming from a browser
String uaHeader = theRequest.getHeader("user-agent"); String uaHeader = theRequest.getHeader("user-agent");
boolean requestIsBrowser = false; boolean requestIsBrowser = false;
if (uaHeader != null && uaHeader.contains("Mozilla")) { if (uaHeader != null && uaHeader.contains("Mozilla")) {
requestIsBrowser = true; requestIsBrowser = true;
}
for (int i = theServer.getInterceptors().size() - 1; i >= 0; i--) {
IServerInterceptor next = theServer.getInterceptors().get(i);
boolean continueProcessing = next.outgoingResponse(theRequest, responseObject.getDstu1Bundle());
if (!continueProcessing) {
ourLog.debug("Interceptor {} returned false, not continuing processing");
return null;
}
}
return theRequest.getResponse().streamResponseAsBundle(responseObject.getDstu1Bundle(), summaryMode, theRequest.isRespondGzip(), requestIsBrowser);
} }
for (int i = theServer.getInterceptors().size() - 1; i >= 0; i--) {
IServerInterceptor next = theServer.getInterceptors().get(i);
boolean continueProcessing = next.outgoingResponse(theRequest, responseObject.getDstu1Bundle());
if (!continueProcessing) {
ourLog.debug("Interceptor {} returned false, not continuing processing");
return null;
}
}
return theRequest.getResponse().streamResponseAsBundle(responseObject.getDstu1Bundle(), summaryMode, theRequest.isRespondGzip(), requestIsBrowser);
} }
public ResourceOrDstu1Bundle doInvokeServer(IRestfulServer<?> theServer, RequestDetails theRequest) { public ResourceOrDstu1Bundle doInvokeServer(IRestfulServer<?> theServer, RequestDetails theRequest) {
@ -363,8 +363,6 @@ public abstract class BaseResourceReturningMethodBinding extends BaseMethodBindi
bundleFactory.addRootPropertiesToBundle(null, theRequest.getFhirServerBase(), linkSelf, count, getResponseBundleType(), lastUpdated); bundleFactory.addRootPropertiesToBundle(null, theRequest.getFhirServerBase(), linkSelf, count, getResponseBundleType(), lastUpdated);
responseObject = new ResourceOrDstu1Bundle(resource); responseObject = new ResourceOrDstu1Bundle(resource);
break;
} else { } else {
Set<Include> includes = getRequestIncludesFromParams(params); Set<Include> includes = getRequestIncludesFromParams(params);
@ -394,9 +392,8 @@ public abstract class BaseResourceReturningMethodBinding extends BaseMethodBindi
IBaseResource resBundle = bundleFactory.getResourceBundle(); IBaseResource resBundle = bundleFactory.getResourceBundle();
responseObject = new ResourceOrDstu1Bundle(resBundle); responseObject = new ResourceOrDstu1Bundle(resBundle);
} }
break;
} }
break;
} }
case RESOURCE: { case RESOURCE: {
IBundleProvider result = (IBundleProvider) resultObj; IBundleProvider result = (IBundleProvider) resultObj;

View File

@ -1,32 +1,10 @@
package ca.uhn.fhir.rest.method; package ca.uhn.fhir.rest.method;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2017 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 static org.apache.commons.lang3.StringUtils.isBlank;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.Validate;
import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IBaseResource;
@ -34,7 +12,6 @@ import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.rest.annotation.ConditionalUrlParam; import ca.uhn.fhir.rest.annotation.ConditionalUrlParam;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum; import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
import ca.uhn.fhir.rest.server.Constants;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;

View File

@ -93,9 +93,8 @@ public class ConformanceMethodBinding extends BaseResourceReturningMethodBinding
if ("metadata".equals(theRequest.getOperation())) { if ("metadata".equals(theRequest.getOperation())) {
if (theRequest.getRequestType() == RequestTypeEnum.GET) { if (theRequest.getRequestType() == RequestTypeEnum.GET) {
return true; return true;
} else {
throw new MethodNotAllowedException("/metadata request must use HTTP GET", RequestTypeEnum.GET);
} }
throw new MethodNotAllowedException("/metadata request must use HTTP GET", RequestTypeEnum.GET);
} }
return false; return false;

View File

@ -86,7 +86,7 @@ public class DynamicSearchMethodBinding extends BaseResourceReturningMethodBindi
} }
@Override @Override
public IBundleProvider invokeServer(IRestfulServer theServer, RequestDetails theRequest, Object[] theMethodParams) throws InvalidRequestException, InternalErrorException { public IBundleProvider invokeServer(IRestfulServer<?> theServer, RequestDetails theRequest, Object[] theMethodParams) throws InvalidRequestException, InternalErrorException {
if (myIdParamIndex != null) { if (myIdParamIndex != null) {
theMethodParams[myIdParamIndex] = theRequest.getId(); theMethodParams[myIdParamIndex] = theRequest.getId();
} }

View File

@ -113,9 +113,8 @@ public class ElementsParameter implements IParameter {
retVal.add("meta"); retVal.add("meta");
return retVal; return retVal;
} else {
return null;
} }
return null;
} }
@Override @Override

View File

@ -1,27 +1,5 @@
package ca.uhn.fhir.rest.method; package ca.uhn.fhir.rest.method;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2017 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 static org.apache.commons.lang3.StringUtils.defaultString;
import org.hl7.fhir.instance.model.api.IPrimitiveType; import org.hl7.fhir.instance.model.api.IPrimitiveType;
import ca.uhn.fhir.util.ReflectionUtil; import ca.uhn.fhir.util.ReflectionUtil;

View File

@ -156,12 +156,9 @@ public class GetTagsMethodBinding extends BaseMethodBinding<TagList> {
IParser parser = createAppropriateParserForParsingResponse(theResponseMimeType, theResponseReader, theResponseStatusCode, null); IParser parser = createAppropriateParserForParsingResponse(theResponseMimeType, theResponseReader, theResponseStatusCode, null);
TagList retVal = parser.parseTagList(theResponseReader); TagList retVal = parser.parseTagList(theResponseReader);
return retVal; return retVal;
} else {
throw processNon2xxResponseAndReturnExceptionToThrow(theResponseStatusCode, theResponseMimeType, theResponseReader);
} }
throw processNon2xxResponseAndReturnExceptionToThrow(theResponseStatusCode, theResponseMimeType, theResponseReader);
} }
@Override @Override
public Object invokeServer(IRestfulServer<?> theServer, RequestDetails theRequest) throws BaseServerResponseException, IOException { public Object invokeServer(IRestfulServer<?> theServer, RequestDetails theRequest) throws BaseServerResponseException, IOException {
Object[] params = createParametersForServerRequest(theRequest); Object[] params = createParametersForServerRequest(theRequest);

View File

@ -184,6 +184,7 @@ public class HistoryMethodBinding extends BaseResourceReturningMethodBinding {
throw new InternalErrorException("Server provided resource at index " + index + " with no ID set (using IResource#setId(IdDt))"); throw new InternalErrorException("Server provided resource at index " + index + " with no ID set (using IResource#setId(IdDt))");
} }
if (isBlank(nextResource.getIdElement().getVersionIdPart()) && nextResource instanceof IResource) { if (isBlank(nextResource.getIdElement().getVersionIdPart()) && nextResource instanceof IResource) {
//TODO: Use of a deprecated method should be resolved.
IdDt versionId = (IdDt) ResourceMetadataKeyEnum.VERSION_ID.get((IResource) nextResource); IdDt versionId = (IdDt) ResourceMetadataKeyEnum.VERSION_ID.get((IResource) nextResource);
if (versionId == null || versionId.isEmpty()) { if (versionId == null || versionId.isEmpty()) {
throw new InternalErrorException("Server provided resource at index " + index + " with no Version ID set (using IResource#setId(IdDt))"); throw new InternalErrorException("Server provided resource at index " + index + " with no Version ID set (using IResource#setId(IdDt))");

View File

@ -149,12 +149,11 @@ class IncludeParameter extends BaseQueryParameter {
if (myInstantiableCollectionType == null) { if (myInstantiableCollectionType == null) {
if (mySpecType == String.class) { if (mySpecType == String.class) {
return value; return value;
} else {
return new Include(value, recurse);
} }
} else { return new Include(value, recurse);
retValCollection.add(new Include(value, recurse));
} }
//FIXME null access
retValCollection.add(new Include(value, recurse));
} }
return retValCollection; return retValCollection;

View File

@ -482,9 +482,8 @@ public class MethodUtil {
OperationParameter.throwInvalidMode(theObject.toString()); OperationParameter.throwInvalidMode(theObject.toString());
} }
return retVal; return retVal;
} else {
return null;
} }
return null;
} }
@Override @Override
@ -671,6 +670,7 @@ public class MethodUtil {
break; break;
} }
//FIXME null access
return binder.parse(theContext, theUnqualifiedParamName, theParameters); return binder.parse(theContext, theUnqualifiedParamName, theParameters);
} }

View File

@ -281,10 +281,9 @@ public class OperationMethodBinding extends BaseResourceReturningMethodBinding {
if (!myIdempotent) { if (!myIdempotent) {
String message = getContext().getLocalizer().getMessage(OperationMethodBinding.class, "methodNotSupported", theRequest.getRequestType(), RequestTypeEnum.POST.name()); String message = getContext().getLocalizer().getMessage(OperationMethodBinding.class, "methodNotSupported", theRequest.getRequestType(), RequestTypeEnum.POST.name());
throw new MethodNotAllowedException(message, RequestTypeEnum.POST); throw new MethodNotAllowedException(message, RequestTypeEnum.POST);
} else {
String message = getContext().getLocalizer().getMessage(OperationMethodBinding.class, "methodNotSupported", theRequest.getRequestType(), RequestTypeEnum.GET.name(), RequestTypeEnum.POST.name());
throw new MethodNotAllowedException(message, RequestTypeEnum.GET, RequestTypeEnum.POST);
} }
String message = getContext().getLocalizer().getMessage(OperationMethodBinding.class, "methodNotSupported", theRequest.getRequestType(), RequestTypeEnum.GET.name(), RequestTypeEnum.POST.name());
throw new MethodNotAllowedException(message, RequestTypeEnum.GET, RequestTypeEnum.POST);
} }
if (myIdParamIndex != null) { if (myIdParamIndex != null) {
@ -341,34 +340,33 @@ public class OperationMethodBinding extends BaseResourceReturningMethodBinding {
if (!theUseHttpGet) { if (!theUseHttpGet) {
return new HttpPostClientInvocation(theContext, theInput, b.toString()); return new HttpPostClientInvocation(theContext, theInput, b.toString());
} else {
FhirTerser t = theContext.newTerser();
List<Object> parameters = t.getValues(theInput, "Parameters.parameter");
Map<String, List<String>> params = new LinkedHashMap<String, List<String>>();
for (Object nextParameter : parameters) {
IPrimitiveType<?> nextNameDt = (IPrimitiveType<?>) t.getSingleValueOrNull((IBase) nextParameter, "name");
if (nextNameDt == null || nextNameDt.isEmpty()) {
ourLog.warn("Ignoring input parameter with no value in Parameters.parameter.name in operation client invocation");
continue;
}
String nextName = nextNameDt.getValueAsString();
if (!params.containsKey(nextName)) {
params.put(nextName, new ArrayList<String>());
}
IBaseDatatype value = (IBaseDatatype) t.getSingleValueOrNull((IBase) nextParameter, "value[x]");
if (value == null) {
continue;
}
if (!(value instanceof IPrimitiveType)) {
throw new IllegalArgumentException("Can not invoke operation as HTTP GET when it has parameters with a composite (non priitive) datatype as the value. Found value: " + value.getClass().getName());
}
IPrimitiveType<?> primitive = (IPrimitiveType<?>) value;
params.get(nextName).add(primitive.getValueAsString());
}
return new HttpGetClientInvocation(theContext, params, b.toString());
} }
FhirTerser t = theContext.newTerser();
List<Object> parameters = t.getValues(theInput, "Parameters.parameter");
Map<String, List<String>> params = new LinkedHashMap<String, List<String>>();
for (Object nextParameter : parameters) {
IPrimitiveType<?> nextNameDt = (IPrimitiveType<?>) t.getSingleValueOrNull((IBase) nextParameter, "name");
if (nextNameDt == null || nextNameDt.isEmpty()) {
ourLog.warn("Ignoring input parameter with no value in Parameters.parameter.name in operation client invocation");
continue;
}
String nextName = nextNameDt.getValueAsString();
if (!params.containsKey(nextName)) {
params.put(nextName, new ArrayList<String>());
}
IBaseDatatype value = (IBaseDatatype) t.getSingleValueOrNull((IBase) nextParameter, "value[x]");
if (value == null) {
continue;
}
if (!(value instanceof IPrimitiveType)) {
throw new IllegalArgumentException("Can not invoke operation as HTTP GET when it has parameters with a composite (non priitive) datatype as the value. Found value: " + value.getClass().getName());
}
IPrimitiveType<?> primitive = (IPrimitiveType<?>) value;
params.get(nextName).add(primitive.getValueAsString());
}
return new HttpGetClientInvocation(theContext, params, b.toString());
} }
public static class ReturnType { public static class ReturnType {

View File

@ -136,9 +136,8 @@ public class OperationParameter implements IParameter {
public String getSearchParamType() { public String getSearchParamType() {
if (mySearchParameterBinding != null) { if (mySearchParameterBinding != null) {
return mySearchParameterBinding.getParamType().getCode(); return mySearchParameterBinding.getParamType().getCode();
} else {
return null;
} }
return null;
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@ -326,7 +325,7 @@ public class OperationParameter implements IParameter {
} else { } else {
for (String nextValue : paramValues) { for (String nextValue : paramValues) {
FhirContext ctx = theRequest.getServer().getFhirContext(); FhirContext ctx = theRequest.getServer().getFhirContext();
RuntimePrimitiveDatatypeDefinition def = (RuntimePrimitiveDatatypeDefinition) ctx.getElementDefinition((Class<? extends IBase>) myParameterType); RuntimePrimitiveDatatypeDefinition def = (RuntimePrimitiveDatatypeDefinition) ctx.getElementDefinition(myParameterType.asSubclass(IBase.class));
IPrimitiveType<?> instance = def.newInstance(); IPrimitiveType<?> instance = def.newInstance();
instance.setValueAsString(nextValue); instance.setValueAsString(nextValue);
matchingParamValues.add(instance); matchingParamValues.add(instance);

View File

@ -81,9 +81,8 @@ public class PageMethodBinding extends BaseResourceReturningMethodBinding {
IBase bundle = handlePagingRequest(theServer, theRequest, theRequest.getParameters().get(Constants.PARAM_PAGINGACTION)[0]); IBase bundle = handlePagingRequest(theServer, theRequest, theRequest.getParameters().get(Constants.PARAM_PAGINGACTION)[0]);
if (bundle instanceof Bundle) { if (bundle instanceof Bundle) {
return new ResourceOrDstu1Bundle((Bundle) bundle); return new ResourceOrDstu1Bundle((Bundle) bundle);
} else {
return new ResourceOrDstu1Bundle((IBaseResource) bundle);
} }
return new ResourceOrDstu1Bundle((IBaseResource) bundle);
} }
private IBase handlePagingRequest(IRestfulServer<?> theServer, RequestDetails theRequest, String thePagingAction) { private IBase handlePagingRequest(IRestfulServer<?> theServer, RequestDetails theRequest, String thePagingAction) {
@ -144,9 +143,8 @@ public class PageMethodBinding extends BaseResourceReturningMethodBinding {
Bundle bundle = bundleFactory.getDstu1Bundle(); Bundle bundle = bundleFactory.getDstu1Bundle();
if (bundle != null) { if (bundle != null) {
return bundle; return bundle;
} else {
return bundleFactory.getResourceBundle();
} }
return bundleFactory.getResourceBundle();
// if (bundle != null) { // if (bundle != null) {
// for (int i = getInterceptors().size() - 1; i >= 0; i--) { // for (int i = getInterceptors().size() - 1; i >= 0; i--) {
// IServerInterceptor next = getInterceptors().get(i); // IServerInterceptor next = getInterceptors().get(i);

View File

@ -23,8 +23,6 @@ package ca.uhn.fhir.rest.method;
import java.io.IOException; import java.io.IOException;
import java.io.Writer; import java.io.Writer;
import org.hl7.fhir.instance.model.api.IBaseResource;
import ca.uhn.fhir.model.api.TagList; import ca.uhn.fhir.model.api.TagList;
import ca.uhn.fhir.parser.IParser; import ca.uhn.fhir.parser.IParser;

View File

@ -34,7 +34,6 @@ import ca.uhn.fhir.rest.api.PatchTypeEnum;
import ca.uhn.fhir.rest.server.Constants; import ca.uhn.fhir.rest.server.Constants;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
class PatchTypeParameter implements IParameter { class PatchTypeParameter implements IParameter {
@Override @Override

View File

@ -120,9 +120,8 @@ public class QualifiedParamList extends ArrayList<String> {
char nextChar = theString.charAt(i); char nextChar = theString.charAt(i);
if (nextChar != '\\') { if (nextChar != '\\') {
break; break;
} else {
retVal++;
} }
retVal++;
} }
return retVal; return retVal;
} }

View File

@ -99,9 +99,8 @@ public class ReadMethodBinding extends BaseResourceReturningMethodBinding implem
public RestOperationTypeEnum getRestOperationType(RequestDetails theRequestDetails) { public RestOperationTypeEnum getRestOperationType(RequestDetails theRequestDetails) {
if (mySupportsVersion && theRequestDetails.getId().hasVersionIdPart()) { if (mySupportsVersion && theRequestDetails.getId().hasVersionIdPart()) {
return RestOperationTypeEnum.VREAD; return RestOperationTypeEnum.VREAD;
} else {
return RestOperationTypeEnum.READ;
} }
return RestOperationTypeEnum.READ;
} }
@Override @Override

View File

@ -30,11 +30,10 @@ import org.hl7.fhir.instance.model.api.IBaseResource;
import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
import ca.uhn.fhir.util.CoverageIgnore; import ca.uhn.fhir.util.CoverageIgnore;
class RequestOperationCallbackParameter implements IParameter { class RequestOperationCallbackParameter implements IParameter {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ServletRequestParameter.class); // private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ServletRequestParameter.class);
@CoverageIgnore @CoverageIgnore
@Override @Override

View File

@ -225,9 +225,8 @@ public class SearchMethodBinding extends BaseResourceReturningMethodBinding {
if (!myQueryName.equals(queryName)) { if (!myQueryName.equals(queryName)) {
ourLog.trace("Query name does not match {}", myQueryName); ourLog.trace("Query name does not match {}", myQueryName);
return false; return false;
} else {
methodParamsTemp.add(Constants.PARAM_QUERY);
} }
methodParamsTemp.add(Constants.PARAM_QUERY);
} else { } else {
ourLog.trace("Query name does not match {}", myQueryName); ourLog.trace("Query name does not match {}", myQueryName);
return false; return false;
@ -346,9 +345,8 @@ public class SearchMethodBinding extends BaseResourceReturningMethodBinding {
if (theId == null || !theId.hasIdPart()) { if (theId == null || !theId.hasIdPart()) {
String msg = theContext.getLocalizer().getMessage(SearchMethodBinding.class.getName() + ".idNullForCompartmentSearch"); String msg = theContext.getLocalizer().getMessage(SearchMethodBinding.class.getName() + ".idNullForCompartmentSearch");
throw new InvalidRequestException(msg); throw new InvalidRequestException(msg);
} else {
compartmentSearch = true;
} }
compartmentSearch = true;
} }
/* /*

View File

@ -283,8 +283,10 @@ public class SearchParameter extends BaseQueryParameter {
this.myRequired = required; this.myRequired = required;
} }
@SuppressWarnings({ "unchecked", "unused" }) @SuppressWarnings("unchecked")
public void setType(FhirContext theContext, final Class<?> type, Class<? extends Collection<?>> theInnerCollectionType, Class<? extends Collection<?>> theOuterCollectionType) { public void setType(FhirContext theContext, final Class<?> type, Class<? extends Collection<?>> theInnerCollectionType, Class<? extends Collection<?>> theOuterCollectionType) {
this.myType = type; this.myType = type;
if (IQueryParameterType.class.isAssignableFrom(type)) { if (IQueryParameterType.class.isAssignableFrom(type)) {
myParamBinder = new QueryParameterTypeBinder((Class<? extends IQueryParameterType>) type, myCompositeTypes); myParamBinder = new QueryParameterTypeBinder((Class<? extends IQueryParameterType>) type, myCompositeTypes);

View File

@ -1,55 +1,17 @@
package ca.uhn.fhir.rest.method; package ca.uhn.fhir.rest.method;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2017 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.Method;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set; import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.hl7.fhir.instance.model.api.IBaseResource;
import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.primitive.InstantDt;
import ca.uhn.fhir.parser.DataFormatException;
import ca.uhn.fhir.rest.annotation.Since;
import ca.uhn.fhir.rest.param.ParameterUtil;
import ca.uhn.fhir.rest.server.Constants;
import ca.uhn.fhir.rest.server.exceptions.InternalErrorException;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
class SinceOrAtParameter extends SearchParameter { class SinceOrAtParameter extends SearchParameter {
private Class<?> myType; // private Class<?> myType;
private String myParamName; // private String myParamName;
private Class<?> myAnnotationType; // private Class<?> myAnnotationType;
public SinceOrAtParameter(String theParamName, Class<?> theAnnotationType) { public SinceOrAtParameter(String theParamName, Class<?> theAnnotationType) {
super(theParamName, false); super(theParamName, false);
myParamName = theParamName; // myParamName = theParamName;
myAnnotationType = theAnnotationType; // myAnnotationType = theAnnotationType;
} }
@Override @Override

View File

@ -112,16 +112,15 @@ public class TransactionMethodBinding extends BaseResourceReturningMethodBinding
if (theArgs[myTransactionParamIndex] instanceof Bundle) { if (theArgs[myTransactionParamIndex] instanceof Bundle) {
Bundle bundle = (Bundle) theArgs[myTransactionParamIndex]; Bundle bundle = (Bundle) theArgs[myTransactionParamIndex];
return createTransactionInvocation(bundle, context); return createTransactionInvocation(bundle, context);
} else {
@SuppressWarnings("unchecked")
List<IBaseResource> resources = (List<IBaseResource>) theArgs[myTransactionParamIndex];
return createTransactionInvocation(resources, context);
} }
@SuppressWarnings("unchecked")
List<IBaseResource> resources = (List<IBaseResource>) theArgs[myTransactionParamIndex];
return createTransactionInvocation(resources, context);
} }
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public Object invokeServer(IRestfulServer theServer, RequestDetails theRequest, Object[] theMethodParams) throws InvalidRequestException, InternalErrorException { public Object invokeServer(IRestfulServer<?> theServer, RequestDetails theRequest, Object[] theMethodParams) throws InvalidRequestException, InternalErrorException {
/* /*
* The design of HAPI's transaction method for DSTU1 support assumed that a transaction was just an update on a * The design of HAPI's transaction method for DSTU1 support assumed that a transaction was just an update on a

View File

@ -30,7 +30,6 @@ import org.hl7.fhir.instance.model.api.IBaseResource;
import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.instance.model.api.IIdType;
import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.FhirVersionEnum;
import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.rest.annotation.Update; import ca.uhn.fhir.rest.annotation.Update;
@ -150,11 +149,10 @@ public class UpdateMethodBinding extends BaseOutcomeReturningMethodBindingWithRe
if (isBlank(theResourceId)) { if (isBlank(theResourceId)) {
String msg = getContext().getLocalizer().getMessage(BaseOutcomeReturningMethodBindingWithResourceParam.class, "noIdInBodyForUpdate"); String msg = getContext().getLocalizer().getMessage(BaseOutcomeReturningMethodBindingWithResourceParam.class, "noIdInBodyForUpdate");
throw new InvalidRequestException(msg); throw new InvalidRequestException(msg);
} else { }
if (!theResourceId.equals(theUrlId)) { if (!theResourceId.equals(theUrlId)) {
String msg = getContext().getLocalizer().getMessage(BaseOutcomeReturningMethodBindingWithResourceParam.class, "incorrectIdForUpdate", theResourceId, theUrlId); String msg = getContext().getLocalizer().getMessage(BaseOutcomeReturningMethodBindingWithResourceParam.class, "incorrectIdForUpdate", theResourceId, theUrlId);
throw new InvalidRequestException(msg); throw new InvalidRequestException(msg);
}
} }
} else { } else {
theResource.setId((IIdType)null); theResource.setId((IIdType)null);

View File

@ -151,9 +151,8 @@ public abstract class BaseQueryParameter implements IParameter {
if (handlesMissing()) { if (handlesMissing()) {
return parse(theRequest.getServer().getFhirContext(), paramList); return parse(theRequest.getServer().getFhirContext(), paramList);
} else {
return null;
} }
return null;
} }
return parse(theRequest.getServer().getFhirContext(), paramList); return parse(theRequest.getServer().getFhirContext(), paramList);

View File

@ -32,7 +32,6 @@ import org.hl7.fhir.instance.model.api.IPrimitiveType;
import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.IQueryParameterOr; import ca.uhn.fhir.model.api.IQueryParameterOr;
import ca.uhn.fhir.model.api.IQueryParameterType;
import ca.uhn.fhir.model.api.TemporalPrecisionEnum; import ca.uhn.fhir.model.api.TemporalPrecisionEnum;
import ca.uhn.fhir.model.dstu.valueset.QuantityCompararatorEnum; import ca.uhn.fhir.model.dstu.valueset.QuantityCompararatorEnum;
import ca.uhn.fhir.model.primitive.DateDt; import ca.uhn.fhir.model.primitive.DateDt;
@ -43,7 +42,7 @@ import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.util.ValidateUtil; import ca.uhn.fhir.util.ValidateUtil;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class DateParam extends BaseParamWithPrefix<DateParam> implements IQueryParameterType , IQueryParameterOr<DateParam> { public class DateParam extends BaseParamWithPrefix<DateParam> implements /*IQueryParameterType , */IQueryParameterOr<DateParam> {
private final DateTimeDt myValue = new DateTimeDt(); private final DateTimeDt myValue = new DateTimeDt();
@ -220,9 +219,8 @@ public class DateParam extends BaseParamWithPrefix<DateParam> implements IQueryP
public String getValueAsString() { public String getValueAsString() {
if (myValue != null) { if (myValue != null) {
return myValue.getValueAsString(); return myValue.getValueAsString();
} else {
return null;
} }
return null;
} }
/** /**

View File

@ -345,6 +345,7 @@ public class DateRangeParam implements IQueryParameterAnd<DateParam> {
public void setRangeFromDatesInclusive(String theLowerBound, String theUpperBound) { public void setRangeFromDatesInclusive(String theLowerBound, String theUpperBound) {
myLowerBound = theLowerBound != null ? new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, theLowerBound) : null; myLowerBound = theLowerBound != null ? new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, theLowerBound) : null;
myUpperBound = theUpperBound != null ? new DateParam(ParamPrefixEnum.LESSTHAN_OR_EQUALS, theUpperBound) : null; myUpperBound = theUpperBound != null ? new DateParam(ParamPrefixEnum.LESSTHAN_OR_EQUALS, theUpperBound) : null;
//FIXME potential null access on theLowerBound
if (isNotBlank(theLowerBound) && isNotBlank(theUpperBound) && theLowerBound.equals(theUpperBound)) { if (isNotBlank(theLowerBound) && isNotBlank(theUpperBound) && theLowerBound.equals(theUpperBound)) {
myLowerBound.setPrefix(ParamPrefixEnum.EQUAL); myLowerBound.setPrefix(ParamPrefixEnum.EQUAL);
myUpperBound.setPrefix(ParamPrefixEnum.EQUAL); myUpperBound.setPrefix(ParamPrefixEnum.EQUAL);

View File

@ -38,6 +38,8 @@ import ca.uhn.fhir.util.CoverageIgnore;
@CoverageIgnore @CoverageIgnore
public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype { public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype {
private static final long serialVersionUID = 993056016725918652L;
/** /**
* Constructor * Constructor
*/ */
@ -78,6 +80,7 @@ public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype
return super.isBaseEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(mySystem, myVersion, myCode, myDisplay, myPrimary); return super.isBaseEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty(mySystem, myVersion, myCode, myDisplay, myPrimary);
} }
@Deprecated //override deprecated method
@Override @Override
public <T extends IElement> List<T> getAllPopulatedChildElementsOfType(Class<T> theType) { public <T extends IElement> List<T> getAllPopulatedChildElementsOfType(Class<T> theType) {
return ca.uhn.fhir.util.ElementUtil.allPopulatedChildElements(theType, mySystem, myVersion, myCode, myDisplay, myPrimary); return ca.uhn.fhir.util.ElementUtil.allPopulatedChildElements(theType, mySystem, myVersion, myCode, myDisplay, myPrimary);
@ -90,6 +93,7 @@ public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype
* <b>Definition:</b> The identification of the code system that defines the meaning of the symbol in the code. * <b>Definition:</b> The identification of the code system that defines the meaning of the symbol in the code.
* </p> * </p>
*/ */
@Override
public UriDt getSystemElement() { public UriDt getSystemElement() {
if (mySystem == null) { if (mySystem == null) {
mySystem = new UriDt(); mySystem = new UriDt();
@ -116,6 +120,7 @@ public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype
* <b>Definition:</b> The identification of the code system that defines the meaning of the symbol in the code. * <b>Definition:</b> The identification of the code system that defines the meaning of the symbol in the code.
* </p> * </p>
*/ */
@Override
public InternalCodingDt setSystem(String theUri) { public InternalCodingDt setSystem(String theUri) {
mySystem = new UriDt(theUri); mySystem = new UriDt(theUri);
return this; return this;
@ -169,6 +174,7 @@ public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype
* <b>Definition:</b> A symbol in syntax defined by the system. The symbol may be a predefined code or an expression in a syntax defined by the coding system (e.g. post-coordination) * <b>Definition:</b> A symbol in syntax defined by the system. The symbol may be a predefined code or an expression in a syntax defined by the coding system (e.g. post-coordination)
* </p> * </p>
*/ */
@Override
public CodeDt getCodeElement() { public CodeDt getCodeElement() {
if (myCode == null) { if (myCode == null) {
myCode = new CodeDt(); myCode = new CodeDt();
@ -195,6 +201,7 @@ public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype
* <b>Definition:</b> A symbol in syntax defined by the system. The symbol may be a predefined code or an expression in a syntax defined by the coding system (e.g. post-coordination) * <b>Definition:</b> A symbol in syntax defined by the system. The symbol may be a predefined code or an expression in a syntax defined by the coding system (e.g. post-coordination)
* </p> * </p>
*/ */
@Override
public InternalCodingDt setCode(String theCode) { public InternalCodingDt setCode(String theCode) {
myCode = new CodeDt(theCode); myCode = new CodeDt(theCode);
return this; return this;
@ -233,6 +240,7 @@ public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype
* <b>Definition:</b> A representation of the meaning of the code in the system, following the rules of the system. * <b>Definition:</b> A representation of the meaning of the code in the system, following the rules of the system.
* </p> * </p>
*/ */
@Override
public InternalCodingDt setDisplay(String theString) { public InternalCodingDt setDisplay(String theString) {
myDisplay = new StringDt(theString); myDisplay = new StringDt(theString);
return this; return this;
@ -292,11 +300,13 @@ public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype
return getDisplay(); return getDisplay();
} }
@Deprecated //override deprecated method
@Override @Override
public Boolean getMissing() { public Boolean getMissing() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@Deprecated //override deprecated method
@Override @Override
public IQueryParameterType setMissing(Boolean theMissing) { public IQueryParameterType setMissing(Boolean theMissing) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();

View File

@ -147,9 +147,8 @@ public enum ParamPrefixEnum {
public String getValueForContext(FhirContext theContext) { public String getValueForContext(FhirContext theContext) {
if (theContext.getVersion().getVersion() == FhirVersionEnum.DSTU1) { if (theContext.getVersion().getVersion() == FhirVersionEnum.DSTU1) {
return getDstu1Value(); return getDstu1Value();
} else {
return getValue();
} }
return getValue();
} }
/** /**

View File

@ -139,9 +139,8 @@ public class ParameterUtil {
public static String escapeWithDefault(Object theValue) { public static String escapeWithDefault(Object theValue) {
if (theValue == null) { if (theValue == null) {
return ""; return "";
} else {
return escape(theValue.toString());
} }
return escape(theValue.toString());
} }
/** /**

View File

@ -29,11 +29,10 @@ import org.apache.commons.lang3.builder.ToStringStyle;
import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IBaseResource;
import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.IQueryParameterType;
import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.util.CoverageIgnore; import ca.uhn.fhir.util.CoverageIgnore;
public class ReferenceParam extends BaseParam implements IQueryParameterType { public class ReferenceParam extends BaseParam /*implements IQueryParameterType*/ {
private String myChain; private String myChain;
@ -93,9 +92,8 @@ public class ReferenceParam extends BaseParam implements IQueryParameterType {
String doGetValueAsQueryToken(FhirContext theContext) { String doGetValueAsQueryToken(FhirContext theContext) {
if (isBlank(myId.getResourceType())) { if (isBlank(myId.getResourceType())) {
return myId.getValue(); // e.g. urn:asdjd or 123 or cid:wieiuru or #1 return myId.getValue(); // e.g. urn:asdjd or 123 or cid:wieiuru or #1
} else {
return myId.getIdPart();
} }
return myId.getIdPart();
} }
@Override @Override

View File

@ -150,6 +150,7 @@ public class ResourceParameter implements IParameter {
String ctValue = theRequest.getHeader(Constants.HEADER_CONTENT_TYPE); String ctValue = theRequest.getHeader(Constants.HEADER_CONTENT_TYPE);
if (ctValue != null) { if (ctValue != null) {
if (ctValue.startsWith("application/x-www-form-urlencoded")) { if (ctValue.startsWith("application/x-www-form-urlencoded")) {
//FIXME potential null access theMethodBinding
String msg = theRequest.getServer().getFhirContext().getLocalizer().getMessage(ResourceParameter.class, "invalidContentTypeInRequest", ctValue, theMethodBinding.getRestOperationType()); String msg = theRequest.getServer().getFhirContext().getLocalizer().getMessage(ResourceParameter.class, "invalidContentTypeInRequest", ctValue, theMethodBinding.getRestOperationType());
throw new InvalidRequestException(msg); throw new InvalidRequestException(msg);
} }
@ -169,9 +170,8 @@ public class ResourceParameter implements IParameter {
if (encoding == null) { if (encoding == null) {
String msg = ctx.getLocalizer().getMessage(ResourceParameter.class, "noContentTypeInRequest", restOperationType); String msg = ctx.getLocalizer().getMessage(ResourceParameter.class, "noContentTypeInRequest", restOperationType);
throw new InvalidRequestException(msg); throw new InvalidRequestException(msg);
} else {
requestReader = new InputStreamReader(new ByteArrayInputStream(theRequest.loadRequestContents()), charset);
} }
requestReader = new InputStreamReader(new ByteArrayInputStream(theRequest.loadRequestContents()), charset);
} else { } else {
String msg = ctx.getLocalizer().getMessage(ResourceParameter.class, "invalidContentTypeInRequest", ctValue, restOperationType); String msg = ctx.getLocalizer().getMessage(ResourceParameter.class, "invalidContentTypeInRequest", ctValue, restOperationType);
throw new InvalidRequestException(msg); throw new InvalidRequestException(msg);

View File

@ -27,12 +27,11 @@ import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.commons.lang3.builder.ToStringStyle;
import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.IQueryParameterType;
import ca.uhn.fhir.model.base.composite.BaseCodingDt; import ca.uhn.fhir.model.base.composite.BaseCodingDt;
import ca.uhn.fhir.model.base.composite.BaseIdentifierDt; import ca.uhn.fhir.model.base.composite.BaseIdentifierDt;
import ca.uhn.fhir.model.primitive.UriDt; import ca.uhn.fhir.model.primitive.UriDt;
public class TokenParam extends BaseParam implements IQueryParameterType { public class TokenParam extends BaseParam /*implements IQueryParameterType*/ {
private TokenParamModifier myModifier; private TokenParamModifier myModifier;
private String mySystem; private String mySystem;
@ -86,9 +85,8 @@ public class TokenParam extends BaseParam implements IQueryParameterType {
String doGetQueryParameterQualifier() { String doGetQueryParameterQualifier() {
if (getModifier() != null) { if (getModifier() != null) {
return getModifier().getValue(); return getModifier().getValue();
} else {
return null;
} }
return null;
} }
/** /**
@ -98,9 +96,8 @@ public class TokenParam extends BaseParam implements IQueryParameterType {
String doGetValueAsQueryToken(FhirContext theContext) { String doGetValueAsQueryToken(FhirContext theContext) {
if (getSystem() != null) { if (getSystem() != null) {
return ParameterUtil.escape(StringUtils.defaultString(getSystem())) + '|' + ParameterUtil.escape(getValue()); return ParameterUtil.escape(StringUtils.defaultString(getSystem())) + '|' + ParameterUtil.escape(getValue());
} else {
return ParameterUtil.escape(getValue());
} }
return ParameterUtil.escape(getValue());
} }
/** /**

View File

@ -48,7 +48,7 @@ import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
public class TransactionParameter implements IParameter { public class TransactionParameter implements IParameter {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(TransactionParameter.class); // private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(TransactionParameter.class);
private FhirContext myContext; private FhirContext myContext;
private ParamStyle myParamStyle; private ParamStyle myParamStyle;
private Class<? extends IBaseResource> myResourceBundleType; private Class<? extends IBaseResource> myResourceBundleType;
@ -112,6 +112,7 @@ public class TransactionParameter implements IParameter {
case DSTU1_BUNDLE: { case DSTU1_BUNDLE: {
Bundle bundle; Bundle bundle;
bundle = parser.parseBundle(reader); bundle = parser.parseBundle(reader);
//FIXME resource leak
return bundle; return bundle;
} }
case RESOURCE_LIST: { case RESOURCE_LIST: {
@ -122,12 +123,15 @@ public class TransactionParameter implements IParameter {
resourceList.add(next.getResource()); resourceList.add(next.getResource());
} }
} }
//FIXME resource leak
return resourceList; return resourceList;
} }
case RESOURCE_BUNDLE: case RESOURCE_BUNDLE:
//FIXME resource leak
return parser.parseResource(myResourceBundleType, reader); return parser.parseResource(myResourceBundleType, reader);
} }
//FIXME resource leak
throw new IllegalStateException("Unknown type: " + myParamStyle); // should not happen throw new IllegalStateException("Unknown type: " + myParamStyle); // should not happen
} }

View File

@ -1,9 +1,6 @@
package ca.uhn.fhir.rest.server; package ca.uhn.fhir.rest.server;
import java.util.List;
import ca.uhn.fhir.rest.method.RequestDetails; import ca.uhn.fhir.rest.method.RequestDetails;
import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor;
/* /*
* #%L * #%L

View File

@ -55,9 +55,8 @@ public class ResourceBinding {
if (rm.incomingServerRequestMatchesMethod(theRequest)) { if (rm.incomingServerRequestMatchesMethod(theRequest)) {
ourLog.debug("Handler {} matches", rm); ourLog.debug("Handler {} matches", rm);
return rm; return rm;
} else {
ourLog.trace("Handler {} does not match", rm);
} }
ourLog.trace("Handler {} does not match", rm);
} }
return null; return null;
} }

View File

@ -266,9 +266,8 @@ public class RestfulServer extends HttpServlet implements IRestfulServer<Servlet
if (resourceMethod == null) { if (resourceMethod == null) {
if (isBlank(requestPath)) { if (isBlank(requestPath)) {
throw new InvalidRequestException(myFhirContext.getLocalizer().getMessage(RestfulServer.class, "rootRequest")); throw new InvalidRequestException(myFhirContext.getLocalizer().getMessage(RestfulServer.class, "rootRequest"));
} else { }
throw new InvalidRequestException(myFhirContext.getLocalizer().getMessage(RestfulServer.class, "unknownMethod", requestType.name(), requestPath, requestDetails.getParameters().keySet())); throw new InvalidRequestException(myFhirContext.getLocalizer().getMessage(RestfulServer.class, "unknownMethod", requestType.name(), requestPath, requestDetails.getParameters().keySet()));
}
} }
return resourceMethod; return resourceMethod;
} }
@ -324,45 +323,44 @@ public class RestfulServer extends HttpServlet implements IRestfulServer<Servlet
if (!Modifier.isPublic(m.getModifiers())) { if (!Modifier.isPublic(m.getModifiers())) {
throw new ConfigurationException("Method '" + m.getName() + "' is not public, FHIR RESTful methods must be public"); throw new ConfigurationException("Method '" + m.getName() + "' is not public, FHIR RESTful methods must be public");
}
if (Modifier.isStatic(m.getModifiers())) {
throw new ConfigurationException("Method '" + m.getName() + "' is static, FHIR RESTful methods must not be static");
}
ourLog.debug("Scanning public method: {}#{}", theProvider.getClass(), m.getName());
String resourceName = foundMethodBinding.getResourceName();
ResourceBinding resourceBinding;
if (resourceName == null) {
resourceBinding = myServerBinding;
} else { } else {
if (Modifier.isStatic(m.getModifiers())) { RuntimeResourceDefinition definition = getFhirContext().getResourceDefinition(resourceName);
throw new ConfigurationException("Method '" + m.getName() + "' is static, FHIR RESTful methods must not be static"); if (myResourceNameToBinding.containsKey(definition.getName())) {
resourceBinding = myResourceNameToBinding.get(definition.getName());
} else { } else {
ourLog.debug("Scanning public method: {}#{}", theProvider.getClass(), m.getName()); resourceBinding = new ResourceBinding();
resourceBinding.setResourceName(resourceName);
myResourceNameToBinding.put(resourceName, resourceBinding);
}
}
String resourceName = foundMethodBinding.getResourceName(); List<Class<?>> allowableParams = foundMethodBinding.getAllowableParamAnnotations();
ResourceBinding resourceBinding; if (allowableParams != null) {
if (resourceName == null) { for (Annotation[] nextParamAnnotations : m.getParameterAnnotations()) {
resourceBinding = myServerBinding; for (Annotation annotation : nextParamAnnotations) {
} else { Package pack = annotation.annotationType().getPackage();
RuntimeResourceDefinition definition = getFhirContext().getResourceDefinition(resourceName); if (pack.equals(IdParam.class.getPackage())) {
if (myResourceNameToBinding.containsKey(definition.getName())) { if (!allowableParams.contains(annotation.annotationType())) {
resourceBinding = myResourceNameToBinding.get(definition.getName()); throw new ConfigurationException("Method[" + m.toString() + "] is not allowed to have a parameter annotated with " + annotation);
} else {
resourceBinding = new ResourceBinding();
resourceBinding.setResourceName(resourceName);
myResourceNameToBinding.put(resourceName, resourceBinding);
}
}
List<Class<?>> allowableParams = foundMethodBinding.getAllowableParamAnnotations();
if (allowableParams != null) {
for (Annotation[] nextParamAnnotations : m.getParameterAnnotations()) {
for (Annotation annotation : nextParamAnnotations) {
Package pack = annotation.annotationType().getPackage();
if (pack.equals(IdParam.class.getPackage())) {
if (!allowableParams.contains(annotation.annotationType())) {
throw new ConfigurationException("Method[" + m.toString() + "] is not allowed to have a parameter annotated with " + annotation);
}
}
} }
} }
} }
resourceBinding.addMethod(foundMethodBinding);
ourLog.debug(" * Method: {}#{} is a handler", theProvider.getClass(), m.getName());
} }
} }
resourceBinding.addMethod(foundMethodBinding);
ourLog.debug(" * Method: {}#{} is a handler", theProvider.getClass(), m.getName());
} }
return count; return count;
@ -406,6 +404,7 @@ public class RestfulServer extends HttpServlet implements IRestfulServer<Servlet
@Override @Override
public FhirContext getFhirContext() { public FhirContext getFhirContext() {
if (myFhirContext == null) { if (myFhirContext == null) {
//TODO: Use of a deprecated method should be resolved.
myFhirContext = new FhirContext(); myFhirContext = new FhirContext();
} }
return myFhirContext; return myFhirContext;

View File

@ -425,9 +425,8 @@ public class RestfulServerUtils {
} }
if (encoding == null) { if (encoding == null) {
return null; return null;
} else {
return new ResponseEncoding(theFhirContext, encoding, theContentType);
} }
return new ResponseEncoding(theFhirContext, encoding, theContentType);
} }
public static IParser getNewParser(FhirContext theContext, RequestDetails theRequestDetails) { public static IParser getNewParser(FhirContext theContext, RequestDetails theRequestDetails) {
@ -577,6 +576,7 @@ public class RestfulServerUtils {
} catch (Exception e) { } catch (Exception e) {
// always send a response, even if the parsing went wrong // always send a response, even if the parsing went wrong
} }
//FIXME resource leak
return theRequestDetails.getResponse().sendWriterResponse(status, contentType, charset, writer); return theRequestDetails.getResponse().sendWriterResponse(status, contentType, charset, writer);
} }
@ -700,7 +700,7 @@ public class RestfulServerUtils {
IParser parser = getNewParser(theServer.getFhirContext(), theRequestDetails); IParser parser = getNewParser(theServer.getFhirContext(), theRequestDetails);
parser.encodeResourceToWriter(theResource, writer); parser.encodeResourceToWriter(theResource, writer);
} }
//FIXME resource leak
return restUtil.sendWriterResponse(theStausCode, contentType, charset, writer); return restUtil.sendWriterResponse(theStausCode, contentType, charset, writer);
} }
@ -780,9 +780,8 @@ public class RestfulServerUtils {
public String getResourceContentType() { public String getResourceContentType() {
if (Boolean.TRUE.equals(isNonLegacy())) { if (Boolean.TRUE.equals(isNonLegacy())) {
return getEncoding().getResourceContentTypeNonLegacy(); return getEncoding().getResourceContentTypeNonLegacy();
} else {
return getEncoding().getResourceContentType();
} }
return getEncoding().getResourceContentType();
} }
public Boolean isNonLegacy() { public Boolean isNonLegacy() {

View File

@ -3,7 +3,6 @@ package ca.uhn.fhir.rest.server.exceptions;
import java.lang.reflect.InvocationTargetException; import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -318,9 +317,8 @@ public abstract class BaseServerResponseException extends RuntimeException {
} catch (SecurityException e) { } catch (SecurityException e) {
throw new InternalErrorException(e); throw new InternalErrorException(e);
} }
} else {
return new UnclassifiedServerFailureException(theStatusCode, theMessage);
} }
return new UnclassifiedServerFailureException(theStatusCode, theMessage);
} }
static void registerExceptionType(int theStatusCode, Class<? extends BaseServerResponseException> theType) { static void registerExceptionType(int theStatusCode, Class<? extends BaseServerResponseException> theType) {

View File

@ -42,7 +42,6 @@ import ca.uhn.fhir.rest.annotation.Search;
import ca.uhn.fhir.rest.api.RestOperationTypeEnum; import ca.uhn.fhir.rest.api.RestOperationTypeEnum;
import ca.uhn.fhir.rest.method.RequestDetails; import ca.uhn.fhir.rest.method.RequestDetails;
import ca.uhn.fhir.rest.server.IRestfulServerDefaults; import ca.uhn.fhir.rest.server.IRestfulServerDefaults;
import ca.uhn.fhir.rest.server.RestfulServer;
import ca.uhn.fhir.rest.server.exceptions.AuthenticationException; import ca.uhn.fhir.rest.server.exceptions.AuthenticationException;
import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException;
import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;

View File

@ -33,7 +33,6 @@ import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.Charsets;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.text.StrLookup; import org.apache.commons.lang3.text.StrLookup;
@ -47,7 +46,6 @@ import ca.uhn.fhir.rest.server.EncodingEnum;
import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.RestfulServer;
import ca.uhn.fhir.rest.server.RestfulServerUtils; import ca.uhn.fhir.rest.server.RestfulServerUtils;
import ca.uhn.fhir.rest.server.RestfulServerUtils.ResponseEncoding; import ca.uhn.fhir.rest.server.RestfulServerUtils.ResponseEncoding;
import ca.uhn.fhir.rest.server.exceptions.AuthenticationException;
import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException; import ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException;
import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
@ -259,9 +257,8 @@ public class LoggingInterceptor extends InterceptorAdapter {
default: default:
return ""; return "";
} }
} else {
return "";
} }
return "";
} else if ("id".equals(theKey)) { } else if ("id".equals(theKey)) {
if (myRequestDetails.getId() != null) { if (myRequestDetails.getId() != null) {
return myRequestDetails.getId().getValue(); return myRequestDetails.getId().getValue();
@ -305,9 +302,8 @@ public class LoggingInterceptor extends InterceptorAdapter {
ResponseEncoding encoding = RestfulServerUtils.determineResponseEncodingNoDefault(myRequestDetails, myRequestDetails.getServer().getDefaultResponseEncoding()); ResponseEncoding encoding = RestfulServerUtils.determineResponseEncodingNoDefault(myRequestDetails, myRequestDetails.getServer().getDefaultResponseEncoding());
if (encoding != null) { if (encoding != null) {
return encoding.getEncoding().name(); return encoding.getEncoding().name();
} else {
return "";
} }
return "";
} else if (theKey.equals("exceptionMessage")) { } else if (theKey.equals("exceptionMessage")) {
return myException != null ? myException.getMessage() : null; return myException != null ? myException.getMessage() : null;
} else if (theKey.equals("requestUrl")) { } else if (theKey.equals("requestUrl")) {

View File

@ -44,7 +44,6 @@ import ca.uhn.fhir.rest.server.exceptions.AuthenticationException;
import ca.uhn.fhir.rest.server.exceptions.ForbiddenOperationException; import ca.uhn.fhir.rest.server.exceptions.ForbiddenOperationException;
import ca.uhn.fhir.rest.server.interceptor.IServerOperationInterceptor; import ca.uhn.fhir.rest.server.interceptor.IServerOperationInterceptor;
import ca.uhn.fhir.rest.server.interceptor.InterceptorAdapter; import ca.uhn.fhir.rest.server.interceptor.InterceptorAdapter;
import ca.uhn.fhir.util.BundleUtil;
import ca.uhn.fhir.util.CoverageIgnore; import ca.uhn.fhir.util.CoverageIgnore;
/** /**
@ -209,9 +208,8 @@ public class AuthorizationInterceptor extends InterceptorAdapter implements ISer
if (decision.getDecidingRule() != null) { if (decision.getDecidingRule() != null) {
String ruleName = defaultString(decision.getDecidingRule().getName(), "(unnamed rule)"); String ruleName = defaultString(decision.getDecidingRule().getName(), "(unnamed rule)");
throw new ForbiddenOperationException("Access denied by rule: " + ruleName); throw new ForbiddenOperationException("Access denied by rule: " + ruleName);
} else {
throw new ForbiddenOperationException("Access denied by default policy (no applicable rules)");
} }
throw new ForbiddenOperationException("Access denied by default policy (no applicable rules)");
} }
private void handleUserOperation(RequestDetails theRequest, IBaseResource theResource, RestOperationTypeEnum operation) { private void handleUserOperation(RequestDetails theRequest, IBaseResource theResource, RestOperationTypeEnum operation) {
@ -230,7 +228,7 @@ public class AuthorizationInterceptor extends InterceptorAdapter implements ISer
inputResourceId = theProcessedRequest.getId(); inputResourceId = theProcessedRequest.getId();
break; break;
case OUT: case OUT:
inputResource = null; // inputResource = null;
inputResourceId = theProcessedRequest.getId(); inputResourceId = theProcessedRequest.getId();
break; break;
case NONE: case NONE:

View File

@ -1,7 +1,5 @@
package ca.uhn.fhir.rest.server.interceptor.auth; package ca.uhn.fhir.rest.server.interceptor.auth;
import org.apache.http.impl.client.HttpClientBuilder;
/* /*
* #%L * #%L
* HAPI FHIR - Core Library * HAPI FHIR - Core Library

View File

@ -1,7 +1,5 @@
package ca.uhn.fhir.rest.server.interceptor.auth; package ca.uhn.fhir.rest.server.interceptor.auth;
import java.util.List;
/* /*
* #%L * #%L
* HAPI FHIR - Core Library * HAPI FHIR - Core Library

View File

@ -41,7 +41,7 @@ import ca.uhn.fhir.util.BundleUtil;
import ca.uhn.fhir.util.BundleUtil.BundleEntryParts; import ca.uhn.fhir.util.BundleUtil.BundleEntryParts;
import ca.uhn.fhir.util.FhirTerser; import ca.uhn.fhir.util.FhirTerser;
class RuleImplOp extends BaseRule implements IAuthRule { class RuleImplOp extends BaseRule /*implements IAuthRule*/ {
private AppliesTypeEnum myAppliesTo; private AppliesTypeEnum myAppliesTo;
private Set<?> myAppliesToTypes; private Set<?> myAppliesToTypes;
@ -108,9 +108,8 @@ class RuleImplOp extends BaseRule implements IAuthRule {
if (theOperation == RestOperationTypeEnum.DELETE) { if (theOperation == RestOperationTypeEnum.DELETE) {
if (theInputResource == null) { if (theInputResource == null) {
return newVerdict(); return newVerdict();
} else {
appliesToResource = theInputResource;
} }
appliesToResource = theInputResource;
} else { } else {
return null; return null;
} }
@ -123,45 +122,44 @@ class RuleImplOp extends BaseRule implements IAuthRule {
if (theInputResource != null && requestAppliesToTransaction(ctx, myOp, theInputResource)) { if (theInputResource != null && requestAppliesToTransaction(ctx, myOp, theInputResource)) {
if (getMode() == PolicyEnum.DENY) { if (getMode() == PolicyEnum.DENY) {
return new Verdict(PolicyEnum.DENY, this); return new Verdict(PolicyEnum.DENY, this);
} else {
List<BundleEntryParts> inputResources = BundleUtil.toListOfEntries(ctx, (IBaseBundle) theInputResource);
Verdict verdict = null;
for (BundleEntryParts nextPart : inputResources) {
IBaseResource inputResource = nextPart.getResource();
RestOperationTypeEnum operation = null;
if (nextPart.getRequestType() == RequestTypeEnum.GET) {
continue;
}
if (nextPart.getRequestType() == RequestTypeEnum.POST) {
operation = RestOperationTypeEnum.CREATE;
} else if (nextPart.getRequestType() == RequestTypeEnum.PUT) {
operation = RestOperationTypeEnum.UPDATE;
} else {
throw new InvalidRequestException("Can not handle transaction with operation of type " + nextPart.getRequestType());
}
/*
* This is basically just being conservative - Be careful of transactions containing
* nested operations and nested transactions. We block the by default. At some point
* it would be nice to be more nuanced here.
*/
RuntimeResourceDefinition resourceDef = ctx.getResourceDefinition(nextPart.getResource());
if ("Parameters".equals(resourceDef.getName()) || "Bundle".equals(resourceDef.getName())) {
throw new InvalidRequestException("Can not handle transaction with nested resource of type " + resourceDef.getName());
}
Verdict newVerdict = theRuleApplier.applyRulesAndReturnDecision(operation, theRequestDetails, inputResource, null, null);
if (newVerdict == null) {
continue;
} else if (verdict == null) {
verdict = newVerdict;
} else if (verdict.getDecision() == PolicyEnum.ALLOW && newVerdict.getDecision() == PolicyEnum.DENY) {
verdict = newVerdict;
}
}
return verdict;
} }
List<BundleEntryParts> inputResources = BundleUtil.toListOfEntries(ctx, (IBaseBundle) theInputResource);
Verdict verdict = null;
for (BundleEntryParts nextPart : inputResources) {
IBaseResource inputResource = nextPart.getResource();
RestOperationTypeEnum operation = null;
if (nextPart.getRequestType() == RequestTypeEnum.GET) {
continue;
}
if (nextPart.getRequestType() == RequestTypeEnum.POST) {
operation = RestOperationTypeEnum.CREATE;
} else if (nextPart.getRequestType() == RequestTypeEnum.PUT) {
operation = RestOperationTypeEnum.UPDATE;
} else {
throw new InvalidRequestException("Can not handle transaction with operation of type " + nextPart.getRequestType());
}
/*
* This is basically just being conservative - Be careful of transactions containing
* nested operations and nested transactions. We block the by default. At some point
* it would be nice to be more nuanced here.
*/
RuntimeResourceDefinition resourceDef = ctx.getResourceDefinition(nextPart.getResource());
if ("Parameters".equals(resourceDef.getName()) || "Bundle".equals(resourceDef.getName())) {
throw new InvalidRequestException("Can not handle transaction with nested resource of type " + resourceDef.getName());
}
Verdict newVerdict = theRuleApplier.applyRulesAndReturnDecision(operation, theRequestDetails, inputResource, null, null);
if (newVerdict == null) {
continue;
} else if (verdict == null) {
verdict = newVerdict;
} else if (verdict.getDecision() == PolicyEnum.ALLOW && newVerdict.getDecision() == PolicyEnum.DENY) {
verdict = newVerdict;
}
}
return verdict;
} else if (theOutputResource != null) { } else if (theOutputResource != null) {
List<BundleEntryParts> inputResources = BundleUtil.toListOfEntries(ctx, (IBaseBundle) theInputResource); List<BundleEntryParts> inputResources = BundleUtil.toListOfEntries(ctx, (IBaseBundle) theInputResource);
Verdict verdict = null; Verdict verdict = null;
@ -189,9 +187,8 @@ class RuleImplOp extends BaseRule implements IAuthRule {
case METADATA: case METADATA:
if (theOperation == RestOperationTypeEnum.METADATA) { if (theOperation == RestOperationTypeEnum.METADATA) {
return newVerdict(); return newVerdict();
} else {
return null;
} }
return null;
default: default:
// Should not happen // Should not happen
throw new IllegalStateException("Unable to apply security to event of type " + theOperation); throw new IllegalStateException("Unable to apply security to event of type " + theOperation);

Some files were not shown because too many files have changed in this diff Show More