From 7adb35d003c4d446313d4ff5d2f46a12b7051dd7 Mon Sep 17 00:00:00 2001 From: sekaijin Date: Wed, 8 Feb 2017 16:41:03 +0100 Subject: [PATCH] resolve some warnings unused then clause does not complete normally serial missing @Override remove unnecessary cast --- ...BaseRuntimeElementCompositeDefinition.java | 3 +- .../context/BaseRuntimeElementDefinition.java | 9 +- .../ca/uhn/fhir/context/FhirVersionEnum.java | 2 - .../ca/uhn/fhir/context/ModelScanner.java | 4 +- ...ntimeChildDeclaredExtensionDefinition.java | 4 +- .../context/RuntimeChildDirectResource.java | 2 +- .../fhir/context/RuntimeChildExtension.java | 2 +- .../RuntimeChildResourceBlockDefinition.java | 5 +- .../RuntimePrimitiveDatatypeDefinition.java | 5 - .../java/ca/uhn/fhir/i18n/HapiLocalizer.java | 6 +- .../ca/uhn/fhir/model/api/BaseBundle.java | 3 +- .../ca/uhn/fhir/model/api/BaseElement.java | 3 +- .../model/api/BaseIdentifiableElement.java | 4 +- .../ca/uhn/fhir/model/api/BasePrimitive.java | 1 - .../java/ca/uhn/fhir/model/api/Bundle.java | 9 +- .../ca/uhn/fhir/model/api/BundleEntry.java | 1 + .../ca/uhn/fhir/model/api/ExtensionDt.java | 5 + .../java/ca/uhn/fhir/model/api/IResource.java | 1 + .../java/ca/uhn/fhir/model/api/Include.java | 6 +- .../model/api/ResourceMetadataKeyEnum.java | 48 +- .../api/annotation/ProvidesResources.java | 2 +- .../model/base/composite/BaseCodingDt.java | 7 +- .../model/base/composite/BaseHumanNameDt.java | 5 +- .../base/composite/BaseIdentifierDt.java | 15 +- .../model/base/composite/BaseNarrativeDt.java | 2 + .../model/base/composite/BaseQuantityDt.java | 8 +- .../base/resource/BaseOperationOutcome.java | 2 + .../valueset/QuantityCompararatorEnum.java | 1 + .../fhir/model/primitive/BaseDateTimeDt.java | 95 +- .../uhn/fhir/model/primitive/BooleanDt.java | 3 +- .../ca/uhn/fhir/model/primitive/IdDt.java | 26 +- .../valueset/BundleEntrySearchModeEnum.java | 3 + .../BundleEntryTransactionMethodEnum.java | 3 + .../fhir/model/valueset/BundleTypeEnum.java | 3 + .../BaseThymeleafNarrativeGenerator.java | 61 +- .../java/ca/uhn/fhir/parser/BaseParser.java | 33 +- .../java/ca/uhn/fhir/parser/JsonParser.java | 73 +- .../java/ca/uhn/fhir/parser/ParserState.java | 16 +- .../java/ca/uhn/fhir/parser/XmlParser.java | 51 +- .../ca/uhn/fhir/rest/annotation/Delete.java | 2 - .../ca/uhn/fhir/rest/client/BaseClient.java | 1 + .../uhn/fhir/rest/client/GenericClient.java | 81 +- .../rest/client/RestfulClientFactory.java | 5 +- .../rest/client/apache/ApacheHttpClient.java | 9 +- .../rest/client/apache/ApacheHttpRequest.java | 4 +- .../client/apache/ApacheHttpResponse.java | 2 + .../apache/ApacheRestfulClientFactory.java | 2 + .../interceptor/LoggingInterceptor.java | 1 + .../fhir/rest/gclient/DateClientParam.java | 1 - .../fhir/rest/gclient/StringCriterion.java | 1 - .../ca/uhn/fhir/rest/method/BaseBinder.java | 1 - .../BaseHttpClientInvocationWithContents.java | 14 +- .../fhir/rest/method/BaseMethodBinding.java | 10 +- .../BaseOutcomeReturningMethodBinding.java | 19 +- ...indingWithResourceIdButNoResourceBody.java | 3 +- ...turningMethodBindingWithResourceParam.java | 3 +- .../BaseResourceReturningMethodBinding.java | 41 +- .../rest/method/ConditionalParamBinder.java | 23 - .../rest/method/ConformanceMethodBinding.java | 3 +- .../method/DynamicSearchMethodBinding.java | 2 +- .../fhir/rest/method/ElementsParameter.java | 3 +- .../fhir/rest/method/FhirPrimitiveBinder.java | 22 - .../rest/method/GetTagsMethodBinding.java | 5 +- .../rest/method/HistoryMethodBinding.java | 1 + .../fhir/rest/method/IncludeParameter.java | 7 +- .../ca/uhn/fhir/rest/method/MethodUtil.java | 4 +- .../rest/method/OperationMethodBinding.java | 58 +- .../fhir/rest/method/OperationParameter.java | 5 +- .../fhir/rest/method/PageMethodBinding.java | 6 +- .../ca/uhn/fhir/rest/method/ParseAction.java | 2 - .../fhir/rest/method/PatchTypeParameter.java | 1 - .../fhir/rest/method/QualifiedParamList.java | 3 +- .../fhir/rest/method/ReadMethodBinding.java | 3 +- .../RequestOperationCallbackParameter.java | 3 +- .../fhir/rest/method/SearchMethodBinding.java | 6 +- .../uhn/fhir/rest/method/SearchParameter.java | 4 +- .../fhir/rest/method/SinceOrAtParameter.java | 48 +- .../rest/method/TransactionMethodBinding.java | 9 +- .../fhir/rest/method/UpdateMethodBinding.java | 10 +- .../fhir/rest/param/BaseQueryParameter.java | 3 +- .../ca/uhn/fhir/rest/param/DateParam.java | 6 +- .../uhn/fhir/rest/param/DateRangeParam.java | 1 + .../uhn/fhir/rest/param/InternalCodingDt.java | 10 + .../uhn/fhir/rest/param/ParamPrefixEnum.java | 3 +- .../ca/uhn/fhir/rest/param/ParameterUtil.java | 3 +- .../uhn/fhir/rest/param/ReferenceParam.java | 6 +- .../fhir/rest/param/ResourceParameter.java | 4 +- .../ca/uhn/fhir/rest/param/TokenParam.java | 9 +- .../fhir/rest/param/TransactionParameter.java | 6 +- .../uhn/fhir/rest/server/IRestfulServer.java | 3 - .../uhn/fhir/rest/server/ResourceBinding.java | 3 +- .../uhn/fhir/rest/server/RestfulServer.java | 67 +- .../fhir/rest/server/RestfulServerUtils.java | 9 +- .../BaseServerResponseException.java | 4 +- .../interceptor/IServerInterceptor.java | 1 - .../interceptor/LoggingInterceptor.java | 8 +- .../auth/AuthorizationInterceptor.java | 6 +- .../auth/IAuthRuleBuilderOperationNamed.java | 2 - ...hRuleBuilderRuleConditionalClassifier.java | 2 - .../server/interceptor/auth/RuleImplOp.java | 83 +- .../server/servlet/ServletRequestDetails.java | 2 +- .../servlet/ServletRestfulResponse.java | 12 +- .../java/ca/uhn/fhir/util/ElementUtil.java | 6 +- .../java/ca/uhn/fhir/util/FhirTerser.java | 21 +- .../java/ca/uhn/fhir/util/IModelVisitor.java | 2 - .../uhn/fhir/util/OperationOutcomeUtil.java | 3 +- .../main/java/ca/uhn/fhir/util/PortUtil.java | 1 + .../java/ca/uhn/fhir/util/ReflectionUtil.java | 3 +- .../uhn/fhir/util/ResourceReferenceInfo.java | 5 +- .../main/java/ca/uhn/fhir/util/UrlUtil.java | 74 +- .../main/java/ca/uhn/fhir/util/XmlUtil.java | 3 +- .../uhn/fhir/util/jar/DependencyLogImpl.java | 3 +- .../fhir/validation/SchemaBaseValidator.java | 4 +- .../fhir/exceptions/DefinitionException.java | 2 + .../hl7/fhir/exceptions/FHIRException.java | 2 + .../NoTerminologyServiceException.java | 2 + .../fhir/exceptions/PathEngineException.java | 2 + .../TerminologyServiceException.java | 2 + .../hl7/fhir/exceptions/UcumException.java | 2 + .../hl7/fhir/instance/model/api/IIdType.java | 2 + .../fhir/instance/model/api/INarrative.java | 1 + .../org/hl7/fhir/utilities/MyURIResolver.java | 55 +- .../java/org/hl7/fhir/utilities/Table.java | 4 +- .../java/org/hl7/fhir/utilities/TextFile.java | 93 +- .../org/hl7/fhir/utilities/Utilities.java | 1818 ++++++++--------- .../org/hl7/fhir/utilities/ucum/Decimal.java | 30 +- .../xhtml/HierarchicalTableGenerator.java | 78 +- .../fhir/utilities/xhtml/XhtmlDocument.java | 24 +- .../hl7/fhir/utilities/xhtml/XhtmlNode.java | 557 ++--- .../hl7/fhir/utilities/xhtml/XhtmlParser.java | 77 +- .../org/hl7/fhir/utilities/xml/XMLUtil.java | 54 +- .../org/hl7/fhir/utilities/xml/XMLWriter.java | 47 +- .../parser/json/JsonLikeStructureTest.java | 6 +- .../java/ca/uhn/fhir/util/UrlUtilTest.java | 6 +- hapi-fhir-structures-dstu2/pom.xml | 6 +- hapi-fhir-structures-hl7org-dstu2/pom.xml | 6 +- 136 files changed, 2053 insertions(+), 2161 deletions(-) diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/BaseRuntimeElementCompositeDefinition.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/BaseRuntimeElementCompositeDefinition.java index 2ec9745efaf..1bf3cec2f60 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/BaseRuntimeElementCompositeDefinition.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/BaseRuntimeElementCompositeDefinition.java @@ -474,9 +474,8 @@ public abstract class BaseRuntimeElementCompositeDefinition ext for (String nextName : next.getValidChildNames()) { if (myNameToChild.containsKey(nextName)) { throw new ConfigurationException("Duplicate child name[" + nextName + "] in Element[" + getName() + "]"); - } else { - myNameToChild.put(nextName, next); } + myNameToChild.put(nextName, next); } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/BaseRuntimeElementDefinition.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/BaseRuntimeElementDefinition.java index e4107a028c0..3121a8ad1ae 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/BaseRuntimeElementDefinition.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/BaseRuntimeElementDefinition.java @@ -148,10 +148,10 @@ public abstract class BaseRuntimeElementDefinition { public T newInstance(Object theArgument) { try { if (theArgument == null) { - return getConstructor(null).newInstance(null); - } else { - return getConstructor(theArgument).newInstance(theArgument); + return getConstructor(null).newInstance(); } + return getConstructor(theArgument).newInstance(theArgument); + } catch (Exception e) { throw new ConfigurationException("Failed to instantiate type:" + getImplementingClass().getName(), e); } @@ -171,9 +171,8 @@ public abstract class BaseRuntimeElementDefinition { String extUrl = next.getExtensionUrl(); if (myUrlToExtension.containsKey(extUrl)) { throw new ConfigurationException("Duplicate extension URL[" + extUrl + "] in Element[" + getName() + "]"); - } else { - myUrlToExtension.put(extUrl, next); } + myUrlToExtension.put(extUrl, next); if (next.isModifier()) { myExtensionsModifier.add(next); } else { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/FhirVersionEnum.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/FhirVersionEnum.java index 44c35d99ca4..ce4e4b41ef7 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/FhirVersionEnum.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/FhirVersionEnum.java @@ -1,7 +1,5 @@ package ca.uhn.fhir.context; -import java.util.concurrent.Callable; - /* * #%L * HAPI FHIR - Core Library diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/ModelScanner.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/ModelScanner.java index e1d96461213..ac6015635e3 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/ModelScanner.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/ModelScanner.java @@ -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"); } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildDeclaredExtensionDefinition.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildDeclaredExtensionDefinition.java index 5012deba3db..706368937bb 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildDeclaredExtensionDefinition.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildDeclaredExtensionDefinition.java @@ -114,9 +114,9 @@ public class RuntimeChildDeclaredExtensionDefinition extends RuntimeChildChoiceD if (retVal == null) { if (myModifier) { return "modifierExtension"; - } else { - return "extension"; } + return "extension"; + } return retVal; } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildDirectResource.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildDirectResource.java index 52829f7067a..35dc42b206d 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildDirectResource.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildDirectResource.java @@ -33,7 +33,7 @@ import ca.uhn.fhir.model.api.annotation.Description; public class RuntimeChildDirectResource extends BaseRuntimeDeclaredChildDefinition { - private RuntimeElemContainedResources myElem; +// private RuntimeElemContainedResources myElem; private FhirContext myContext; RuntimeChildDirectResource(Field theField, Child theChildAnnotation, Description theDescriptionAnnotation, String theElementName) throws ConfigurationException { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildExtension.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildExtension.java index cf3dc0145ce..044c661e632 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildExtension.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildExtension.java @@ -31,7 +31,7 @@ import ca.uhn.fhir.model.api.annotation.Description; public class RuntimeChildExtension extends RuntimeChildAny { - private RuntimeChildUndeclaredExtensionDefinition myExtensionElement; +// private RuntimeChildUndeclaredExtensionDefinition myExtensionElement; public RuntimeChildExtension(Field theField, String theElementName, Child theChildAnnotation, Description theDescriptionAnnotation) { super(theField, theElementName, theChildAnnotation, theDescriptionAnnotation); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildResourceBlockDefinition.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildResourceBlockDefinition.java index 81f2835a914..e622d876613 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildResourceBlockDefinition.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimeChildResourceBlockDefinition.java @@ -32,7 +32,7 @@ import ca.uhn.fhir.model.api.annotation.Description; public class RuntimeChildResourceBlockDefinition extends BaseRuntimeDeclaredChildDefinition { - private RuntimeResourceBlockDefinition myElementDef; +// private RuntimeResourceBlockDefinition myElementDef; private Class myResourceBlockType; private FhirContext myContext; @@ -46,9 +46,8 @@ public class RuntimeChildResourceBlockDefinition extends BaseRuntimeDeclaredChil public RuntimeResourceBlockDefinition getChildByName(String theName) { if (getElementName().equals(theName)) { return getDefinition(); - }else { - return null; } + return null; } private RuntimeResourceBlockDefinition getDefinition() { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimePrimitiveDatatypeDefinition.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimePrimitiveDatatypeDefinition.java index f22dca3a832..d6f89a0ec29 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimePrimitiveDatatypeDefinition.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/context/RuntimePrimitiveDatatypeDefinition.java @@ -21,21 +21,16 @@ package ca.uhn.fhir.context; */ import static org.apache.commons.lang3.StringUtils.isBlank; -import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -import java.lang.reflect.TypeVariable; import java.util.Map; import org.hl7.fhir.instance.model.api.IBase; import org.hl7.fhir.instance.model.api.IBaseDatatype; 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.ResourceDef; -import ca.uhn.fhir.util.CoverageIgnore; public class RuntimePrimitiveDatatypeDefinition extends BaseRuntimeElementDefinition> implements IRuntimeDatatypeDefinition { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/i18n/HapiLocalizer.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/i18n/HapiLocalizer.java index d21169083a5..6646f8fe34b 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/i18n/HapiLocalizer.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/i18n/HapiLocalizer.java @@ -93,13 +93,11 @@ public class HapiLocalizer { format = new MessageFormat(formatString.trim()); myKeyToMessageFormat.put(theQualifiedKey, format); return format.format(theParameters).toString(); - } else { - String retVal = findFormatString(theQualifiedKey); - return retVal; } + String retVal = findFormatString(theQualifiedKey); + return retVal; } - public Set getAllKeys(){ HashSet retVal = new HashSet(); for (ResourceBundle nextBundle : myBundle) { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseBundle.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseBundle.java index ed101c996d4..568bf15758d 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseBundle.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseBundle.java @@ -24,8 +24,9 @@ import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.model.primitive.StringDt; 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 myAuthorUri; private IdDt myId; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseElement.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseElement.java index 89c7fc52082..301ec430c03 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseElement.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseElement.java @@ -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.Description; -public abstract class BaseElement implements IElement, ISupportsUndeclaredExtensions { +public abstract class BaseElement implements /*IElement, */ISupportsUndeclaredExtensions { + private static final long serialVersionUID = -3092659584634499332L; private List myFormatCommentsPost; private List myFormatCommentsPre; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseIdentifiableElement.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseIdentifiableElement.java index d9aa36cec83..e32cb76248b 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseIdentifiableElement.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BaseIdentifiableElement.java @@ -26,6 +26,7 @@ import ca.uhn.fhir.util.CoverageIgnore; public abstract class BaseIdentifiableElement extends BaseElement implements IIdentifiableElement { + private static final long serialVersionUID = -7816838417076777914L; private String myElementSpecificId; @Override @@ -43,9 +44,8 @@ public abstract class BaseIdentifiableElement extends BaseElement implements IId public IdDt getId() { if (myElementSpecificId == null) { return new LockedId(); - } else { - return new LockedId(myElementSpecificId); } + return new LockedId(myElementSpecificId); } @Override diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BasePrimitive.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BasePrimitive.java index b2ddacc0060..03bdd8541dc 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BasePrimitive.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BasePrimitive.java @@ -27,7 +27,6 @@ import java.io.ObjectOutput; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; -import org.hl7.fhir.instance.model.api.IPrimitiveType; import ca.uhn.fhir.parser.DataFormatException; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/Bundle.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/Bundle.java index b0116a4422a..0f4de315e06 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/Bundle.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/Bundle.java @@ -30,7 +30,6 @@ import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.builder.ToStringBuilder; 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.RuntimeResourceDefinition; @@ -47,8 +46,9 @@ import ca.uhn.fhir.model.valueset.BundleTypeEnum; import ca.uhn.fhir.rest.server.Constants; 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 BoundCodeDt myType; private StringDt myBundleId; @@ -127,6 +127,7 @@ public class Bundle extends BaseBundle implements IBase /* implements IElement * if (theResource.getId().isAbsolute()) { entry.getLinkSelf().setValue(theResource.getId().getValue()); + //TODO: Use of a deprecated method should be resolved. entry.getId().setValue(theResource.getId().toVersionless().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(); b.append(resId); + //TODO: Use of a deprecated method should be resolved. entry.getId().setValue(b.toString()); if (isNotBlank(theResource.getId().getVersionIdPart())) { @@ -149,6 +151,7 @@ public class Bundle extends BaseBundle implements IBase /* implements IElement * b.append('/'); b.append(theResource.getId().getVersionIdPart()); } else { + //TODO: Use of a deprecated method should be resolved. IdDt versionId = (IdDt) ResourceMetadataKeyEnum.VERSION_ID.get(theResource); if (versionId != null) { b.append('/'); @@ -176,6 +179,7 @@ public class Bundle extends BaseBundle implements IBase /* implements IElement * InstantDt updated = ResourceMetadataKeyEnum.UPDATED.get(theResource); if (updated != null) { + //TODO: Use of a deprecated method should be resolved. entry.setUpdated(updated); } @@ -323,6 +327,7 @@ public class Bundle extends BaseBundle implements IBase /* implements IElement * if (map == null) { map = new HashMap(); for (BundleEntry next : this.getEntries()) { + //TODO: Use of a deprecated method should be resolved. if (next.getId().isEmpty() == false) { map.put(next.getId().toUnqualified(), next.getResource()); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BundleEntry.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BundleEntry.java index 41bb2a6fbf6..572a372648e 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BundleEntry.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/BundleEntry.java @@ -37,6 +37,7 @@ import ca.uhn.fhir.util.ElementUtil; public class BundleEntry extends BaseBundle { + private static final long serialVersionUID = 2635639739195593736L; //@formatter:off /* **************************************************** * NB: add any new fields to the isEmpty() method!!! diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/ExtensionDt.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/ExtensionDt.java index 18dede5ab8b..ca83d6ab10f 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/ExtensionDt.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/ExtensionDt.java @@ -36,6 +36,8 @@ import ca.uhn.fhir.model.primitive.StringDt; @DatatypeDef(name = "Extension") public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDatatype, IBaseExtension { + private static final long serialVersionUID = 6399491332783085935L; + private boolean myModifier; @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. *

*/ + @Override public String getUrl() { return myUrl != null ? myUrl.getValue() : null; } @@ -95,6 +98,7 @@ public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDa * {@link #getUndeclaredModifierExtensions()} to retrieve the child extensions. *

*/ + @Override public IBaseDatatype getValue() { return myValue; } @@ -148,6 +152,7 @@ public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDa } @Override + @Deprecated //override deprecated method public List getAllPopulatedChildElementsOfType(Class theType) { return new ArrayList(); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/IResource.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/IResource.java index ba9f34840aa..3b4f6d923d8 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/IResource.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/IResource.java @@ -71,6 +71,7 @@ public interface IResource extends ICompositeElement, org.hl7.fhir.instance.mode * * @since 1.5 */ + @Override IBaseMetaType getMeta(); /** diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/Include.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/Include.java index 2529f16a147..f1fa8ea571c 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/Include.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/Include.java @@ -142,9 +142,8 @@ public class Include { int secondColon = myValue.indexOf(':', firstColon + 1); if (secondColon != -1) { 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); if (secondColon != -1) { return myValue.substring(secondColon + 1); - } else { - return null; } + return null; } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/ResourceMetadataKeyEnum.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/ResourceMetadataKeyEnum.java index 671af0b64f8..603ef37151f 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/ResourceMetadataKeyEnum.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/ResourceMetadataKeyEnum.java @@ -307,21 +307,19 @@ public abstract class ResourceMetadataKeyEnum implements Serializable { Object obj = resource.getResourceMetadata().get(SECURITY_LABELS); if (obj == null) { return null; - } else { - try { - @SuppressWarnings("unchecked") - List securityLabels = (List) 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 securityLabels = (List) 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 @@ -349,9 +347,8 @@ public abstract class ResourceMetadataKeyEnum implements Serializable { } else if (retValObj instanceof TagList) { if (((TagList) retValObj).isEmpty()) { 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 " + TagList.class.getCanonicalName()); @@ -496,9 +493,8 @@ public abstract class ResourceMetadataKeyEnum implements Serializable { } else if (retValObj instanceof DecimalDt) { if (((DecimalDt) retValObj).isEmpty()) { return null; - } else { - return (DecimalDt) retValObj; } + return (DecimalDt) retValObj; } else if (retValObj instanceof String) { if (StringUtils.isBlank((String) retValObj)) { return null; @@ -562,9 +558,8 @@ public abstract class ResourceMetadataKeyEnum implements Serializable { } else if (retValObj instanceof InstantDt) { if (((InstantDt) retValObj).isEmpty()) { 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 " + InstantDt.class.getCanonicalName()); @@ -577,9 +572,8 @@ public abstract class ResourceMetadataKeyEnum implements Serializable { } else if (retValObj instanceof String) { if (StringUtils.isBlank(((String) retValObj))) { 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 " + String.class.getCanonicalName()); @@ -591,15 +585,13 @@ public abstract class ResourceMetadataKeyEnum implements Serializable { } else if (retValObj instanceof String) { if (isNotBlank((String) retValObj)) { return new IdDt((String) retValObj); - } else { - return null; } + return null; } else if (retValObj instanceof IdDt) { if (((IdDt) retValObj).isEmpty()) { return null; - } else { - return (IdDt) retValObj; } + return (IdDt) retValObj; } else if (retValObj instanceof Number) { return new IdDt(((Number) retValObj).toString()); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/annotation/ProvidesResources.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/annotation/ProvidesResources.java index 13b82d2dd34..ff3e770271e 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/annotation/ProvidesResources.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/api/annotation/ProvidesResources.java @@ -39,5 +39,5 @@ import java.lang.annotation.RetentionPolicy; */ @Retention(RetentionPolicy.RUNTIME) public @interface ProvidesResources { - Class[] resources(); + Class[] resources(); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseCodingDt.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseCodingDt.java index c86e1b53219..fd3821eb44c 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseCodingDt.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseCodingDt.java @@ -34,6 +34,8 @@ import ca.uhn.fhir.rest.param.TokenParam; public abstract class BaseCodingDt extends BaseIdentifiableElement implements ICompositeDatatype, IQueryParameterType { + private static final long serialVersionUID = 4425182816398730643L; + /** * Gets the value(s) for code (Symbol in syntax defined by the system). creating it if it does not exist. Will not return null. * @@ -85,9 +87,8 @@ public abstract class BaseCodingDt extends BaseIdentifiableElement implements IC public String getValueAsQueryToken(FhirContext theContext) { if (getSystemElement().getValueAsString() != null) { return ParameterUtil.escape(StringUtils.defaultString(getSystemElement().getValueAsString())) + '|' + ParameterUtil.escape(getCodeElement().getValueAsString()); - } else { - return ParameterUtil.escape(getCodeElement().getValueAsString()); - } + } + return ParameterUtil.escape(getCodeElement().getValueAsString()); } /** diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseHumanNameDt.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseHumanNameDt.java index aaf206abf65..c25a128eb60 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseHumanNameDt.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseHumanNameDt.java @@ -32,6 +32,8 @@ import ca.uhn.fhir.util.DatatypeUtil; public abstract class BaseHumanNameDt extends BaseIdentifiableElement { + private static final long serialVersionUID = 2765500013165698259L; + /** * Gets the value(s) for family (Family name (often called 'Surname')). creating it if it does not exist. Will not return null. * @@ -146,9 +148,8 @@ public abstract class BaseHumanNameDt extends BaseIdentifiableElement { nameParts.addAll(getSuffix()); if (nameParts.size() > 0) { return ca.uhn.fhir.util.DatatypeUtil.joinStringsSpaceSeparated(nameParts); - } else { - return getTextElement().getValue(); } + return getTextElement().getValue(); } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseIdentifierDt.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseIdentifierDt.java index 97bb7dad22f..64474417a5d 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseIdentifierDt.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseIdentifierDt.java @@ -33,6 +33,8 @@ import ca.uhn.fhir.rest.param.StringParam; public abstract class BaseIdentifierDt extends BaseIdentifiableElement implements ICompositeDatatype, IQueryParameterType { + private static final long serialVersionUID = 4400972469749953077L; + @Override public String getQueryParameterQualifier() { return null; @@ -61,13 +63,12 @@ public abstract class BaseIdentifierDt extends BaseIdentifiableElement implement */ @Override public String getValueAsQueryToken(FhirContext theContext) { - UriDt system = (UriDt) getSystemElement(); - StringDt value = (StringDt) getValueElement(); - if (system.getValueAsString() != null) { - return ParameterUtil.escape(StringUtils.defaultString(system.getValueAsString())) + '|' + ParameterUtil.escape(value.getValueAsString()); - } else { - return ParameterUtil.escape(value.getValueAsString()); - } + UriDt system = getSystemElement(); + StringDt value = getValueElement(); + if (system.getValueAsString() != null) { + return ParameterUtil.escape(StringUtils.defaultString(system.getValueAsString())) + '|' + ParameterUtil.escape(value.getValueAsString()); + } + return ParameterUtil.escape(value.getValueAsString()); } /** diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseNarrativeDt.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseNarrativeDt.java index c0b756d89f5..10de03d0d76 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseNarrativeDt.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseNarrativeDt.java @@ -32,6 +32,8 @@ import ca.uhn.fhir.model.primitive.XhtmlDt; */ public abstract class BaseNarrativeDt> extends BaseIdentifiableElement implements ICompositeDatatype, INarrative { + private static final long serialVersionUID = -525238683230100077L; + public abstract BoundCodeDt getStatus(); @Override diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseQuantityDt.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseQuantityDt.java index ef12d27fa14..e8490c195ce 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseQuantityDt.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/composite/BaseQuantityDt.java @@ -28,6 +28,7 @@ import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.api.BaseIdentifiableElement; import ca.uhn.fhir.model.api.ICompositeDatatype; 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.primitive.BoundCodeDt; 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 { - + private static final long serialVersionUID = -925486613033086056L; + /** * Sets the value(s) for value (Numerical value (with implicit precision)) * @@ -64,15 +66,19 @@ public abstract class BaseQuantityDt extends BaseIdentifiableElement implements String[] parts = theValue.split("\\|"); if (parts.length > 0 && StringUtils.isNotBlank(parts[0])) { if (parts[0].startsWith("<=")) { + //TODO: Use of a deprecated method should be resolved. getComparatorElement().setValue(QuantityCompararatorEnum.LESSTHAN_OR_EQUALS.getCode()); setValue(new BigDecimal(parts[0].substring(2))); } else if (parts[0].startsWith("<")) { + //TODO: Use of a deprecated method should be resolved. getComparatorElement().setValue(QuantityCompararatorEnum.LESSTHAN.getCode()); setValue(new BigDecimal(parts[0].substring(1))); } else if (parts[0].startsWith(">=")) { + //TODO: Use of a deprecated method should be resolved. getComparatorElement().setValue(QuantityCompararatorEnum.GREATERTHAN_OR_EQUALS.getCode()); setValue(new BigDecimal(parts[0].substring(2))); } else if (parts[0].startsWith(">")) { + //TODO: Use of a deprecated method should be resolved. getComparatorElement().setValue(QuantityCompararatorEnum.GREATERTHAN.getCode()); setValue(new BigDecimal(parts[0].substring(1))); } else { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/resource/BaseOperationOutcome.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/resource/BaseOperationOutcome.java index 83db641b8a5..95cc6d25611 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/resource/BaseOperationOutcome.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/base/resource/BaseOperationOutcome.java @@ -40,6 +40,8 @@ public interface BaseOperationOutcome extends IResource, IBaseOperationOutcome { public static abstract class BaseIssue extends BaseIdentifiableElement implements IResourceBlock { + private static final long serialVersionUID = 6700020892151450738L; + public abstract CodeDt getSeverityElement(); public abstract StringDt getDetailsElement(); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/dstu/valueset/QuantityCompararatorEnum.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/dstu/valueset/QuantityCompararatorEnum.java index 1e6adcadacc..3f57e0ba73c 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/dstu/valueset/QuantityCompararatorEnum.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/dstu/valueset/QuantityCompararatorEnum.java @@ -119,6 +119,7 @@ public enum QuantityCompararatorEnum { /** * Converts codes to their respective enumerated values */ + @SuppressWarnings("serial") public static final IValueSetEnumBinder VALUESET_BINDER = new IValueSetEnumBinder() { @Override public String toCodeString(QuantityCompararatorEnum theEnum) { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/BaseDateTimeDt.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/BaseDateTimeDt.java index b0ba33a2112..f579baccf1b 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/BaseDateTimeDt.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/BaseDateTimeDt.java @@ -98,65 +98,64 @@ public abstract class BaseDateTimeDt extends BasePrimitive { protected String encode(Date theValue) { if (theValue == null) { return null; + } + GregorianCalendar cal; + if (myTimeZoneZulu) { + cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); + } else if (myTimeZone != null) { + cal = new GregorianCalendar(myTimeZone); } else { - GregorianCalendar cal; - if (myTimeZoneZulu) { - cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); - } else if (myTimeZone != null) { - cal = new GregorianCalendar(myTimeZone); - } else { - cal = new GregorianCalendar(); - } - cal.setTime(theValue); + cal = new GregorianCalendar(); + } + cal.setTime(theValue); - StringBuilder b = new StringBuilder(); - leftPadWithZeros(cal.get(Calendar.YEAR), 4, b); - if (myPrecision.ordinal() > TemporalPrecisionEnum.YEAR.ordinal()) { + StringBuilder b = new StringBuilder(); + leftPadWithZeros(cal.get(Calendar.YEAR), 4, b); + if (myPrecision.ordinal() > TemporalPrecisionEnum.YEAR.ordinal()) { + b.append('-'); + leftPadWithZeros(cal.get(Calendar.MONTH) + 1, 2, b); + if (myPrecision.ordinal() > TemporalPrecisionEnum.MONTH.ordinal()) { b.append('-'); - leftPadWithZeros(cal.get(Calendar.MONTH) + 1, 2, b); - if (myPrecision.ordinal() > TemporalPrecisionEnum.MONTH.ordinal()) { - b.append('-'); - leftPadWithZeros(cal.get(Calendar.DATE), 2, b); - if (myPrecision.ordinal() > TemporalPrecisionEnum.DAY.ordinal()) { - b.append('T'); - leftPadWithZeros(cal.get(Calendar.HOUR_OF_DAY), 2, b); + leftPadWithZeros(cal.get(Calendar.DATE), 2, b); + if (myPrecision.ordinal() > TemporalPrecisionEnum.DAY.ordinal()) { + b.append('T'); + leftPadWithZeros(cal.get(Calendar.HOUR_OF_DAY), 2, b); + b.append(':'); + leftPadWithZeros(cal.get(Calendar.MINUTE), 2, b); + if (myPrecision.ordinal() > TemporalPrecisionEnum.MINUTE.ordinal()) { b.append(':'); - leftPadWithZeros(cal.get(Calendar.MINUTE), 2, b); - if (myPrecision.ordinal() > TemporalPrecisionEnum.MINUTE.ordinal()) { - b.append(':'); - leftPadWithZeros(cal.get(Calendar.SECOND), 2, b); - if (myPrecision.ordinal() > TemporalPrecisionEnum.SECOND.ordinal()) { - b.append('.'); - b.append(myFractionalSeconds); - for (int i = myFractionalSeconds.length(); i < 3; i++) { - b.append('0'); - } + leftPadWithZeros(cal.get(Calendar.SECOND), 2, b); + if (myPrecision.ordinal() > TemporalPrecisionEnum.SECOND.ordinal()) { + b.append('.'); + b.append(myFractionalSeconds); + for (int i = myFractionalSeconds.length(); i < 3; i++) { + b.append('0'); } } + } - if (myTimeZoneZulu) { - b.append('Z'); - } else if (myTimeZone != null) { - int offset = myTimeZone.getOffset(theValue.getTime()); - if (offset >= 0) { - b.append('+'); - } else { - b.append('-'); - 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); + if (myTimeZoneZulu) { + b.append('Z'); + } else if (myTimeZone != null) { + int offset = myTimeZone.getOffset(theValue.getTime()); + if (offset >= 0) { + b.append('+'); + } else { + b.append('-'); + 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); } } } - return b.toString(); } + return b.toString(); } /** @@ -671,7 +670,7 @@ public abstract class BaseDateTimeDt extends BasePrimitive { public BaseDateTimeDt setNanos(long theNanos) { validateValueInRange(theNanos, 0, NANOS_PER_SECOND-1); String fractionalSeconds = StringUtils.leftPad(Long.toString(theNanos), 9, '0'); - + // Strip trailing 0s for (int i = fractionalSeconds.length(); i > 0; i--) { if (fractionalSeconds.charAt(i-1) != '0') { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/BooleanDt.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/BooleanDt.java index d3112bd417d..751c43077fc 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/BooleanDt.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/BooleanDt.java @@ -60,9 +60,8 @@ public class BooleanDt extends BasePrimitive implements IBaseBooleanDat protected String encode(Boolean theValue) { if (Boolean.TRUE.equals(theValue)) { return "true"; - } else { - return "false"; } + return "false"; } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/IdDt.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/IdDt.java index 6c888f6b92e..008b7fb3e0d 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/IdDt.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/IdDt.java @@ -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.IIdType; -import ca.uhn.fhir.model.api.IPrimitiveDatatype; import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.api.annotation.DatatypeDef; import ca.uhn.fhir.model.api.annotation.SimpleSetter; @@ -54,7 +53,7 @@ import ca.uhn.fhir.util.UrlUtil; *

*/ @DatatypeDef(name = "id", profileOf = StringDt.class) -public class IdDt extends UriDt implements IPrimitiveDatatype, IIdType { +public class IdDt extends UriDt implements /*IPrimitiveDatatype, */IIdType { private String myBaseUrl; private boolean myHaveComponentParts; @@ -183,6 +182,7 @@ public class IdDt extends UriDt implements IPrimitiveDatatype, IIdType { setValue(theUrl.getValueAsString()); } + @Override public void applyTo(IBaseResource theResouce) { if (theResouce == null) { throw new NullPointerException("theResource can not be null"); @@ -332,12 +332,12 @@ public class IdDt extends UriDt implements IPrimitiveDatatype, IIdType { return myUnqualifiedVersionId; } + @Override public Long getVersionIdPartAsLong() { if (!hasVersionIdPart()) { return null; - } else { - return Long.parseLong(getVersionIdPart()); } + return Long.parseLong(getVersionIdPart()); } /** @@ -345,6 +345,7 @@ public class IdDt extends UriDt implements IPrimitiveDatatype, IIdType { * * @see #getBaseUrl() */ + @Override public boolean hasBaseUrl() { return isNotBlank(myBaseUrl); } @@ -440,7 +441,9 @@ public class IdDt extends UriDt implements IPrimitiveDatatype, IIdType { /** * Copies the value from the given IdDt to this 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 public void setId(IdDt theId) { setValue(theId.getValue()); @@ -666,15 +669,14 @@ public class IdDt extends UriDt implements IPrimitiveDatatype, IIdType { public static IdDt of(IBaseResource theResouce) { if (theResouce == 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 { - IIdType retVal = theResouce.getIdElement(); - if (retVal == null) { - return null; - } else if (retVal instanceof IdDt) { - return (IdDt) retVal; - } else { - return new IdDt(retVal.getValue()); - } + return new IdDt(retVal.getValue()); } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/valueset/BundleEntrySearchModeEnum.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/valueset/BundleEntrySearchModeEnum.java index 735d3306877..ed055699d59 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/valueset/BundleEntrySearchModeEnum.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/valueset/BundleEntrySearchModeEnum.java @@ -90,6 +90,9 @@ public enum BundleEntrySearchModeEnum { * Converts codes to their respective enumerated values */ public static final IValueSetEnumBinder VALUESET_BINDER = new IValueSetEnumBinder() { + + private static final long serialVersionUID = -3836039426814809083L; + @Override public String toCodeString(BundleEntrySearchModeEnum theEnum) { return theEnum.getCode(); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/valueset/BundleEntryTransactionMethodEnum.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/valueset/BundleEntryTransactionMethodEnum.java index 3c6e5fc6122..42fd2b353d8 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/valueset/BundleEntryTransactionMethodEnum.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/valueset/BundleEntryTransactionMethodEnum.java @@ -97,6 +97,9 @@ public enum BundleEntryTransactionMethodEnum { * Converts codes to their respective enumerated values */ public static final IValueSetEnumBinder VALUESET_BINDER = new IValueSetEnumBinder() { + + private static final long serialVersionUID = 7569681479045998433L; + @Override public String toCodeString(BundleEntryTransactionMethodEnum theEnum) { return theEnum.getCode(); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/valueset/BundleTypeEnum.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/valueset/BundleTypeEnum.java index 49ed6266e2a..627109c54f7 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/valueset/BundleTypeEnum.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/valueset/BundleTypeEnum.java @@ -102,6 +102,9 @@ public enum BundleTypeEnum { * Converts codes to their respective enumerated values */ public static final IValueSetEnumBinder VALUESET_BINDER = new IValueSetEnumBinder() { + + private static final long serialVersionUID = -305725916208867517L; + @Override public String toCodeString(BundleTypeEnum theEnum) { return theEnum.getCode(); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/narrative/BaseThymeleafNarrativeGenerator.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/narrative/BaseThymeleafNarrativeGenerator.java index 507a98c6bbb..69a898fe2ba 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/narrative/BaseThymeleafNarrativeGenerator.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/narrative/BaseThymeleafNarrativeGenerator.java @@ -85,10 +85,7 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener initialize(theContext); } - String name = null; - if (name == null) { - name = myClassToName.get(theResource.getClass()); - } + String name = myClassToName.get(theResource.getClass()); if (name == null) { name = theContext.getResourceDefinition(theResource).getName().toLowerCase(); } @@ -97,9 +94,8 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener if (myIgnoreMissingTemplates) { ourLog.debug("No narrative template available for resorce: {}", name); 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 { @@ -132,10 +128,9 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener } theNarrative.setStatusAsString("empty"); return; - } else { + } throw new DataFormatException(e); } - } } protected abstract List getPropertyFile(); @@ -229,6 +224,7 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener String narrativePropName = name + ".narrative"; String narrativeName = file.getProperty(narrativePropName); if (isBlank(narrativeName)) { + //FIXME resource leak 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"); } } + //FIXME resource leak return resource; } else if (name.startsWith("file:")) { File file = new File(name.substring("file:".length())); @@ -418,31 +415,30 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener context.setVariable("resource", value); String name = null; - if (value != null) { - Class nextClass = value.getClass(); - do { - name = myClassToName.get(nextClass); - nextClass = nextClass.getSuperclass(); - } while (name == null && nextClass.equals(Object.class) == false); - if (name == null) { - if (value instanceof IBaseResource) { - name = myContext.getResourceDefinition((Class) value).getName(); - } else if (value instanceof IDatatype) { - name = value.getClass().getSimpleName(); - name = name.substring(0, name.length() - 2); - } else if (value instanceof IBaseDatatype) { - name = value.getClass().getSimpleName(); - if (name.endsWith("Type")) { - name = name.substring(0, name.length() - 4); - } - } else { - throw new DataFormatException("Don't know how to determine name for type: " + value.getClass()); - } - name = name.toLowerCase(); - if (!myNameToNarrativeTemplate.containsKey(name)) { - name = null; + Class nextClass = value.getClass(); + do { + name = myClassToName.get(nextClass); + nextClass = nextClass.getSuperclass(); + } while (name == null && nextClass.equals(Object.class) == false); + + if (name == null) { + if (value instanceof IBaseResource) { + name = myContext.getResourceDefinition((Class) value).getName(); + } else if (value instanceof IDatatype) { + name = value.getClass().getSimpleName(); + name = name.substring(0, name.length() - 2); + } else if (value instanceof IBaseDatatype) { + name = value.getClass().getSimpleName(); + if (name.endsWith("Type")) { + name = name.substring(0, name.length() - 4); } + } 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) { ourLog.debug("No narrative template available for type: {}", value.getClass()); 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); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/BaseParser.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/BaseParser.java index 3c764c9d313..801f061dd68 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/BaseParser.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/BaseParser.java @@ -305,24 +305,20 @@ public abstract class BaseParser implements IParser { } } 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) { @@ -1112,9 +1108,8 @@ public abstract class BaseParser implements IParser { } if (theElements.contains(thePathBuilder.toString())) { return true; - } else { - return false; } + return false; } else if (myParent != null) { boolean parentCheck; if (theCheckingForWhitelist) { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/JsonParser.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/JsonParser.java index 782907c977d..792bb597db6 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/JsonParser.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/JsonParser.java @@ -25,37 +25,74 @@ import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isNotBlank; import java.io.IOException; -import java.io.PushbackReader; import java.io.Reader; import java.io.Writer; import java.math.BigDecimal; -import java.util.*; -import java.util.Map.Entry; +import java.util.ArrayList; +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.Validate; 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.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.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.base.composite.BaseCodingDt; 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.parser.json.GsonStructure; import ca.uhn.fhir.parser.json.JsonLikeArray; import ca.uhn.fhir.parser.json.JsonLikeObject; import ca.uhn.fhir.parser.json.JsonLikeStructure; import ca.uhn.fhir.parser.json.JsonLikeValue; -import ca.uhn.fhir.parser.json.JsonLikeWriter; import ca.uhn.fhir.parser.json.JsonLikeValue.ScalarType; 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.util.ElementUtil; @@ -110,9 +147,8 @@ public class JsonParser extends BaseParser implements IJsonLikeParser { } theListToAddTo.get(valueIdx).addAll(theCommentsToAdd); return true; - } else { - return false; } + return false; } private boolean addToHeldExtensions(int valueIdx, List> ext, ArrayList> 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)); } return true; - } else { - return false; } + return false; } private void addToHeldIds(int theValueIdx, ArrayList 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) { // 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) { // throw new DataFormatException("Invalid content of element " + thePosition + ", expected " + theValueType); // } - } +// } private void beginArray(JsonLikeWriter theEventWriter, String arrayName) throws IOException { theEventWriter.beginArray(arrayName); @@ -281,6 +316,7 @@ public class JsonParser extends BaseParser implements IJsonLikeParser { writeTagWithTextNode(theEventWriter, "deleted", nextEntry.getDeletedAt()); } writeTagWithTextNode(theEventWriter, "title", nextEntry.getTitle()); + //TODO: Use of a deprecated method should be resolved. writeTagWithTextNode(theEventWriter, "id", nextEntry.getId()); linkStarted = false; @@ -291,6 +327,7 @@ public class JsonParser extends BaseParser implements IJsonLikeParser { theEventWriter.endArray(); } + //TODO: Use of a deprecated method should be resolved. writeOptionalTagWithTextNode(theEventWriter, "updated", nextEntry.getUpdated()); writeOptionalTagWithTextNode(theEventWriter, "published", nextEntry.getPublished()); @@ -575,7 +612,7 @@ public class JsonParser extends BaseParser implements IJsonLikeParser { } if (narr != null && narr.isEmpty()) { gen.generateNarrative(myContext, theResource, narr); - if (narr != null && !narr.isEmpty()) { + if (!narr.isEmpty()) { RuntimeChildNarrativeDefinition child = (RuntimeChildNarrativeDefinition) nextChild; String childName = nextChild.getChildNameByDatatype(child.getDatatype()); BaseRuntimeElementDefinition type = child.getChildByName(childName); @@ -980,7 +1017,7 @@ public class JsonParser extends BaseParser implements IJsonLikeParser { for (RuntimeChildDeclaredExtensionDefinition nextDef : resDef.getExtensionsNonModifier()) { for (IBase nextValue : nextDef.getAccessor().getValues(theResource)) { if (nextValue != null) { - if (nextValue == null || nextValue.isEmpty()) { + if (nextValue.isEmpty()) { continue; } extensions.add(new HeldExtension(nextDef, nextValue, theChildElem)); @@ -990,7 +1027,7 @@ public class JsonParser extends BaseParser implements IJsonLikeParser { for (RuntimeChildDeclaredExtensionDefinition nextDef : resDef.getExtensionsModifier()) { for (IBase nextValue : nextDef.getAccessor().getValues(theResource)) { if (nextValue != null) { - if (nextValue == null || nextValue.isEmpty()) { + if (nextValue.isEmpty()) { continue; } modifierExtensions.add(new HeldExtension(nextDef, nextValue, theChildElem)); @@ -1106,7 +1143,7 @@ public class JsonParser extends BaseParser implements IJsonLikeParser { } JsonLikeValue alternateVal = theAlternateVal; - if (alternateVal != null && alternateVal.isObject() == false) { + if (alternateVal.isObject() == false) { getErrorHandler().incorrectJsonType(null, theAlternateName, ValueType.OBJECT, null, alternateVal.getJsonType(), null); return; } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/ParserState.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/ParserState.java index 9750f68f511..02a26311d39 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/ParserState.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/ParserState.java @@ -142,6 +142,7 @@ class ParserState { if (entry.getLinkSelf() != null && entry.getLinkSelf().isEmpty() == false) { id = new IdDt(entry.getLinkSelf().getValue()); } else { + //TODO: Use of a deprecated method should be resolved. id = entry.getId(); } @@ -159,6 +160,7 @@ class ParserState { if (resource != null) { resource.getResourceMetadata().put(ResourceMetadataKeyEnum.DELETED_AT, entry.getDeletedAt()); + //TODO: Use of a deprecated method should be resolved. resource.getResourceMetadata().put(ResourceMetadataKeyEnum.VERSION_ID, id); } } @@ -364,6 +366,7 @@ class ParserState { @Override public void attributeValue(String theName, String theValue) throws DataFormatException { if ("ref".equals(theName)) { + //TODO: Use of a deprecated method should be resolved. getEntry().setId(new IdDt(theValue)); } else if ("when".equals(theName)) { getEntry().setDeleted(new InstantDt(theValue)); @@ -451,10 +454,12 @@ class ParserState { if ("title".equals(theLocalPart)) { push(new AtomPrimitiveState(myEntry.getTitle())); } else if ("id".equals(theLocalPart)) { + //TODO: Use of a deprecated method should be resolved. push(new AtomPrimitiveState(myEntry.getId())); } else if ("link".equals(theLocalPart)) { push(new AtomLinkState(myEntry)); } else if ("updated".equals(theLocalPart)) { + //TODO: Use of a deprecated method should be resolved. push(new AtomPrimitiveState(myEntry.getUpdated())); } else if ("published".equals(theLocalPart)) { push(new AtomPrimitiveState(myEntry.getPublished())); @@ -771,7 +776,7 @@ class ParserState { myErrorHandler.unknownAttribute(null, theName); } - public boolean elementIsRepeating(@SuppressWarnings("unused") String theChildName) { + public boolean elementIsRepeating(String theChildName) { return false; } @@ -790,7 +795,6 @@ class ParserState { /** * Default implementation just handles undeclared extensions */ - @SuppressWarnings("unused") public void enteringNewElementExtension(StartElement theElement, String theUrlAttr, boolean theIsModifier) { if (myPreResourceState != null && getCurrentElement() instanceof ISupportsUndeclaredExtensions) { ExtensionDt newExtension = new ExtensionDt(theIsModifier); @@ -1031,6 +1035,7 @@ class ParserState { @Override public void enteringNewElement(String theNamespaceUri, String theLocalPart) throws DataFormatException { if ("base".equals(theLocalPart)) { + //TODO: Use of a deprecated method should be resolved. push(new PrimitiveState(getPreResourceState(), myEntry.getLinkBase())); } else if ("request".equals(theLocalPart)) { push(new BundleEntryTransactionState(myEntry)); @@ -1302,6 +1307,7 @@ class ParserState { } String bundleBaseUrl = myInstance.getLinkBase().getValue(); + //TODO: Use of a deprecated method should be resolved. String entryBaseUrl = nextEntry.getLinkBase().getValue(); String version = ResourceMetadataKeyEnum.VERSION.get(nextResource); String resourceName = myContext.getResourceDefinition(nextResource).getName(); @@ -2030,9 +2036,8 @@ class ParserState { private PreResourceState getRootPreResourceState() { if (getPreResourceState() != null) { return getPreResourceState(); - } else { - return this; } + return this; } @Override @@ -2590,8 +2595,7 @@ class ParserState { public void attributeValue(String theName, String theValue) throws DataFormatException { if (myJsonMode) { myDt.setValueAsString(theValue); - return; - } else { + } else { // IGNORE - don't handle this as an error, we process these as XML events } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/XmlParser.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/XmlParser.java index 19f402c0125..516e53cb6cb 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/XmlParser.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/parser/XmlParser.java @@ -45,17 +45,14 @@ import javax.xml.stream.events.Namespace; import javax.xml.stream.events.StartElement; import javax.xml.stream.events.XMLEvent; -import ca.uhn.fhir.model.api.BaseBundle; import org.apache.commons.lang3.StringUtils; import org.hl7.fhir.instance.model.api.IAnyResource; import org.hl7.fhir.instance.model.api.IBase; import org.hl7.fhir.instance.model.api.IBaseBinary; 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.IBaseHasExtensions; 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.IBaseXhtml; 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.BaseRuntimeDeclaredChildDefinition; -import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition; import ca.uhn.fhir.context.BaseRuntimeElementDefinition; 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.RuntimeChildExtension; 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.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 * {@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 FHIR_NS = "http://hl7.org/fhir"; @@ -149,10 +145,9 @@ public class XmlParser extends BaseParser implements IParser { if (myPrettyPrint) { PrettyPrintWriterWrapper retVal = new PrettyPrintWriterWrapper(eventWriter); return retVal; - } else { - NonPrettyPrintWriterWrapper retVal = new NonPrettyPrintWriterWrapper(eventWriter); - return retVal; } + NonPrettyPrintWriterWrapper retVal = new NonPrettyPrintWriterWrapper(eventWriter); + return retVal; } @Override @@ -330,6 +325,7 @@ public class XmlParser extends BaseParser implements IParser { eventWriter.writeNamespace("at", TOMBSTONES_NS); if (nextEntry.getDeletedResourceId().isEmpty()) { + //TODO: Use of a deprecated method should be resolved. writeOptionalAttribute(eventWriter, "ref", nextEntry.getId().getValueAsString()); } else { writeOptionalAttribute(eventWriter, "ref", nextEntry.getDeletedResourceId().getValueAsString()); @@ -361,12 +357,15 @@ public class XmlParser extends BaseParser implements IParser { writeOptionalTagWithTextNode(eventWriter, "title", nextEntry.getTitle()); if (!deleted) { + //TODO: Use of a deprecated method should be resolved. if (nextEntry.getId().isEmpty() == false) { + //TODO: Use of a deprecated method should be resolved. writeTagWithTextNode(eventWriter, "id", nextEntry.getId()); } else { writeTagWithTextNode(eventWriter, "id", nextEntry.getResource().getId()); } } + //TODO: Use of a deprecated method should be resolved. writeOptionalTagWithTextNode(eventWriter, "updated", nextEntry.getUpdated()); writeOptionalTagWithTextNode(eventWriter, "published", nextEntry.getPublished()); @@ -420,6 +419,7 @@ public class XmlParser extends BaseParser implements IParser { IdDt bundleId = theBundle.getId(); if (bundleId != null && isNotBlank(bundleId.getVersionIdPart()) || (updated != null && !updated.isEmpty())) { theEventWriter.writeStartElement("meta"); + //FIXME potential null acces bundleId may be null at this time due to the OR clause writeOptionalTagWithValue(theEventWriter, "versionId", bundleId.getVersionIdPart()); if (updated != null) { writeOptionalTagWithValue(theEventWriter, "lastUpdated", updated.getValueAsString()); @@ -476,8 +476,11 @@ public class XmlParser extends BaseParser implements IParser { if (deleted) { theEventWriter.writeStartElement("deleted"); + //TODO: Use of a deprecated method should be resolved. writeOptionalTagWithValue(theEventWriter, "type", nextEntry.getId().getResourceType()); + //TODO: Use of a deprecated method should be resolved. writeOptionalTagWithValue(theEventWriter, "id", nextEntry.getId().getIdPart()); + //TODO: Use of a deprecated method should be resolved. writeOptionalTagWithValue(theEventWriter, "versionId", nextEntry.getId().getVersionIdPart()); writeOptionalTagWithValue(theEventWriter, "instant", nextEntry.getDeletedAt().getValueAsString()); theEventWriter.writeEndElement(); @@ -504,18 +507,16 @@ public class XmlParser extends BaseParser implements IParser { switch (childDef.getChildType()) { case ID_DATATYPE: { - IIdType value = (IIdType) theElement; + IIdType value = IIdType.class.cast(theElement); String encodedValue = "id".equals(childName) ? value.getIdPart() : value.getValue(); - if (value != null) { - theEventWriter.writeStartElement(childName); - theEventWriter.writeAttribute("value", encodedValue); - encodeExtensionsIfPresent(theResource, theEventWriter, theElement, theIncludedResource); - theEventWriter.writeEndElement(); - } + theEventWriter.writeStartElement(childName); + theEventWriter.writeAttribute("value", encodedValue); + encodeExtensionsIfPresent(theResource, theEventWriter, theElement, theIncludedResource); + theEventWriter.writeEndElement(); break; } case PRIMITIVE_DATATYPE: { - IPrimitiveType pd = (IPrimitiveType) theElement; + IPrimitiveType pd = IPrimitiveType.class.cast(theElement); String value = pd.getValueAsString(); if (value != null || super.hasExtensions(pd)) { theEventWriter.writeStartElement(childName); @@ -568,23 +569,21 @@ public class XmlParser extends BaseParser implements IParser { break; } case PRIMITIVE_XHTML: { - XhtmlDt dt = (XhtmlDt) theElement; + XhtmlDt dt = XhtmlDt.class.cast(theElement); if (dt.hasContent()) { encodeXhtml(dt, theEventWriter); } break; } case PRIMITIVE_XHTML_HL7ORG: { - IBaseXhtml dt = (IBaseXhtml) theElement; - if (dt.isEmpty()) { - break; - } else { + IBaseXhtml dt = IBaseXhtml.class.cast(theElement); + if (!dt.isEmpty()) { // TODO: this is probably not as efficient as it could be XhtmlDt hdt = new XhtmlDt(); hdt.setValueAsString(dt.getValueAsString()); encodeXhtml(hdt, theEventWriter); - break; } + break; } case EXTENSION_DECLARED: case UNDECL_EXT: { @@ -621,6 +620,7 @@ public class XmlParser extends BaseParser implements IParser { } else { narr = null; } + //FIXME potential null access on narr see line 623 if (gen != null && narr.isEmpty()) { gen.generateNarrative(myContext, theResource, narr); } @@ -914,9 +914,8 @@ public class XmlParser extends BaseParser implements IParser { childDef = myContext.getElementDefinition(value.getClass()); if (childDef == null) { throw new ConfigurationException("Unable to encode extension, unrecognized child element type: " + value.getClass().getCanonicalName()); - } else { - childName = RuntimeChildUndeclaredExtensionDefinition.createExtensionChildName(childDef); - } + } + childName = RuntimeChildUndeclaredExtensionDefinition.createExtensionChildName(childDef); } else { childDef = extDef.getChildElementDefinitionByDatatype(value.getClass()); if (childDef == null) { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Delete.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Delete.java index 58eb2fe01b9..59caaab86ab 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Delete.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/annotation/Delete.java @@ -27,8 +27,6 @@ import java.lang.annotation.Target; import org.hl7.fhir.instance.model.api.IBaseResource; -import ca.uhn.fhir.model.api.IResource; - /** * RESTful method annotation to be used for the FHIR * delete method. diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/BaseClient.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/BaseClient.java index 0cb93da1a37..9def56fb5cd 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/BaseClient.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/BaseClient.java @@ -323,6 +323,7 @@ public abstract class BaseClient implements IRestfulClient { } } catch (DataFormatException e) { + //FIXME potential null access on httpResquest String msg = getFhirContext().getLocalizer().getMessage(BaseClient.class, "failedToParseResponse", httpRequest.getHttpVerbName(), httpRequest.getUri(), e.toString()); throw new FhirClientConnectionException(msg, e); } catch (IllegalStateException e) { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/GenericClient.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/GenericClient.java index 511ff147aad..67251bdbd0a 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/GenericClient.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/GenericClient.java @@ -87,6 +87,7 @@ public class GenericClient extends BaseClient implements IGenericClient { myContext = theContext; } + @Deprecated //override deprecated method @Override public IBaseConformance conformance() { if (myContext.getVersion().getVersion().isRi()) { @@ -111,6 +112,7 @@ public class GenericClient extends BaseClient implements IGenericClient { return new CreateInternal(); } + @Deprecated //overide deprecated method @Override public MethodOutcome create(IBaseResource theResource) { BaseHttpClientInvocation invocation = MethodUtil.createCreateInvocation(theResource, myContext); @@ -133,6 +135,7 @@ public class GenericClient extends BaseClient implements IGenericClient { return new DeleteInternal(); } + @Deprecated //override deprecated method @Override public MethodOutcome delete(final Class theType, IdDt theId) { HttpDeleteClientInvocation invocation = DeleteMethodBinding.createDeleteInvocation(getFhirContext(), theId.withResourceType(toResourceName(theType))); @@ -146,6 +149,7 @@ public class GenericClient extends BaseClient implements IGenericClient { return resp; } + @Deprecated //override deprecated method @Override public MethodOutcome delete(Class theType, String theId) { return delete(theType, new IdDt(theId)); @@ -186,12 +190,11 @@ public class GenericClient extends BaseClient implements IGenericClient { if (theNotModifiedHandler == null) { return invokeClient(myContext, binding, invocation, theEncoding, thePrettyPrint, myLogRequestAndResponse, theSummary, theSubsetElements); - } else { - try { - return invokeClient(myContext, binding, invocation, theEncoding, thePrettyPrint, myLogRequestAndResponse, theSummary, theSubsetElements); - } catch (NotModifiedException e) { - return theNotModifiedHandler.call(); - } + } + try { + return invokeClient(myContext, binding, invocation, theEncoding, thePrettyPrint, myLogRequestAndResponse, theSummary, theSubsetElements); + } catch (NotModifiedException e) { + return theNotModifiedHandler.call(); } } @@ -245,6 +248,7 @@ public class GenericClient extends BaseClient implements IGenericClient { return new HistoryInternal(); } + @Deprecated //override deprecated method @Override public Bundle history(final Class theType, IdDt theIdDt, DateTimeDt theSince, Integer theLimit) { String resourceName = theType != null ? toResourceName(theType) : null; @@ -260,6 +264,7 @@ public class GenericClient extends BaseClient implements IGenericClient { } + @Deprecated //override deprecated method @Override public Bundle history(Class theType, String theId, DateTimeDt theSince, Integer theLimit) { return history(theType, new IdDt(theId), theSince, theLimit); @@ -409,6 +414,7 @@ public class GenericClient extends BaseClient implements IGenericClient { myLastRequest = theLastRequest; } + @Deprecated //override deprecated method @Override public void setLogRequestAndResponse(boolean theLogRequestAndResponse) { myLogRequestAndResponse = theLogRequestAndResponse; @@ -423,6 +429,7 @@ public class GenericClient extends BaseClient implements IGenericClient { return new TransactionInternal(); } + @Deprecated //override deprecated method @Override public List transaction(List theResources) { BaseHttpClientInvocation invocation = TransactionMethodBinding.createTransactionInvocation(theResources, myContext); @@ -569,6 +576,7 @@ public class GenericClient extends BaseClient implements IGenericClient { protected SummaryEnum mySummaryMode; + @Deprecated //override deprecated method @SuppressWarnings("unchecked") @Override public T andLogRequestAndResponse(boolean theLogRequestAndResponse) { @@ -612,9 +620,8 @@ public class GenericClient extends BaseClient implements IGenericClient { public List> getPreferResponseTypes(Class theDefault) { if (myPreferResponseTypes != null) { return myPreferResponseTypes; - } else { - return toTypeList(theDefault); } + return toTypeList(theDefault); } protected HashSet getSubsetElements() { @@ -1207,6 +1214,7 @@ public class GenericClient extends BaseClient implements IGenericClient { return nextOrPrevious(PREVIOUS, theBundle); } + @Deprecated //override deprecated method @Override public IGetPageTyped url(String thePageUrl) { return new GetPageInternal(thePageUrl); @@ -1446,29 +1454,27 @@ public class GenericClient extends BaseClient implements IGenericClient { handler = new ResourceResponseHandler(myReturnResourceType); Object retVal = invoke(null, handler, invocation); 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 @@ -1591,10 +1597,10 @@ public class GenericClient extends BaseClient implements IGenericClient { private final class OutcomeResponseHandler implements IClientResponseHandler { private PreferReturnEnum myPrefer; - private final String myResourceName; +// private final String myResourceName; private OutcomeResponseHandler(String theResourceName) { - myResourceName = theResourceName; +// myResourceName = theResourceName; } private OutcomeResponseHandler(String theResourceName, PreferReturnEnum thePrefer) { @@ -1634,9 +1640,8 @@ public class GenericClient extends BaseClient implements IGenericClient { public Object execute() {// AAA if (myId.hasVersionIdPart()) { 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 @@ -1774,9 +1779,8 @@ public class GenericClient extends BaseClient implements IGenericClient { IVersionSpecificBundleFactory bundleFactory = myContext.newBundleFactory(); bundleFactory.initializeWithBundleResource(response); return bundleFactory.toListOfResources(); - } else { - return new ArrayList(new BundleResponseHandler(myType).invokeClient(theResponseMimeType, theResponseReader, theResponseStatusCode, theHeaders).toListOfResources()); } + return new ArrayList(new BundleResponseHandler(myType).invokeClient(theResponseMimeType, theResponseReader, theResponseStatusCode, theHeaders).toListOfResources()); } } @@ -1850,6 +1854,7 @@ public class GenericClient extends BaseClient implements IGenericClient { return this; } + @Deprecated //override deprecated method @Override public IBase execute() { @@ -1906,8 +1911,11 @@ public class GenericClient extends BaseClient implements IGenericClient { if (rootSs == null) { rootSs = nextSortSpec; } else { + //FIXME lastSs is null never set + //TODO unused assignment lastSs.setChain(nextSortSpec); } + //TODO unused assignment lastSs = nextSortSpec; } if (rootSs != null) { @@ -1983,6 +1991,7 @@ public class GenericClient extends BaseClient implements IGenericClient { return this; } + @Deprecated //override deprecated method @Override public IQuery limitTo(int theLimitTo) { return count(theLimitTo); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/RestfulClientFactory.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/RestfulClientFactory.java index ba3f19c0e64..00f023e3502 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/RestfulClientFactory.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/RestfulClientFactory.java @@ -318,12 +318,13 @@ public abstract class RestfulClientFactory implements IRestfulClientFactory { String serverFhirVersionString = null; Object value = t.getSingleValueOrNull(conformance, "fhirVersion"); if (value instanceof IPrimitiveType) { - serverFhirVersionString = ((IPrimitiveType) value).getValueAsString(); + serverFhirVersionString = IPrimitiveType.class.cast(value).getValueAsString(); } FhirVersionEnum serverFhirVersionEnum = null; if (StringUtils.isBlank(serverFhirVersionString)) { // we'll be lenient and accept this } else { + //FIXME null access on serverFhirVersionString if (serverFhirVersionString.startsWith("0.80") || serverFhirVersionString.startsWith("0.0.8")) { serverFhirVersionEnum = FhirVersionEnum.DSTU1; } else if (serverFhirVersionString.startsWith("0.4")) { @@ -347,11 +348,13 @@ public abstract class RestfulClientFactory implements IRestfulClientFactory { } + @Deprecated //override deprecated method @Override public ServerValidationModeEnum getServerValidationModeEnum() { return getServerValidationMode(); } + @Deprecated //override deprecated method @Override public void setServerValidationModeEnum(ServerValidationModeEnum theServerValidationMode) { setServerValidationMode(theServerValidationMode); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpClient.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpClient.java index 7fb1c8ed98f..be1af48e8b0 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpClient.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpClient.java @@ -30,7 +30,13 @@ import org.apache.http.HttpEntity; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; 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.message.BasicNameValuePair; 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.exceptions.InternalErrorException; 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 diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpRequest.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpRequest.java index 0859096690a..e0023673d2a 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpRequest.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpRequest.java @@ -21,6 +21,7 @@ package ca.uhn.fhir.rest.client.apache; */ import java.io.IOException; +import java.nio.charset.Charset; import java.util.HashMap; import java.util.LinkedList; import java.util.List; @@ -92,7 +93,8 @@ public class ApacheHttpRequest implements IHttpRequest { if (myRequest instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) myRequest).getEntity(); if (entity.isRepeatable()) { - return IOUtils.toString(entity.getContent()); + //TODO verify the charset + return IOUtils.toString(entity.getContent(), Charset.defaultCharset()); } } return null; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpResponse.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpResponse.java index 939afeeaccf..9dc17f33068 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpResponse.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheHttpResponse.java @@ -61,6 +61,7 @@ public class ApacheHttpResponse implements IHttpResponse { this.myResponse = theResponse; } + @Deprecated //override deprecated method @Override public void bufferEntitity() throws IOException { bufferEntity(); @@ -77,6 +78,7 @@ public class ApacheHttpResponse implements IHttpResponse { try { this.myEntityBytes = IOUtils.toByteArray(respEntity); } catch (IllegalStateException e) { + //FIXME resouce leak throw new InternalErrorException(e); } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheRestfulClientFactory.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheRestfulClientFactory.java index b1819788b78..20337994173 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheRestfulClientFactory.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/apache/ApacheRestfulClientFactory.java @@ -73,12 +73,14 @@ public class ApacheRestfulClientFactory extends RestfulClientFactory { public synchronized HttpClient getNativeHttpClient() { if (myHttpClient == null) { + //FIXME potential resoource leak PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(5000, TimeUnit.MILLISECONDS); connectionManager.setMaxTotal(getPoolMaxTotal()); connectionManager.setDefaultMaxPerRoute(getPoolMaxPerRoute()); // @formatter:off + //TODO: Use of a deprecated method should be resolved. RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(getSocketTimeout()) .setConnectTimeout(getConnectTimeout()).setConnectionRequestTimeout(getConnectionRequestTimeout()) .setStaleConnectionCheckEnabled(true).setProxy(myProxy).build(); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/interceptor/LoggingInterceptor.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/interceptor/LoggingInterceptor.java index e844d96cb13..be47354efd3 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/interceptor/LoggingInterceptor.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/client/interceptor/LoggingInterceptor.java @@ -120,6 +120,7 @@ public class LoggingInterceptor implements IClientInterceptor { } if (myLogResponseBody) { + //TODO: Use of a deprecated method should be resolved. theResponse.bufferEntitity(); InputStream respEntity = null; try { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/DateClientParam.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/DateClientParam.java index 53e08a67891..156cdee4672 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/DateClientParam.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/DateClientParam.java @@ -27,7 +27,6 @@ import java.util.Date; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.model.api.TemporalPrecisionEnum; import ca.uhn.fhir.model.primitive.DateTimeDt; -import ca.uhn.fhir.rest.gclient.DateClientParam.IDateSpecifier; import ca.uhn.fhir.rest.param.ParamPrefixEnum; /** diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/StringCriterion.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/StringCriterion.java index 1085092bd8c..d22a2b29a0b 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/StringCriterion.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/gclient/StringCriterion.java @@ -3,7 +3,6 @@ package ca.uhn.fhir.rest.gclient; import static org.apache.commons.lang3.StringUtils.isBlank; import java.util.Collection; -import java.util.List; import org.apache.commons.lang3.StringUtils; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseBinder.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseBinder.java index c56ecce41c8..b220d8ea997 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseBinder.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseBinder.java @@ -21,7 +21,6 @@ package ca.uhn.fhir.rest.method; */ import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; import java.util.List; import ca.uhn.fhir.context.ConfigurationException; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseHttpClientInvocationWithContents.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseHttpClientInvocationWithContents.java index b0e80a30c94..659866775e5 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseHttpClientInvocationWithContents.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseHttpClientInvocationWithContents.java @@ -200,12 +200,11 @@ abstract class BaseHttpClientInvocationWithContents extends BaseHttpClientInvoca if (myParams != null) { 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) { @@ -253,10 +252,9 @@ abstract class BaseHttpClientInvocationWithContents extends BaseHttpClientInvoca Bundle bundle = bundleFactory.getDstu1Bundle(); if (bundle != null) { 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) { return myContents; } else { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseMethodBinding.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseMethodBinding.java index 12111548400..04983df24c7 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseMethodBinding.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseMethodBinding.java @@ -259,9 +259,8 @@ public abstract class BaseMethodBinding implements IClientResponseHandler } catch (InvocationTargetException e) { if (e.getCause() instanceof BaseServerResponseException) { 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) { throw new InternalErrorException("Failed to call access method", e); } @@ -455,6 +454,7 @@ public abstract class BaseMethodBinding implements IClientResponseHandler if (returnTypeFromRp != null) { if (returnTypeFromAnnotation != null && !isResourceInterface(returnTypeFromAnnotation)) { if (!returnTypeFromRp.isAssignableFrom(returnTypeFromAnnotation)) { + //FIXME potential null access on retunrTypeFromMethod 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"); } @@ -492,9 +492,8 @@ public abstract class BaseMethodBinding implements IClientResponseHandler if (search.dynamic()) { IDynamicSearchResourceProvider provider = (IDynamicSearchResourceProvider) theProvider; 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) { return new ConformanceMethodBinding(theMethod, theContext, theProvider); } else if (create != null) { @@ -510,9 +509,8 @@ public abstract class BaseMethodBinding implements IClientResponseHandler } else if (validate != null) { if (theContext.getVersion().getVersion() == FhirVersionEnum.DSTU1) { 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) { return new GetTagsMethodBinding(theMethod, theContext, theProvider, getTags); } else if (addTags != null) { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseOutcomeReturningMethodBinding.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseOutcomeReturningMethodBinding.java index e007da44676..a63ec352a63 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseOutcomeReturningMethodBinding.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/BaseOutcomeReturningMethodBinding.java @@ -101,16 +101,14 @@ abstract class BaseOutcomeReturningMethodBinding extends BaseMethodBinding list = dstu1bundle.toListOfResources(); if (list.size() == 0) { 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(), isAddContentLocationHeader()); - } else { - // Is this request coming from a browser - String uaHeader = theRequest.getHeader("user-agent"); - boolean requestIsBrowser = false; - if (uaHeader != null && uaHeader.contains("Mozilla")) { - 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); + } + // Is this request coming from a browser + String uaHeader = theRequest.getHeader("user-agent"); + boolean requestIsBrowser = false; + if (uaHeader != null && uaHeader.contains("Mozilla")) { + 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); } 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); responseObject = new ResourceOrDstu1Bundle(resource); - break; - } else { Set includes = getRequestIncludesFromParams(params); @@ -394,9 +392,8 @@ public abstract class BaseResourceReturningMethodBinding extends BaseMethodBindi IBaseResource resBundle = bundleFactory.getResourceBundle(); responseObject = new ResourceOrDstu1Bundle(resBundle); } - - break; } + break; } case RESOURCE: { IBundleProvider result = (IBundleProvider) resultObj; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ConditionalParamBinder.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ConditionalParamBinder.java index 91f1940505a..a989ff419b0 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ConditionalParamBinder.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ConditionalParamBinder.java @@ -1,32 +1,10 @@ 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.util.Collection; import java.util.List; import java.util.Map; -import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; 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.rest.annotation.ConditionalUrlParam; 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.InvalidRequestException; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ConformanceMethodBinding.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ConformanceMethodBinding.java index 48169362690..709fef4e3c9 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ConformanceMethodBinding.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ConformanceMethodBinding.java @@ -93,9 +93,8 @@ public class ConformanceMethodBinding extends BaseResourceReturningMethodBinding if ("metadata".equals(theRequest.getOperation())) { if (theRequest.getRequestType() == RequestTypeEnum.GET) { 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; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/DynamicSearchMethodBinding.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/DynamicSearchMethodBinding.java index 3aa901a4798..1a01636467b 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/DynamicSearchMethodBinding.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/DynamicSearchMethodBinding.java @@ -86,7 +86,7 @@ public class DynamicSearchMethodBinding extends BaseResourceReturningMethodBindi } @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) { theMethodParams[myIdParamIndex] = theRequest.getId(); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ElementsParameter.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ElementsParameter.java index 9e0c61c737b..44483bc79a9 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ElementsParameter.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ElementsParameter.java @@ -113,9 +113,8 @@ public class ElementsParameter implements IParameter { retVal.add("meta"); return retVal; - } else { - return null; } + return null; } @Override diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/FhirPrimitiveBinder.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/FhirPrimitiveBinder.java index 8a6600e8b62..92d9d94dfdf 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/FhirPrimitiveBinder.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/FhirPrimitiveBinder.java @@ -1,27 +1,5 @@ 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 ca.uhn.fhir.util.ReflectionUtil; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/GetTagsMethodBinding.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/GetTagsMethodBinding.java index 026b0babe55..9bea10da060 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/GetTagsMethodBinding.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/GetTagsMethodBinding.java @@ -156,12 +156,9 @@ public class GetTagsMethodBinding extends BaseMethodBinding { IParser parser = createAppropriateParserForParsingResponse(theResponseMimeType, theResponseReader, theResponseStatusCode, null); TagList retVal = parser.parseTagList(theResponseReader); return retVal; - } else { - throw processNon2xxResponseAndReturnExceptionToThrow(theResponseStatusCode, theResponseMimeType, theResponseReader); } - + throw processNon2xxResponseAndReturnExceptionToThrow(theResponseStatusCode, theResponseMimeType, theResponseReader); } - @Override public Object invokeServer(IRestfulServer theServer, RequestDetails theRequest) throws BaseServerResponseException, IOException { Object[] params = createParametersForServerRequest(theRequest); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/HistoryMethodBinding.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/HistoryMethodBinding.java index decb2c1a88d..dae8c9d3dfb 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/HistoryMethodBinding.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/HistoryMethodBinding.java @@ -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))"); } 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); if (versionId == null || versionId.isEmpty()) { throw new InternalErrorException("Server provided resource at index " + index + " with no Version ID set (using IResource#setId(IdDt))"); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/IncludeParameter.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/IncludeParameter.java index 90e86b934f2..64123323625 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/IncludeParameter.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/IncludeParameter.java @@ -149,12 +149,11 @@ class IncludeParameter extends BaseQueryParameter { if (myInstantiableCollectionType == null) { if (mySpecType == String.class) { return value; - } else { - return new Include(value, recurse); } - } else { - retValCollection.add(new Include(value, recurse)); + return new Include(value, recurse); } + //FIXME null access + retValCollection.add(new Include(value, recurse)); } return retValCollection; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/MethodUtil.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/MethodUtil.java index 0a1ec69dbfd..5ee93f41ebe 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/MethodUtil.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/MethodUtil.java @@ -482,9 +482,8 @@ public class MethodUtil { OperationParameter.throwInvalidMode(theObject.toString()); } return retVal; - } else { - return null; } + return null; } @Override @@ -671,6 +670,7 @@ public class MethodUtil { break; } + //FIXME null access return binder.parse(theContext, theUnqualifiedParamName, theParameters); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/OperationMethodBinding.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/OperationMethodBinding.java index df89dcdb5bd..b4024c77d03 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/OperationMethodBinding.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/OperationMethodBinding.java @@ -281,10 +281,9 @@ public class OperationMethodBinding extends BaseResourceReturningMethodBinding { if (!myIdempotent) { String message = getContext().getLocalizer().getMessage(OperationMethodBinding.class, "methodNotSupported", theRequest.getRequestType(), RequestTypeEnum.POST.name()); 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) { @@ -341,34 +340,33 @@ public class OperationMethodBinding extends BaseResourceReturningMethodBinding { if (!theUseHttpGet) { return new HttpPostClientInvocation(theContext, theInput, b.toString()); - } else { - FhirTerser t = theContext.newTerser(); - List parameters = t.getValues(theInput, "Parameters.parameter"); - - Map> params = new LinkedHashMap>(); - 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()); - } - - 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 parameters = t.getValues(theInput, "Parameters.parameter"); + + Map> params = new LinkedHashMap>(); + 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()); + } + + 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 { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/OperationParameter.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/OperationParameter.java index d179fb45f13..a5d2162de53 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/OperationParameter.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/OperationParameter.java @@ -136,9 +136,8 @@ public class OperationParameter implements IParameter { public String getSearchParamType() { if (mySearchParameterBinding != null) { return mySearchParameterBinding.getParamType().getCode(); - } else { - return null; } + return null; } @SuppressWarnings("unchecked") @@ -326,7 +325,7 @@ public class OperationParameter implements IParameter { } else { for (String nextValue : paramValues) { FhirContext ctx = theRequest.getServer().getFhirContext(); - RuntimePrimitiveDatatypeDefinition def = (RuntimePrimitiveDatatypeDefinition) ctx.getElementDefinition((Class) myParameterType); + RuntimePrimitiveDatatypeDefinition def = (RuntimePrimitiveDatatypeDefinition) ctx.getElementDefinition(myParameterType.asSubclass(IBase.class)); IPrimitiveType instance = def.newInstance(); instance.setValueAsString(nextValue); matchingParamValues.add(instance); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/PageMethodBinding.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/PageMethodBinding.java index 40e15970d25..c5b449e4d34 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/PageMethodBinding.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/PageMethodBinding.java @@ -81,9 +81,8 @@ public class PageMethodBinding extends BaseResourceReturningMethodBinding { IBase bundle = handlePagingRequest(theServer, theRequest, theRequest.getParameters().get(Constants.PARAM_PAGINGACTION)[0]); if (bundle instanceof 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) { @@ -144,9 +143,8 @@ public class PageMethodBinding extends BaseResourceReturningMethodBinding { Bundle bundle = bundleFactory.getDstu1Bundle(); if (bundle != null) { return bundle; - } else { - return bundleFactory.getResourceBundle(); } + return bundleFactory.getResourceBundle(); // if (bundle != null) { // for (int i = getInterceptors().size() - 1; i >= 0; i--) { // IServerInterceptor next = getInterceptors().get(i); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ParseAction.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ParseAction.java index 36236eceab1..c820a12f8e8 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ParseAction.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ParseAction.java @@ -23,8 +23,6 @@ package ca.uhn.fhir.rest.method; import java.io.IOException; import java.io.Writer; -import org.hl7.fhir.instance.model.api.IBaseResource; - import ca.uhn.fhir.model.api.TagList; import ca.uhn.fhir.parser.IParser; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/PatchTypeParameter.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/PatchTypeParameter.java index 6aac25b7fc6..89782c42a29 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/PatchTypeParameter.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/PatchTypeParameter.java @@ -34,7 +34,6 @@ import ca.uhn.fhir.rest.api.PatchTypeEnum; import ca.uhn.fhir.rest.server.Constants; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; -import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; class PatchTypeParameter implements IParameter { @Override diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/QualifiedParamList.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/QualifiedParamList.java index 0cea1a13b55..61ec7d7c43e 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/QualifiedParamList.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/QualifiedParamList.java @@ -120,9 +120,8 @@ public class QualifiedParamList extends ArrayList { char nextChar = theString.charAt(i); if (nextChar != '\\') { break; - } else { - retVal++; } + retVal++; } return retVal; } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ReadMethodBinding.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ReadMethodBinding.java index d88f573ea70..abe7fd75105 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ReadMethodBinding.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/ReadMethodBinding.java @@ -99,9 +99,8 @@ public class ReadMethodBinding extends BaseResourceReturningMethodBinding implem public RestOperationTypeEnum getRestOperationType(RequestDetails theRequestDetails) { if (mySupportsVersion && theRequestDetails.getId().hasVersionIdPart()) { return RestOperationTypeEnum.VREAD; - } else { - return RestOperationTypeEnum.READ; } + return RestOperationTypeEnum.READ; } @Override diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/RequestOperationCallbackParameter.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/RequestOperationCallbackParameter.java index 047123dc366..1e9ba5e8f7c 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/RequestOperationCallbackParameter.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/RequestOperationCallbackParameter.java @@ -30,11 +30,10 @@ import org.hl7.fhir.instance.model.api.IBaseResource; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; -import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.util.CoverageIgnore; 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 @Override diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/SearchMethodBinding.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/SearchMethodBinding.java index 3ca67891b3f..97f2d571313 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/SearchMethodBinding.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/SearchMethodBinding.java @@ -225,9 +225,8 @@ public class SearchMethodBinding extends BaseResourceReturningMethodBinding { if (!myQueryName.equals(queryName)) { ourLog.trace("Query name does not match {}", myQueryName); return false; - } else { - methodParamsTemp.add(Constants.PARAM_QUERY); } + methodParamsTemp.add(Constants.PARAM_QUERY); } else { ourLog.trace("Query name does not match {}", myQueryName); return false; @@ -346,9 +345,8 @@ public class SearchMethodBinding extends BaseResourceReturningMethodBinding { if (theId == null || !theId.hasIdPart()) { String msg = theContext.getLocalizer().getMessage(SearchMethodBinding.class.getName() + ".idNullForCompartmentSearch"); throw new InvalidRequestException(msg); - } else { - compartmentSearch = true; } + compartmentSearch = true; } /* diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/SearchParameter.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/SearchParameter.java index 2de5ad8bccc..698d4a2ead7 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/SearchParameter.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/SearchParameter.java @@ -283,8 +283,10 @@ public class SearchParameter extends BaseQueryParameter { this.myRequired = required; } - @SuppressWarnings({ "unchecked", "unused" }) + @SuppressWarnings("unchecked") public void setType(FhirContext theContext, final Class type, Class> theInnerCollectionType, Class> theOuterCollectionType) { + + this.myType = type; if (IQueryParameterType.class.isAssignableFrom(type)) { myParamBinder = new QueryParameterTypeBinder((Class) type, myCompositeTypes); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/SinceOrAtParameter.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/SinceOrAtParameter.java index 1cad5634ac0..c7fbf04daf6 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/SinceOrAtParameter.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/SinceOrAtParameter.java @@ -1,55 +1,17 @@ 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 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 { - private Class myType; - private String myParamName; - private Class myAnnotationType; +// private Class myType; +// private String myParamName; +// private Class myAnnotationType; public SinceOrAtParameter(String theParamName, Class theAnnotationType) { super(theParamName, false); - myParamName = theParamName; - myAnnotationType = theAnnotationType; +// myParamName = theParamName; +// myAnnotationType = theAnnotationType; } @Override diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/TransactionMethodBinding.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/TransactionMethodBinding.java index e82561dcc16..f9d2fc57a81 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/TransactionMethodBinding.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/TransactionMethodBinding.java @@ -112,16 +112,15 @@ public class TransactionMethodBinding extends BaseResourceReturningMethodBinding if (theArgs[myTransactionParamIndex] instanceof Bundle) { Bundle bundle = (Bundle) theArgs[myTransactionParamIndex]; return createTransactionInvocation(bundle, context); - } else { - @SuppressWarnings("unchecked") - List resources = (List) theArgs[myTransactionParamIndex]; - return createTransactionInvocation(resources, context); } + @SuppressWarnings("unchecked") + List resources = (List) theArgs[myTransactionParamIndex]; + return createTransactionInvocation(resources, context); } @SuppressWarnings("unchecked") @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 diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/UpdateMethodBinding.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/UpdateMethodBinding.java index ae6c2da85ed..c7e7df4d787 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/UpdateMethodBinding.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/method/UpdateMethodBinding.java @@ -30,7 +30,6 @@ import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.context.FhirVersionEnum; import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.rest.annotation.Update; @@ -150,11 +149,10 @@ public class UpdateMethodBinding extends BaseOutcomeReturningMethodBindingWithRe if (isBlank(theResourceId)) { String msg = getContext().getLocalizer().getMessage(BaseOutcomeReturningMethodBindingWithResourceParam.class, "noIdInBodyForUpdate"); throw new InvalidRequestException(msg); - } else { - if (!theResourceId.equals(theUrlId)) { - String msg = getContext().getLocalizer().getMessage(BaseOutcomeReturningMethodBindingWithResourceParam.class, "incorrectIdForUpdate", theResourceId, theUrlId); - throw new InvalidRequestException(msg); - } + } + if (!theResourceId.equals(theUrlId)) { + String msg = getContext().getLocalizer().getMessage(BaseOutcomeReturningMethodBindingWithResourceParam.class, "incorrectIdForUpdate", theResourceId, theUrlId); + throw new InvalidRequestException(msg); } } else { theResource.setId((IIdType)null); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/BaseQueryParameter.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/BaseQueryParameter.java index d60480c8f1c..ea1fec5cbe9 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/BaseQueryParameter.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/BaseQueryParameter.java @@ -151,9 +151,8 @@ public abstract class BaseQueryParameter implements IParameter { if (handlesMissing()) { return parse(theRequest.getServer().getFhirContext(), paramList); - } else { - return null; } + return null; } return parse(theRequest.getServer().getFhirContext(), paramList); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/DateParam.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/DateParam.java index 387a539d866..ba863284f64 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/DateParam.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/DateParam.java @@ -32,7 +32,6 @@ import org.hl7.fhir.instance.model.api.IPrimitiveType; import ca.uhn.fhir.context.FhirContext; 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.dstu.valueset.QuantityCompararatorEnum; 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; @SuppressWarnings("deprecation") -public class DateParam extends BaseParamWithPrefix implements IQueryParameterType , IQueryParameterOr { +public class DateParam extends BaseParamWithPrefix implements /*IQueryParameterType , */IQueryParameterOr { private final DateTimeDt myValue = new DateTimeDt(); @@ -220,9 +219,8 @@ public class DateParam extends BaseParamWithPrefix implements IQueryP public String getValueAsString() { if (myValue != null) { return myValue.getValueAsString(); - } else { - return null; } + return null; } /** diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/DateRangeParam.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/DateRangeParam.java index 9af925c56ff..b8003cc9f24 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/DateRangeParam.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/DateRangeParam.java @@ -345,6 +345,7 @@ public class DateRangeParam implements IQueryParameterAnd { public void setRangeFromDatesInclusive(String theLowerBound, String theUpperBound) { myLowerBound = theLowerBound != null ? new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, theLowerBound) : 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)) { myLowerBound.setPrefix(ParamPrefixEnum.EQUAL); myUpperBound.setPrefix(ParamPrefixEnum.EQUAL); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/InternalCodingDt.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/InternalCodingDt.java index 4495b778c99..e11c8e63200 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/InternalCodingDt.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/InternalCodingDt.java @@ -38,6 +38,8 @@ import ca.uhn.fhir.util.CoverageIgnore; @CoverageIgnore public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype { + private static final long serialVersionUID = 993056016725918652L; + /** * 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); } + @Deprecated //override deprecated method @Override public List getAllPopulatedChildElementsOfType(Class theType) { return ca.uhn.fhir.util.ElementUtil.allPopulatedChildElements(theType, mySystem, myVersion, myCode, myDisplay, myPrimary); @@ -90,6 +93,7 @@ public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype * Definition: The identification of the code system that defines the meaning of the symbol in the code. *

*/ + @Override public UriDt getSystemElement() { if (mySystem == null) { mySystem = new UriDt(); @@ -116,6 +120,7 @@ public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype * Definition: The identification of the code system that defines the meaning of the symbol in the code. *

*/ + @Override public InternalCodingDt setSystem(String theUri) { mySystem = new UriDt(theUri); return this; @@ -169,6 +174,7 @@ public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype * Definition: 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) *

*/ + @Override public CodeDt getCodeElement() { if (myCode == null) { myCode = new CodeDt(); @@ -195,6 +201,7 @@ public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype * Definition: 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) *

*/ + @Override public InternalCodingDt setCode(String theCode) { myCode = new CodeDt(theCode); return this; @@ -233,6 +240,7 @@ public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype * Definition: A representation of the meaning of the code in the system, following the rules of the system. *

*/ + @Override public InternalCodingDt setDisplay(String theString) { myDisplay = new StringDt(theString); return this; @@ -292,11 +300,13 @@ public class InternalCodingDt extends BaseCodingDt implements ICompositeDatatype return getDisplay(); } + @Deprecated //override deprecated method @Override public Boolean getMissing() { throw new UnsupportedOperationException(); } + @Deprecated //override deprecated method @Override public IQueryParameterType setMissing(Boolean theMissing) { throw new UnsupportedOperationException(); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParamPrefixEnum.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParamPrefixEnum.java index 82bc481f862..52593680d70 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParamPrefixEnum.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParamPrefixEnum.java @@ -147,9 +147,8 @@ public enum ParamPrefixEnum { public String getValueForContext(FhirContext theContext) { if (theContext.getVersion().getVersion() == FhirVersionEnum.DSTU1) { return getDstu1Value(); - } else { - return getValue(); } + return getValue(); } /** diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParameterUtil.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParameterUtil.java index 1b63cfc9d2e..6dfcc942126 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParameterUtil.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ParameterUtil.java @@ -139,9 +139,8 @@ public class ParameterUtil { public static String escapeWithDefault(Object theValue) { if (theValue == null) { return ""; - } else { - return escape(theValue.toString()); } + return escape(theValue.toString()); } /** diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ReferenceParam.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ReferenceParam.java index 150809c0806..cd29240777e 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ReferenceParam.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ReferenceParam.java @@ -29,11 +29,10 @@ import org.apache.commons.lang3.builder.ToStringStyle; import org.hl7.fhir.instance.model.api.IBaseResource; import ca.uhn.fhir.context.FhirContext; -import ca.uhn.fhir.model.api.IQueryParameterType; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.util.CoverageIgnore; -public class ReferenceParam extends BaseParam implements IQueryParameterType { +public class ReferenceParam extends BaseParam /*implements IQueryParameterType*/ { private String myChain; @@ -93,9 +92,8 @@ public class ReferenceParam extends BaseParam implements IQueryParameterType { String doGetValueAsQueryToken(FhirContext theContext) { if (isBlank(myId.getResourceType())) { return myId.getValue(); // e.g. urn:asdjd or 123 or cid:wieiuru or #1 - } else { - return myId.getIdPart(); } + return myId.getIdPart(); } @Override diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ResourceParameter.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ResourceParameter.java index be68f9a766a..7ab06b5f59e 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ResourceParameter.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/ResourceParameter.java @@ -150,6 +150,7 @@ public class ResourceParameter implements IParameter { String ctValue = theRequest.getHeader(Constants.HEADER_CONTENT_TYPE); if (ctValue != null) { 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()); throw new InvalidRequestException(msg); } @@ -169,9 +170,8 @@ public class ResourceParameter implements IParameter { if (encoding == null) { String msg = ctx.getLocalizer().getMessage(ResourceParameter.class, "noContentTypeInRequest", restOperationType); throw new InvalidRequestException(msg); - } else { - requestReader = new InputStreamReader(new ByteArrayInputStream(theRequest.loadRequestContents()), charset); } + requestReader = new InputStreamReader(new ByteArrayInputStream(theRequest.loadRequestContents()), charset); } else { String msg = ctx.getLocalizer().getMessage(ResourceParameter.class, "invalidContentTypeInRequest", ctValue, restOperationType); throw new InvalidRequestException(msg); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/TokenParam.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/TokenParam.java index 5ddf6d101dc..0298c6bf7d4 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/TokenParam.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/TokenParam.java @@ -27,12 +27,11 @@ import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; 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.BaseIdentifierDt; 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 String mySystem; @@ -86,9 +85,8 @@ public class TokenParam extends BaseParam implements IQueryParameterType { String doGetQueryParameterQualifier() { if (getModifier() != null) { return getModifier().getValue(); - } else { - return null; } + return null; } /** @@ -98,9 +96,8 @@ public class TokenParam extends BaseParam implements IQueryParameterType { String doGetValueAsQueryToken(FhirContext theContext) { if (getSystem() != null) { return ParameterUtil.escape(StringUtils.defaultString(getSystem())) + '|' + ParameterUtil.escape(getValue()); - } else { - return ParameterUtil.escape(getValue()); } + return ParameterUtil.escape(getValue()); } /** diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/TransactionParameter.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/TransactionParameter.java index 4c63992765a..ed2e9020584 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/TransactionParameter.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/param/TransactionParameter.java @@ -48,7 +48,7 @@ import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; 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 ParamStyle myParamStyle; private Class myResourceBundleType; @@ -112,6 +112,7 @@ public class TransactionParameter implements IParameter { case DSTU1_BUNDLE: { Bundle bundle; bundle = parser.parseBundle(reader); + //FIXME resource leak return bundle; } case RESOURCE_LIST: { @@ -122,12 +123,15 @@ public class TransactionParameter implements IParameter { resourceList.add(next.getResource()); } } + //FIXME resource leak return resourceList; } case RESOURCE_BUNDLE: + //FIXME resource leak return parser.parseResource(myResourceBundleType, reader); } + //FIXME resource leak throw new IllegalStateException("Unknown type: " + myParamStyle); // should not happen } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/IRestfulServer.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/IRestfulServer.java index 7d67796f9ed..46877d82d43 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/IRestfulServer.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/IRestfulServer.java @@ -1,9 +1,6 @@ package ca.uhn.fhir.rest.server; -import java.util.List; - import ca.uhn.fhir.rest.method.RequestDetails; -import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor; /* * #%L diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/ResourceBinding.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/ResourceBinding.java index 0c3bf7a5e14..2e13855c823 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/ResourceBinding.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/ResourceBinding.java @@ -55,9 +55,8 @@ public class ResourceBinding { if (rm.incomingServerRequestMatchesMethod(theRequest)) { ourLog.debug("Handler {} matches", rm); return rm; - } else { - ourLog.trace("Handler {} does not match", rm); } + ourLog.trace("Handler {} does not match", rm); } return null; } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/RestfulServer.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/RestfulServer.java index d673656cd24..f1c0a5ff2a7 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/RestfulServer.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/RestfulServer.java @@ -266,9 +266,8 @@ public class RestfulServer extends HttpServlet implements IRestfulServer> 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); - } - } + List> 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; @@ -406,6 +404,7 @@ public class RestfulServer extends HttpServlet implements IRestfulServer theType) { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/IServerInterceptor.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/IServerInterceptor.java index 0a4a93c772b..c05a5b432ba 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/IServerInterceptor.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/IServerInterceptor.java @@ -42,7 +42,6 @@ import ca.uhn.fhir.rest.annotation.Search; import ca.uhn.fhir.rest.api.RestOperationTypeEnum; import ca.uhn.fhir.rest.method.RequestDetails; 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.BaseServerResponseException; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/LoggingInterceptor.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/LoggingInterceptor.java index 1ff01053224..e5e4ca59f49 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/LoggingInterceptor.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/LoggingInterceptor.java @@ -33,7 +33,6 @@ import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -import org.apache.commons.io.Charsets; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; 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.RestfulServerUtils; 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.servlet.ServletRequestDetails; @@ -259,9 +257,8 @@ public class LoggingInterceptor extends InterceptorAdapter { default: return ""; } - } else { - return ""; } + return ""; } else if ("id".equals(theKey)) { if (myRequestDetails.getId() != null) { return myRequestDetails.getId().getValue(); @@ -305,9 +302,8 @@ public class LoggingInterceptor extends InterceptorAdapter { ResponseEncoding encoding = RestfulServerUtils.determineResponseEncodingNoDefault(myRequestDetails, myRequestDetails.getServer().getDefaultResponseEncoding()); if (encoding != null) { return encoding.getEncoding().name(); - } else { - return ""; } + return ""; } else if (theKey.equals("exceptionMessage")) { return myException != null ? myException.getMessage() : null; } else if (theKey.equals("requestUrl")) { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/AuthorizationInterceptor.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/AuthorizationInterceptor.java index 2f1b53eeb03..dd26ab8dc06 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/AuthorizationInterceptor.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/AuthorizationInterceptor.java @@ -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.interceptor.IServerOperationInterceptor; import ca.uhn.fhir.rest.server.interceptor.InterceptorAdapter; -import ca.uhn.fhir.util.BundleUtil; import ca.uhn.fhir.util.CoverageIgnore; /** @@ -209,9 +208,8 @@ public class AuthorizationInterceptor extends InterceptorAdapter implements ISer if (decision.getDecidingRule() != null) { String ruleName = defaultString(decision.getDecidingRule().getName(), "(unnamed rule)"); 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) { @@ -230,7 +228,7 @@ public class AuthorizationInterceptor extends InterceptorAdapter implements ISer inputResourceId = theProcessedRequest.getId(); break; case OUT: - inputResource = null; +// inputResource = null; inputResourceId = theProcessedRequest.getId(); break; case NONE: diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/IAuthRuleBuilderOperationNamed.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/IAuthRuleBuilderOperationNamed.java index be8f3d1ff0b..4d1e4d07e95 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/IAuthRuleBuilderOperationNamed.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/IAuthRuleBuilderOperationNamed.java @@ -1,7 +1,5 @@ package ca.uhn.fhir.rest.server.interceptor.auth; -import org.apache.http.impl.client.HttpClientBuilder; - /* * #%L * HAPI FHIR - Core Library diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/IAuthRuleBuilderRuleConditionalClassifier.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/IAuthRuleBuilderRuleConditionalClassifier.java index ffaf2dca76e..4b8a8449ccd 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/IAuthRuleBuilderRuleConditionalClassifier.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/IAuthRuleBuilderRuleConditionalClassifier.java @@ -1,7 +1,5 @@ package ca.uhn.fhir.rest.server.interceptor.auth; -import java.util.List; - /* * #%L * HAPI FHIR - Core Library diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/RuleImplOp.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/RuleImplOp.java index 89eb25d8127..118e9b08c80 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/RuleImplOp.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/interceptor/auth/RuleImplOp.java @@ -41,7 +41,7 @@ import ca.uhn.fhir.util.BundleUtil; import ca.uhn.fhir.util.BundleUtil.BundleEntryParts; import ca.uhn.fhir.util.FhirTerser; -class RuleImplOp extends BaseRule implements IAuthRule { +class RuleImplOp extends BaseRule /*implements IAuthRule*/ { private AppliesTypeEnum myAppliesTo; private Set myAppliesToTypes; @@ -108,9 +108,8 @@ class RuleImplOp extends BaseRule implements IAuthRule { if (theOperation == RestOperationTypeEnum.DELETE) { if (theInputResource == null) { return newVerdict(); - } else { - appliesToResource = theInputResource; } + appliesToResource = theInputResource; } else { return null; } @@ -123,45 +122,44 @@ class RuleImplOp extends BaseRule implements IAuthRule { if (theInputResource != null && requestAppliesToTransaction(ctx, myOp, theInputResource)) { if (getMode() == PolicyEnum.DENY) { return new Verdict(PolicyEnum.DENY, this); - } else { - List 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 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) { List inputResources = BundleUtil.toListOfEntries(ctx, (IBaseBundle) theInputResource); Verdict verdict = null; @@ -189,9 +187,8 @@ class RuleImplOp extends BaseRule implements IAuthRule { case METADATA: if (theOperation == RestOperationTypeEnum.METADATA) { return newVerdict(); - } else { - return null; } + return null; default: // Should not happen throw new IllegalStateException("Unable to apply security to event of type " + theOperation); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRequestDetails.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRequestDetails.java index 3000ed48133..03ab3d077f0 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRequestDetails.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRequestDetails.java @@ -105,7 +105,7 @@ public class ServletRequestDetails extends RequestDetails { } } } - + //FIXME resource leak return requestContents; } catch (IOException e) { ourLog.error("Could not load request resource", e); diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRestfulResponse.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRestfulResponse.java index 457825bc52e..64108021fee 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRestfulResponse.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/rest/server/servlet/ServletRestfulResponse.java @@ -51,12 +51,11 @@ public class ServletRestfulResponse extends RestfulResponse void addElement(ArrayList retVal, IElement next, Class theType) { + //FIXME There seems to be an error on theType == null => if (theType != null|| theType.isAssignableFrom if (theType == null|| theType.isAssignableFrom(next.getClass())) { - retVal.add((T) next); + retVal.add(theType.cast(next)); } if (next instanceof ICompositeElement) { ICompositeElement iCompositeElement = (ICompositeElement) next; + //TODO: Use of a deprecated method should be resolved. retVal.addAll(iCompositeElement.getAllPopulatedChildElementsOfType(theType)); } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/FhirTerser.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/FhirTerser.java index a35a062a319..37f86b4fa7e 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/FhirTerser.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/FhirTerser.java @@ -70,13 +70,11 @@ public class FhirTerser { if (theTarget instanceof IPrimitiveType) { ((IPrimitiveType)theTarget).setValueAsString(((IPrimitiveType)theSource).getValueAsString()); return; - } else { - if (theIgnoreMissingFields) { - return; - } else { - throw new DataFormatException("Can not copy value from primitive of type " + theSource.getClass().getName() + " into type " + theTarget.getClass().getName()); - } } + if (theIgnoreMissingFields) { + return; + } + throw new DataFormatException("Can not copy value from primitive of type " + theSource.getClass().getName() + " into type " + theTarget.getClass().getName()); } BaseRuntimeElementCompositeDefinition sourceDef = (BaseRuntimeElementCompositeDefinition) myContext.getElementDefinition(theSource.getClass()); @@ -94,9 +92,8 @@ public class FhirTerser { if (targetChild == null) { if (theIgnoreMissingFields) { continue; - } else { - throw new DataFormatException("Type " + theTarget.getClass().getName() + " does not have a child with name " + elementName); } + throw new DataFormatException("Type " + theTarget.getClass().getName() + " does not have a child with name " + elementName); } BaseRuntimeElementDefinition childDef = targetChild.getChildByName(elementName); @@ -166,10 +163,9 @@ public class FhirTerser { if (theSubList.size() == 1) { return nextDef; - } else { - BaseRuntimeElementCompositeDefinition cmp = (BaseRuntimeElementCompositeDefinition) nextDef.getChildByName(theSubList.get(0)); - return getDefinition(cmp, theSubList.subList(1, theSubList.size())); } + BaseRuntimeElementCompositeDefinition cmp = (BaseRuntimeElementCompositeDefinition) nextDef.getChildByName(theSubList.get(0)); + return getDefinition(cmp, theSubList.subList(1, theSubList.size())); } public BaseRuntimeChildDefinition getDefinition(Class theResourceType, String thePath) { @@ -208,9 +204,8 @@ public class FhirTerser { List retVal = getValues(currentDef, currentObj, parts, theWantedType); if (retVal.isEmpty()) { return null; - } else { - return retVal.get(0); } + return retVal.get(0); } @SuppressWarnings("unchecked") diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/IModelVisitor.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/IModelVisitor.java index 20edcd94db8..d1e22dd61c9 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/IModelVisitor.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/IModelVisitor.java @@ -27,8 +27,6 @@ import org.hl7.fhir.instance.model.api.IBaseResource; import ca.uhn.fhir.context.BaseRuntimeChildDefinition; import ca.uhn.fhir.context.BaseRuntimeElementDefinition; -import ca.uhn.fhir.model.api.ExtensionDt; -import ca.uhn.fhir.model.api.ISupportsUndeclaredExtensions; /** * @see FhirTerser#visit(IBaseResource, IModelVisitor) diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/OperationOutcomeUtil.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/OperationOutcomeUtil.java index 29900f74fb2..07238019a2f 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/OperationOutcomeUtil.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/OperationOutcomeUtil.java @@ -90,9 +90,8 @@ public class OperationOutcomeUtil { public static String getFirstIssueDetails(FhirContext theCtx, IBaseOperationOutcome theOutcome) { if (theCtx.getVersion().getVersion().isNewerThan(FhirVersionEnum.DSTU1)) { return getFirstIssueStringPart(theCtx, theOutcome, "diagnostics"); - } else { - return getFirstIssueStringPart(theCtx, theOutcome, "details"); } + return getFirstIssueStringPart(theCtx, theOutcome, "details"); } public static String getFirstIssueLocation(FhirContext theCtx, IBaseOperationOutcome theOutcome) { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/PortUtil.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/PortUtil.java index 217e6e9ab66..620e36dbbc4 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/PortUtil.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/PortUtil.java @@ -47,6 +47,7 @@ public class PortUtil { Thread.sleep(500); return port; } catch (Exception e) { + //FIXME resource leak throw new Error(e); } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/ReflectionUtil.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/ReflectionUtil.java index 6b842387f40..0c3c991628c 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/ReflectionUtil.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/ReflectionUtil.java @@ -81,9 +81,8 @@ public class ReflectionUtil { ParameterizedType pt = ((ParameterizedType) firstArg); Type pt2 = pt.getActualTypeArguments()[0]; return (Class) pt2; - } else { - type = (Class) firstArg; } + type = (Class) firstArg; return type; } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/ResourceReferenceInfo.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/ResourceReferenceInfo.java index ccdd40f8089..d3bf689217f 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/ResourceReferenceInfo.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/ResourceReferenceInfo.java @@ -107,9 +107,8 @@ public class ResourceReferenceInfo { } } return false; - } else { - // DSTU1 style - return (theInclude.getValue().equals(myOwningResource + '.' + myName)); } + // DSTU1 style + return (theInclude.getValue().equals(myOwningResource + '.' + myName)); } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/UrlUtil.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/UrlUtil.java index 81c850905e5..a275a36a640 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/UrlUtil.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/UrlUtil.java @@ -244,45 +244,45 @@ public class UrlUtil { retVal.setResourceType(id.getResourceType()); retVal.setResourceId(id.getIdPart()); retVal.setVersionId(id.getVersionIdPart()); - return retVal; - } else { - if (url.matches("\\/[a-zA-Z]+\\?.*")) { - url = url.substring(1); - } - int nextStart = 0; - boolean nextIsHistory = false; - - for (int idx = 0; idx < url.length(); idx++) { - char nextChar = url.charAt(idx); - boolean atEnd = (idx + 1) == url.length(); - if (nextChar == '?' || nextChar == '/' || atEnd) { - int endIdx = (atEnd && nextChar != '?') ? idx + 1 : idx; - String nextSubstring = url.substring(nextStart, endIdx); - if (retVal.getResourceType() == null) { - retVal.setResourceType(nextSubstring); - } else if (retVal.getResourceId() == null) { - retVal.setResourceId(nextSubstring); - } else if (nextIsHistory) { - retVal.setVersionId(nextSubstring); - } else { - if (nextSubstring.equals(Constants.URL_TOKEN_HISTORY)) { - nextIsHistory = true; - } else { - throw new InvalidRequestException("Invalid FHIR resource URL: " + url); - } - } - if (nextChar == '?') { - if (url.length() > idx + 1) { - retVal.setParams(url.substring(idx + 1, url.length())); - } - break; - } - nextStart = idx + 1; - } - } - return retVal; } + if (url.matches("\\/[a-zA-Z]+\\?.*")) { + url = url.substring(1); + } + int nextStart = 0; + boolean nextIsHistory = false; + + for (int idx = 0; idx < url.length(); idx++) { + char nextChar = url.charAt(idx); + boolean atEnd = (idx + 1) == url.length(); + if (nextChar == '?' || nextChar == '/' || atEnd) { + int endIdx = (atEnd && nextChar != '?') ? idx + 1 : idx; + String nextSubstring = url.substring(nextStart, endIdx); + if (retVal.getResourceType() == null) { + retVal.setResourceType(nextSubstring); + } else if (retVal.getResourceId() == null) { + retVal.setResourceId(nextSubstring); + } else if (nextIsHistory) { + retVal.setVersionId(nextSubstring); + } else { + if (nextSubstring.equals(Constants.URL_TOKEN_HISTORY)) { + nextIsHistory = true; + } else { + throw new InvalidRequestException("Invalid FHIR resource URL: " + url); + } + } + if (nextChar == '?') { + if (url.length() > idx + 1) { + retVal.setParams(url.substring(idx + 1, url.length())); + } + break; + } + nextStart = idx + 1; + } + } + + return retVal; + } public static String unescape(String theString) { diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/XmlUtil.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/XmlUtil.java index cbdba18d6c5..26b254d76ee 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/XmlUtil.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/XmlUtil.java @@ -1681,9 +1681,8 @@ public class XmlUtil { if (ourNextException != null) { if (ourNextException instanceof FactoryConfigurationError) { throw ((FactoryConfigurationError)ourNextException); - } else { - throw (XMLStreamException)ourNextException; } + throw (XMLStreamException)ourNextException; } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/jar/DependencyLogImpl.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/jar/DependencyLogImpl.java index ec96225c20a..21ea4fb3eda 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/jar/DependencyLogImpl.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/jar/DependencyLogImpl.java @@ -100,8 +100,7 @@ public class DependencyLogImpl implements IDependencyLog { } catch (MalformedURLException ex) { return null; } - } else { - return null; } + return null; } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/SchemaBaseValidator.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/SchemaBaseValidator.java index 9961c19d4bd..61a7f790b5e 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/SchemaBaseValidator.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/SchemaBaseValidator.java @@ -165,7 +165,7 @@ public class SchemaBaseValidator implements IValidatorModule { baseIs = new BOMInputStream(baseIs, false); InputStreamReader baseReader = new InputStreamReader(baseIs, Charset.forName("UTF-8")); Source baseSource = new StreamSource(baseReader, theSystemId); - + //FIXME resource leak return baseSource; } @@ -240,7 +240,7 @@ public class SchemaBaseValidator implements IValidatorModule { } input.setByteStream(baseIs); - + //FIXME resource leak return input; } diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/DefinitionException.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/DefinitionException.java index 0e3aee9c2eb..3896b1dd9b1 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/DefinitionException.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/DefinitionException.java @@ -23,6 +23,8 @@ package org.hl7.fhir.exceptions; public class DefinitionException extends FHIRException { + private static final long serialVersionUID = 8175803009974854088L; + public DefinitionException() { super(); } diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/FHIRException.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/FHIRException.java index 0bcb6cb7f37..274864c3078 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/FHIRException.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/FHIRException.java @@ -25,6 +25,8 @@ public class FHIRException extends Exception { // Note that the 4-argument constructor has been removed as it is not JDK6 compatible + private static final long serialVersionUID = -1793365096090608037L; + public FHIRException() { super(); } diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/NoTerminologyServiceException.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/NoTerminologyServiceException.java index cf01c90072f..08be82d5d89 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/NoTerminologyServiceException.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/NoTerminologyServiceException.java @@ -23,6 +23,8 @@ package org.hl7.fhir.exceptions; public class NoTerminologyServiceException extends FHIRException { + private static final long serialVersionUID = 8196224236579018584L; + public NoTerminologyServiceException() { super(); } diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/PathEngineException.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/PathEngineException.java index 3dc96c5e294..b56c9d9212c 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/PathEngineException.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/PathEngineException.java @@ -23,6 +23,8 @@ package org.hl7.fhir.exceptions; public class PathEngineException extends FHIRException { + private static final long serialVersionUID = -8550234068917355391L; + public PathEngineException() { super(); } diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/TerminologyServiceException.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/TerminologyServiceException.java index 5760798d4fa..2f1ae3dca5a 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/TerminologyServiceException.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/TerminologyServiceException.java @@ -23,6 +23,8 @@ package org.hl7.fhir.exceptions; public class TerminologyServiceException extends FHIRException { + private static final long serialVersionUID = -1547510329455394225L; + public TerminologyServiceException() { super(); } diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/UcumException.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/UcumException.java index 081b3ac8274..c1c2bd8a90e 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/UcumException.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/exceptions/UcumException.java @@ -23,6 +23,8 @@ package org.hl7.fhir.exceptions; public class UcumException extends FHIRException { + private static final long serialVersionUID = -8535757334881835619L; + public UcumException() { super(); } diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/instance/model/api/IIdType.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/instance/model/api/IIdType.java index 119ddb66e4e..35af39be3a5 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/instance/model/api/IIdType.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/instance/model/api/IIdType.java @@ -64,6 +64,7 @@ public interface IIdType extends IPrimitiveType { * * @see #getIdPart() */ + @Override String getValue(); String getVersionIdPart(); @@ -93,6 +94,7 @@ public interface IIdType extends IPrimitiveType { */ boolean isAbsolute(); + @Override boolean isEmpty(); /** diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/instance/model/api/INarrative.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/instance/model/api/INarrative.java index 2d0a86454d1..400155c72b9 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/instance/model/api/INarrative.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/instance/model/api/INarrative.java @@ -23,6 +23,7 @@ package org.hl7.fhir.instance.model.api; public interface INarrative extends ICompositeType { + @Override boolean isEmpty(); // TODO: use less broad exception type here diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/MyURIResolver.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/MyURIResolver.java index ffe257f8d88..bea4891ccd4 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/MyURIResolver.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/MyURIResolver.java @@ -48,7 +48,7 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ import java.io.File; import java.io.FileInputStream; @@ -63,33 +63,34 @@ import javax.xml.transform.stream.StreamSource; public class MyURIResolver implements URIResolver { - private String path; - private URIResolver alt; - - public MyURIResolver(String path, URIResolver alt) { - super(); - this.path = path; - this.alt = alt; - } + private String path; + private URIResolver alt; + + public MyURIResolver(String path, URIResolver alt) { + super(); + this.path = path; + this.alt = alt; + } - @Override - public Source resolve(String href, String base) throws TransformerException { - try { - if (href.startsWith("http://") || href.startsWith("https://")) { - if (alt != null) { - Source s = alt.resolve(href, base); - if (s != null) - return s; - } - return TransformerFactory.newInstance().getURIResolver().resolve(href, base); - } else - return new StreamSource(new FileInputStream(href.contains(File.separator) ? href : Utilities.path(path, href))); - } catch (FileNotFoundException e) { - throw new TransformerException(e); - } catch (IOException e) { - throw new TransformerException(e); - } - } + @Override + public Source resolve(String href, String base) throws TransformerException { + try { + if (href.startsWith("http://") || href.startsWith("https://")) { + if (alt != null) { + Source s = alt.resolve(href, base); + if (s != null) + return s; + } + return TransformerFactory.newInstance().getURIResolver().resolve(href, base); + } else + //FIXME resource leak + return new StreamSource(new FileInputStream(href.contains(File.separator) ? href : Utilities.path(path, href))); + } catch (FileNotFoundException e) { + throw new TransformerException(e); + } catch (IOException e) { + throw new TransformerException(e); + } + } } diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/Table.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/Table.java index dfca0f8dd5e..881ffc7f9f2 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/Table.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/Table.java @@ -26,12 +26,12 @@ import java.util.List; public class Table { - private int rowCount; +// private int rowCount; private int colCount; private List> rows = new ArrayList>(); public Table(int rowCount, int colCount) { - this.rowCount = rowCount; +// this.rowCount = rowCount; this.colCount = colCount; for (int r = 0; r < rowCount; r++) { rows.add(new ArrayList()); diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/TextFile.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/TextFile.java index 740a18f33cb..5ec46b917cc 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/TextFile.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/TextFile.java @@ -25,7 +25,7 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ package org.hl7.fhir.utilities; /* @@ -64,17 +64,17 @@ public class TextFile { public static List readAllLines(String path) throws IOException { List result = new ArrayList(); - + File file = new CSFile(path); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8")); - + while( reader.ready() ) result.add(reader.readLine()); - + reader.close(); return result; } - + public static void writeAllLines(String path, List lines) throws IOException { File file = new CSFile(path); @@ -82,53 +82,54 @@ public class TextFile { OutputStreamWriter sw = new OutputStreamWriter(s, "UTF-8"); for( String line : lines ) sw.write(line + "\r\n"); - + sw.flush(); s.close(); } - - - public static void stringToFile(String content, String path) throws IOException { - File file = new CSFile(path); - OutputStreamWriter sw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); - sw.write('\ufeff'); // Unicode BOM, translates to UTF-8 with the configured outputstreamwriter - sw.write(content); - sw.flush(); - sw.close(); - } - public static void stringToFileNoPrefix(String content, String path) throws IOException { - File file = new CSFile(path); - OutputStreamWriter sw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); - sw.write(content); - sw.flush(); - sw.close(); - } - public static String fileToString(String src) throws FileNotFoundException, IOException { - return streamToString(new FileInputStream(new CSFile(src))); + public static void stringToFile(String content, String path) throws IOException { + File file = new CSFile(path); + OutputStreamWriter sw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); + sw.write('\ufeff'); // Unicode BOM, translates to UTF-8 with the configured outputstreamwriter + sw.write(content); + sw.flush(); + sw.close(); } - public static String streamToString(InputStream input) throws IOException { - InputStreamReader sr = new InputStreamReader(input, "UTF-8"); - StringBuilder b = new StringBuilder(); - //while (sr.ready()) { Commented out by Claude Nanjo (1/14/2014) - sr.ready() always returns false - please remove if change does not impact other areas of codebase - int i = -1; - while((i = sr.read()) > -1) { - char c = (char) i; - b.append(c); - } -// sr.close(); - - return b.toString().replace("\uFEFF", ""); - } + public static void stringToFileNoPrefix(String content, String path) throws IOException { + File file = new CSFile(path); + OutputStreamWriter sw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); + sw.write(content); + sw.flush(); + sw.close(); + } - public static void bytesToFile(byte[] bytes, String path) throws IOException { - File file = new CSFile(path); - OutputStream sw = new FileOutputStream(file); - sw.write(bytes); - sw.flush(); - sw.close(); - - } + public static String fileToString(String src) throws FileNotFoundException, IOException { + //FIXME resource leak + return streamToString(new FileInputStream(new CSFile(src))); + } + + public static String streamToString(InputStream input) throws IOException { + InputStreamReader sr = new InputStreamReader(input, "UTF-8"); + StringBuilder b = new StringBuilder(); + //while (sr.ready()) { Commented out by Claude Nanjo (1/14/2014) - sr.ready() always returns false - please remove if change does not impact other areas of codebase + int i = -1; + while((i = sr.read()) > -1) { + char c = (char) i; + b.append(c); + } + // sr.close(); + + return b.toString().replace("\uFEFF", ""); + } + + public static void bytesToFile(byte[] bytes, String path) throws IOException { + File file = new CSFile(path); + OutputStream sw = new FileOutputStream(file); + sw.write(bytes); + sw.flush(); + sw.close(); + + } } diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/Utilities.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/Utilities.java index e5504da10a7..45facbdd195 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/Utilities.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/Utilities.java @@ -28,976 +28,926 @@ POSSIBILITY OF SUCH DAMAGE. */ package org.hl7.fhir.utilities; -/* - * #%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.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FilenameFilter; import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.net.URLEncoder; -import java.nio.channels.FileChannel; -import java.util.ArrayList; import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.sound.sampled.AudioFormat; -import javax.sound.sampled.AudioSystem; -import javax.sound.sampled.SourceDataLine; -import javax.xml.transform.Transformer; -import javax.xml.transform.TransformerException; -import javax.xml.transform.TransformerFactory; -import javax.xml.transform.URIResolver; -import javax.xml.transform.stream.StreamResult; -import javax.xml.transform.stream.StreamSource; - -import org.apache.commons.io.FileUtils; -import org.hl7.fhir.exceptions.FHIRException; - -import net.sf.saxon.TransformerFactoryImpl; public class Utilities { -// private static final String TOKEN_REGEX = "^a-z[A-Za-z0-9]*$"; + // private static final String TOKEN_REGEX = "^a-z[A-Za-z0-9]*$"; + + + // private static final String OID_REGEX = "[0-2](\\.(0|[1-9]([0-9])*))*"; + // + // + // + public static boolean isInteger(String string) { + try { + int i = Integer.parseInt(string); + return i != i+1; + } catch (Exception e) { + return false; + } + } + + public static boolean isHex(String string) { + try { + int i = Integer.parseInt(string, 16); + return i != i+1; + } catch (Exception e) { + return false; + } + } + + public static boolean isDecimal(String string) { + if (Utilities.noString(string)) + return false; + try { + float r = Float.parseFloat(string); + return r != r + 1; // just to suppress the hint + } catch (Exception e) { + return false; + } + } -// private static final String OID_REGEX = "[0-2](\\.(0|[1-9]([0-9])*))*"; -// -// -// - public static boolean isInteger(String string) { - try { - int i = Integer.parseInt(string); - return i != i+1; - } catch (Exception e) { - return false; - } - } - - public static boolean isHex(String string) { - try { - int i = Integer.parseInt(string, 16); - return i != i+1; - } catch (Exception e) { - return false; - } - } - - public static boolean isDecimal(String string) { - if (Utilities.noString(string)) - return false; - try { - float r = Float.parseFloat(string); - return r != r + 1; // just to suppress the hint - } catch (Exception e) { - return false; - } - } - - public static String escapeXml(String doco) { if (doco == null) return ""; - + StringBuilder b = new StringBuilder(); for (char c : doco.toCharArray()) { - if (c == '<') - b.append("<"); - else if (c == '>') - b.append(">"); - else if (c == '&') - b.append("&"); - else if (c == '"') - b.append("""); - else - b.append(c); + if (c == '<') + b.append("<"); + else if (c == '>') + b.append(">"); + else if (c == '&') + b.append("&"); + else if (c == '"') + b.append("""); + else + b.append(c); } return b.toString(); } -// -// + // + // public static String capitalize(String s) { if( s == null ) return null; if( s.length() == 0 ) return s; if( s.length() == 1 ) return s.toUpperCase(); - + return s.substring(0, 1).toUpperCase() + s.substring(1); } -// -// public static void copyDirectory(String sourceFolder, String destFolder, FileNotifier notifier) throws IOException, FHIRException { -// CSFile src = new CSFile(sourceFolder); -// if (!src.exists()) -// throw new FHIRException("Folder " +sourceFolder+" not found"); -// createDirectory(destFolder); -// -// String[] files = src.list(); -// for (String f : files) { -// if (new CSFile(sourceFolder+File.separator+f).isDirectory()) { -// if (!f.startsWith(".")) // ignore .svn... -// copyDirectory(sourceFolder+File.separator+f, destFolder+File.separator+f, notifier); -// } else { -// if (notifier != null) -// notifier.copyFile(sourceFolder+File.separator+f, destFolder+File.separator+f); -// copyFile(new CSFile(sourceFolder+File.separator+f), new CSFile(destFolder+File.separator+f)); -// } -// } -// } -// -// public static void copyFile(String source, String dest) throws IOException { -// copyFile(new File(source), new File(dest)); -// } -// -// public static void copyFile(File sourceFile, File destFile) throws IOException { -// if(!destFile.exists()) { -// if (!new CSFile(destFile.getParent()).exists()) { -// createDirectory(destFile.getParent()); -// } -// destFile.createNewFile(); -// } -// -// FileChannel source = null; -// FileChannel destination = null; -// -// try { -// source = new FileInputStream(sourceFile).getChannel(); -// destination = new FileOutputStream(destFile).getChannel(); -// destination.transferFrom(source, 0, source.size()); -// } -// finally { -// if(source != null) { -// source.close(); -// } -// if(destination != null) { -// destination.close(); -// } -// } -// } -// -// public static boolean checkFolder(String dir, List errors) -// throws IOException -// { -// if (!new CSFile(dir).exists()) { -// errors.add("Unable to find directory "+dir); -// return false; -// } else { -// return true; -// } -// } -// -// public static boolean checkFile(String purpose, String dir, String file, List errors) -// throws IOException -// { -// if (!new CSFile(dir+file).exists()) { -// errors.add("Unable to find "+purpose+" file "+file+" in "+dir); -// return false; -// } else { -// return true; -// } -// } -// -// public static String asCSV(List strings) { -// StringBuilder s = new StringBuilder(); -// boolean first = true; -// for (String n : strings) { -// if (!first) -// s.append(","); -// s.append(n); -// first = false; -// } -// return s.toString(); -// } -// -// public static String asHtmlBr(String prefix, List strings) { -// StringBuilder s = new StringBuilder(); -// boolean first = true; -// for (String n : strings) { -// if (!first) -// s.append("
"); -// s.append(prefix); -// s.append(n); -// first = false; -// } -// return s.toString(); -// } -// -// public static void clearDirectory(String folder) throws IOException { -// File dir = new File(folder); -// if (dir.exists()) -// FileUtils.cleanDirectory(dir); -//// String[] files = new CSFile(folder).list(); -//// if (files != null) { -//// for (String f : files) { -//// File fh = new CSFile(folder+File.separatorChar+f); -//// if (fh.isDirectory()) -//// clearDirectory(fh.getAbsolutePath()); -//// fh.delete(); -//// } -//// } -// } -// -// public static void createDirectory(String path) throws IOException{ -// new CSFile(path).mkdirs(); -// } -// -// public static String changeFileExt(String name, String ext) { -// if (name.lastIndexOf('.') > -1) -// return name.substring(0, name.lastIndexOf('.')) + ext; -// else -// return name+ext; -// } -// -// public static String cleanupTextString( String contents ) -// { -// if( contents == null || contents.trim().equals("") ) -// return null; -// else -// return contents.trim(); -// } -// -// - public static boolean noString(String v) { - return v == null || v.equals(""); - } -// -// -// public static byte[] saxonTransform(Map files, byte[] source, byte[] xslt) throws TransformerException { -// TransformerFactory f = new net.sf.saxon.TransformerFactoryImpl(); -// f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE); -// StreamSource xsrc = new StreamSource(new ByteArrayInputStream(xslt)); -// f.setURIResolver(new ZipURIResolver(files)); -// Transformer t = f.newTransformer(xsrc); -// -// t.setURIResolver(new ZipURIResolver(files)); -// StreamSource src = new StreamSource(new ByteArrayInputStream(source)); -// ByteArrayOutputStream out = new ByteArrayOutputStream(); -// StreamResult res = new StreamResult(out); -// t.transform(src, res); -// return out.toByteArray(); -// } -// -// public static byte[] transform(Map files, byte[] source, byte[] xslt) throws TransformerException { -// TransformerFactory f = TransformerFactory.newInstance(); -// f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE); -// StreamSource xsrc = new StreamSource(new ByteArrayInputStream(xslt)); -// f.setURIResolver(new ZipURIResolver(files)); -// Transformer t = f.newTransformer(xsrc); -// -// t.setURIResolver(new ZipURIResolver(files)); -// StreamSource src = new StreamSource(new ByteArrayInputStream(source)); -// ByteArrayOutputStream out = new ByteArrayOutputStream(); -// StreamResult res = new StreamResult(out); -// t.transform(src, res); -// return out.toByteArray(); -// } -// -// public static void bytesToFile(byte[] content, String filename) throws IOException { -// FileOutputStream out = new FileOutputStream(filename); -// out.write(content); -// out.close(); -// -// } -// -// public static String saxonTransform(String source, String xslt) throws TransformerException, FileNotFoundException { -// TransformerFactoryImpl f = new net.sf.saxon.TransformerFactoryImpl(); -// f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE); -// StreamSource xsrc = new StreamSource(new FileInputStream(xslt)); -// Transformer t = f.newTransformer(xsrc); -// StreamSource src = new StreamSource(new FileInputStream(source)); -// StreamResult res = new StreamResult(new ByteArrayOutputStream()); -// t.transform(src, res); -// return res.getOutputStream().toString(); -// } -// -// public static void saxonTransform(String xsltDir, String source, String xslt, String dest, URIResolver alt) throws FileNotFoundException, TransformerException { -// saxonTransform(xsltDir, source, xslt, dest, alt, null); -// } -// -// public static void saxonTransform(String xsltDir, String source, String xslt, String dest, URIResolver alt, Map params) throws FileNotFoundException, TransformerException { -// TransformerFactoryImpl f = new net.sf.saxon.TransformerFactoryImpl(); -// f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE); -// StreamSource xsrc = new StreamSource(new FileInputStream(xslt)); -// f.setURIResolver(new MyURIResolver(xsltDir, alt)); -// Transformer t = f.newTransformer(xsrc); -// if (params != null) { -// for (Map.Entry entry : params.entrySet()) { -// t.setParameter(entry.getKey(), entry.getValue()); -// } -// } -// -// t.setURIResolver(new MyURIResolver(xsltDir, alt)); -// StreamSource src = new StreamSource(new FileInputStream(source)); -// StreamResult res = new StreamResult(new FileOutputStream(dest)); -// t.transform(src, res); -// } -// -// public static void transform(String xsltDir, String source, String xslt, String dest, URIResolver alt) throws FileNotFoundException, TransformerException { -// -// TransformerFactory f = TransformerFactory.newInstance(); -// StreamSource xsrc = new StreamSource(new FileInputStream(xslt)); -// f.setURIResolver(new MyURIResolver(xsltDir, alt)); -// Transformer t = f.newTransformer(xsrc); -// -// t.setURIResolver(new MyURIResolver(xsltDir, alt)); -// StreamSource src = new StreamSource(new FileInputStream(source)); -// StreamResult res = new StreamResult(new FileOutputStream(dest)); -// t.transform(src, res); -// -// } -// -// - public static String appendSlash(String definitions) { - return definitions.endsWith(File.separator) ? definitions : definitions+File.separator; - } -// -// public static String appendForwardSlash(String definitions) { -// return definitions.endsWith("/") ? definitions : definitions+"/"; -// } -// -// -// public static String fileTitle(String file) { -// if (file == null) -// return null; -// String s = new File(file).getName(); -// return s.indexOf(".") == -1? s : s.substring(0, s.indexOf(".")); -// } -// -// -// public static String systemEol() -// { -// return System.getProperty("line.separator"); -// } -// - public static String normaliseEolns(String value) { - return value.replace("\r\n", "\r").replace("\n", "\r").replace("\r", "\r\n"); - } -// -// -// public static String unescapeXml(String xml) throws FHIRException { -// if (xml == null) -// return null; -// -// StringBuilder b = new StringBuilder(); -// int i = 0; -// while (i < xml.length()) { -// if (xml.charAt(i) == '&') { -// StringBuilder e = new StringBuilder(); -// i++; -// while (xml.charAt(i) != ';') { -// e.append(xml.charAt(i)); -// i++; -// } -// if (e.toString().equals("lt")) -// b.append("<"); -// else if (e.toString().equals("gt")) -// b.append(">"); -// else if (e.toString().equals("amp")) -// b.append("&"); -// else if (e.toString().equals("quot")) -// b.append("\""); -// else if (e.toString().equals("mu")) -// b.append((char)956); -// else -// throw new FHIRException("unknown XML entity \""+e.toString()+"\""); -// } else -// b.append(xml.charAt(i)); -// i++; -// } -// return b.toString(); -// } -// -// -// -// -// public static String padRight(String src, char c, int len) { -// StringBuilder s = new StringBuilder(); -// s.append(src); -// for (int i = 0; i < len - src.length(); i++) -// s.append(c); -// return s.toString(); -// } -// -// - public static String padLeft(String src, char c, int len) { - StringBuilder s = new StringBuilder(); - for (int i = 0; i < len - src.length(); i++) - s.append(c); - s.append(src); - return s.toString(); - } -// -// - public static String path(String... args) throws IOException { - StringBuilder s = new StringBuilder(); - boolean d = false; - for(String arg: args) { - if (!d) - d = !noString(arg); - else if (!s.toString().endsWith(File.separator)) - s.append(File.separator); - String a = arg; - a = a.replace("\\", File.separator); - if (s.length() > 0 && a.startsWith(File.separator)) - a = a.substring(File.separator.length()); - - while (a.startsWith(".."+File.separator)) { - String p = s.toString().substring(0, s.length()-1); - if (!p.contains(File.separator)) - throw new IOException("illegal path underrun "+Arrays.asList(args)); - s = new StringBuilder(p.substring(0, p.lastIndexOf(File.separator))+File.separator); - a = a.substring(3); - } - if ("..".equals(a)) { - int i = s.substring(0, s.length()-1).lastIndexOf(File.separator); - s = new StringBuilder(s.substring(0, i+1)); - } else - s.append(a); - } - return s.toString(); - } + // + // public static void copyDirectory(String sourceFolder, String destFolder, FileNotifier notifier) throws IOException, FHIRException { + // CSFile src = new CSFile(sourceFolder); + // if (!src.exists()) + // throw new FHIRException("Folder " +sourceFolder+" not found"); + // createDirectory(destFolder); + // + // String[] files = src.list(); + // for (String f : files) { + // if (new CSFile(sourceFolder+File.separator+f).isDirectory()) { + // if (!f.startsWith(".")) // ignore .svn... + // copyDirectory(sourceFolder+File.separator+f, destFolder+File.separator+f, notifier); + // } else { + // if (notifier != null) + // notifier.copyFile(sourceFolder+File.separator+f, destFolder+File.separator+f); + // copyFile(new CSFile(sourceFolder+File.separator+f), new CSFile(destFolder+File.separator+f)); + // } + // } + // } + // + // public static void copyFile(String source, String dest) throws IOException { + // copyFile(new File(source), new File(dest)); + // } + // + // public static void copyFile(File sourceFile, File destFile) throws IOException { + // if(!destFile.exists()) { + // if (!new CSFile(destFile.getParent()).exists()) { + // createDirectory(destFile.getParent()); + // } + // destFile.createNewFile(); + // } + // + // FileChannel source = null; + // FileChannel destination = null; + // + // try { + // source = new FileInputStream(sourceFile).getChannel(); + // destination = new FileOutputStream(destFile).getChannel(); + // destination.transferFrom(source, 0, source.size()); + // } + // finally { + // if(source != null) { + // source.close(); + // } + // if(destination != null) { + // destination.close(); + // } + // } + // } + // + // public static boolean checkFolder(String dir, List errors) + // throws IOException + // { + // if (!new CSFile(dir).exists()) { + // errors.add("Unable to find directory "+dir); + // return false; + // } else { + // return true; + // } + // } + // + // public static boolean checkFile(String purpose, String dir, String file, List errors) + // throws IOException + // { + // if (!new CSFile(dir+file).exists()) { + // errors.add("Unable to find "+purpose+" file "+file+" in "+dir); + // return false; + // } else { + // return true; + // } + // } + // + // public static String asCSV(List strings) { + // StringBuilder s = new StringBuilder(); + // boolean first = true; + // for (String n : strings) { + // if (!first) + // s.append(","); + // s.append(n); + // first = false; + // } + // return s.toString(); + // } + // + // public static String asHtmlBr(String prefix, List strings) { + // StringBuilder s = new StringBuilder(); + // boolean first = true; + // for (String n : strings) { + // if (!first) + // s.append("
"); + // s.append(prefix); + // s.append(n); + // first = false; + // } + // return s.toString(); + // } + // + // public static void clearDirectory(String folder) throws IOException { + // File dir = new File(folder); + // if (dir.exists()) + // FileUtils.cleanDirectory(dir); + //// String[] files = new CSFile(folder).list(); + //// if (files != null) { + //// for (String f : files) { + //// File fh = new CSFile(folder+File.separatorChar+f); + //// if (fh.isDirectory()) + //// clearDirectory(fh.getAbsolutePath()); + //// fh.delete(); + //// } + //// } + // } + // + // public static void createDirectory(String path) throws IOException{ + // new CSFile(path).mkdirs(); + // } + // + // public static String changeFileExt(String name, String ext) { + // if (name.lastIndexOf('.') > -1) + // return name.substring(0, name.lastIndexOf('.')) + ext; + // else + // return name+ext; + // } + // + // public static String cleanupTextString( String contents ) + // { + // if( contents == null || contents.trim().equals("") ) + // return null; + // else + // return contents.trim(); + // } + // + // + public static boolean noString(String v) { + return v == null || v.equals(""); + } + // + // + // public static byte[] saxonTransform(Map files, byte[] source, byte[] xslt) throws TransformerException { + // TransformerFactory f = new net.sf.saxon.TransformerFactoryImpl(); + // f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE); + // StreamSource xsrc = new StreamSource(new ByteArrayInputStream(xslt)); + // f.setURIResolver(new ZipURIResolver(files)); + // Transformer t = f.newTransformer(xsrc); + // + // t.setURIResolver(new ZipURIResolver(files)); + // StreamSource src = new StreamSource(new ByteArrayInputStream(source)); + // ByteArrayOutputStream out = new ByteArrayOutputStream(); + // StreamResult res = new StreamResult(out); + // t.transform(src, res); + // return out.toByteArray(); + // } + // + // public static byte[] transform(Map files, byte[] source, byte[] xslt) throws TransformerException { + // TransformerFactory f = TransformerFactory.newInstance(); + // f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE); + // StreamSource xsrc = new StreamSource(new ByteArrayInputStream(xslt)); + // f.setURIResolver(new ZipURIResolver(files)); + // Transformer t = f.newTransformer(xsrc); + // + // t.setURIResolver(new ZipURIResolver(files)); + // StreamSource src = new StreamSource(new ByteArrayInputStream(source)); + // ByteArrayOutputStream out = new ByteArrayOutputStream(); + // StreamResult res = new StreamResult(out); + // t.transform(src, res); + // return out.toByteArray(); + // } + // + // public static void bytesToFile(byte[] content, String filename) throws IOException { + // FileOutputStream out = new FileOutputStream(filename); + // out.write(content); + // out.close(); + // + // } + // + // public static String saxonTransform(String source, String xslt) throws TransformerException, FileNotFoundException { + // TransformerFactoryImpl f = new net.sf.saxon.TransformerFactoryImpl(); + // f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE); + // StreamSource xsrc = new StreamSource(new FileInputStream(xslt)); + // Transformer t = f.newTransformer(xsrc); + // StreamSource src = new StreamSource(new FileInputStream(source)); + // StreamResult res = new StreamResult(new ByteArrayOutputStream()); + // t.transform(src, res); + // return res.getOutputStream().toString(); + // } + // + // public static void saxonTransform(String xsltDir, String source, String xslt, String dest, URIResolver alt) throws FileNotFoundException, TransformerException { + // saxonTransform(xsltDir, source, xslt, dest, alt, null); + // } + // + // public static void saxonTransform(String xsltDir, String source, String xslt, String dest, URIResolver alt, Map params) throws FileNotFoundException, TransformerException { + // TransformerFactoryImpl f = new net.sf.saxon.TransformerFactoryImpl(); + // f.setAttribute("http://saxon.sf.net/feature/version-warning", Boolean.FALSE); + // StreamSource xsrc = new StreamSource(new FileInputStream(xslt)); + // f.setURIResolver(new MyURIResolver(xsltDir, alt)); + // Transformer t = f.newTransformer(xsrc); + // if (params != null) { + // for (Map.Entry entry : params.entrySet()) { + // t.setParameter(entry.getKey(), entry.getValue()); + // } + // } + // + // t.setURIResolver(new MyURIResolver(xsltDir, alt)); + // StreamSource src = new StreamSource(new FileInputStream(source)); + // StreamResult res = new StreamResult(new FileOutputStream(dest)); + // t.transform(src, res); + // } + // + // public static void transform(String xsltDir, String source, String xslt, String dest, URIResolver alt) throws FileNotFoundException, TransformerException { + // + // TransformerFactory f = TransformerFactory.newInstance(); + // StreamSource xsrc = new StreamSource(new FileInputStream(xslt)); + // f.setURIResolver(new MyURIResolver(xsltDir, alt)); + // Transformer t = f.newTransformer(xsrc); + // + // t.setURIResolver(new MyURIResolver(xsltDir, alt)); + // StreamSource src = new StreamSource(new FileInputStream(source)); + // StreamResult res = new StreamResult(new FileOutputStream(dest)); + // t.transform(src, res); + // + // } + // + // + public static String appendSlash(String definitions) { + return definitions.endsWith(File.separator) ? definitions : definitions+File.separator; + } + // + // public static String appendForwardSlash(String definitions) { + // return definitions.endsWith("/") ? definitions : definitions+"/"; + // } + // + // + // public static String fileTitle(String file) { + // if (file == null) + // return null; + // String s = new File(file).getName(); + // return s.indexOf(".") == -1? s : s.substring(0, s.indexOf(".")); + // } + // + // + // public static String systemEol() + // { + // return System.getProperty("line.separator"); + // } + // + public static String normaliseEolns(String value) { + return value.replace("\r\n", "\r").replace("\n", "\r").replace("\r", "\r\n"); + } + // + // + // public static String unescapeXml(String xml) throws FHIRException { + // if (xml == null) + // return null; + // + // StringBuilder b = new StringBuilder(); + // int i = 0; + // while (i < xml.length()) { + // if (xml.charAt(i) == '&') { + // StringBuilder e = new StringBuilder(); + // i++; + // while (xml.charAt(i) != ';') { + // e.append(xml.charAt(i)); + // i++; + // } + // if (e.toString().equals("lt")) + // b.append("<"); + // else if (e.toString().equals("gt")) + // b.append(">"); + // else if (e.toString().equals("amp")) + // b.append("&"); + // else if (e.toString().equals("quot")) + // b.append("\""); + // else if (e.toString().equals("mu")) + // b.append((char)956); + // else + // throw new FHIRException("unknown XML entity \""+e.toString()+"\""); + // } else + // b.append(xml.charAt(i)); + // i++; + // } + // return b.toString(); + // } + // + // + // + // + // public static String padRight(String src, char c, int len) { + // StringBuilder s = new StringBuilder(); + // s.append(src); + // for (int i = 0; i < len - src.length(); i++) + // s.append(c); + // return s.toString(); + // } + // + // + public static String padLeft(String src, char c, int len) { + StringBuilder s = new StringBuilder(); + for (int i = 0; i < len - src.length(); i++) + s.append(c); + s.append(src); + return s.toString(); + } + // + // + public static String path(String... args) throws IOException { + StringBuilder s = new StringBuilder(); + boolean d = false; + for(String arg: args) { + if (!d) + d = !noString(arg); + else if (!s.toString().endsWith(File.separator)) + s.append(File.separator); + String a = arg; + a = a.replace("\\", File.separator); + if (s.length() > 0 && a.startsWith(File.separator)) + a = a.substring(File.separator.length()); - public static String pathReverse(String... args) { - StringBuilder s = new StringBuilder(); - boolean d = false; - for(String arg: args) { - if (!d) - d = !noString(arg); - else if (!s.toString().endsWith("/")) - s.append("/"); - s.append(arg); - } - return s.toString(); - } -// -// -// -//// public static void checkCase(String filename) { -//// File f = new CSFile(filename); -//// if (!f.getName().equals(filename)) -//// throw new FHIRException("Filename ") -//// -//// } -// -// public static String nmtokenize(String cs) { -// StringBuilder s = new StringBuilder(); -// for (int i = 0; i < cs.length(); i++) { -// char c = cs.charAt(i); -// if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_') -// s.append(c); -// else if (c != ' ') -// s.append("."+Integer.toString(c)); -// } -// return s.toString(); -// } -// -// -// public static boolean isToken(String tail) { -// if (tail == null || tail.length() == 0) -// return false; -// boolean result = isAlphabetic(tail.charAt(0)); -// for (int i = 1; i < tail.length(); i++) { -// result = result && (isAlphabetic(tail.charAt(i)) || isDigit(tail.charAt(i)) || (tail.charAt(i) == '_') || (tail.charAt(i) == '[') || (tail.charAt(i) == ']')); -// } -// return result; -// } -// -// -// private static boolean isDigit(char c) { -// return (c >= '0') && (c <= '9'); -// } -// -// -// private static boolean isAlphabetic(char c) { -// return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')); -// } -// -// -// public static String getDirectoryForFile(String filepath) { -// File f = new File(filepath); -// return f.getParent(); -// } -// -// public static String appendPeriod(String s) { -// if (Utilities.noString(s)) -// return s; -// s = s.trim(); -// if (s.endsWith(".") || s.endsWith("?")) -// return s; -// return s+"."; -// } -// -// -// public static String removePeriod(String s) { -// if (Utilities.noString(s)) -// return s; -// if (s.endsWith(".")) -// return s.substring(0, s.length()-1); -// return s; -// } -// -// -// public static String stripBOM(String string) { -// return string.replace("\uFEFF", ""); -// } -// -// -// public static String oidTail(String id) { -// if (id == null || !id.contains(".")) -// return id; -// return id.substring(id.lastIndexOf(".")+1); -// } -// -// -// public static String oidRoot(String id) { -// if (id == null || !id.contains(".")) -// return id; -// return id.substring(0, id.indexOf(".")); -// } -// - public static String escapeJava(String doco) { - if (doco == null) - return ""; - - StringBuilder b = new StringBuilder(); - for (char c : doco.toCharArray()) { - if (c == '\r') - b.append("\\r"); - else if (c == '\n') - b.append("\\n"); - else if (c == '"') - b.append("\\\""); - else if (c == '\\') - b.append("\\\\"); - else - b.append(c); - } - return b.toString(); - } -// -// -// public static String[] splitByCamelCase(String name) { -// List parts = new ArrayList(); -// StringBuilder b = new StringBuilder(); -// for (int i = 0; i < name.length(); i++) { -// if (i > 0 && Character.isUpperCase(name.charAt(i))) { -// parts.add(b.toString()); -// b = new StringBuilder(); -// } -// b.append(Character.toLowerCase(name.charAt(i))); -// } -// parts.add(b.toString()); -// return parts.toArray(new String[] {} ); -// } -// -// -// public static String encodeUri(String v) { -// return v.replace(" ", "%20").replace("?", "%3F").replace("=", "%3D"); -// } -// -// -// + while (a.startsWith(".."+File.separator)) { + String p = s.toString().substring(0, s.length()-1); + if (!p.contains(File.separator)) + throw new IOException("illegal path underrun "+Arrays.asList(args)); + s = new StringBuilder(p.substring(0, p.lastIndexOf(File.separator))+File.separator); + a = a.substring(3); + } + if ("..".equals(a)) { + int i = s.substring(0, s.length()-1).lastIndexOf(File.separator); + s = new StringBuilder(s.substring(0, i+1)); + } else + s.append(a); + } + return s.toString(); + } + + public static String pathReverse(String... args) { + StringBuilder s = new StringBuilder(); + boolean d = false; + for(String arg: args) { + if (!d) + d = !noString(arg); + else if (!s.toString().endsWith("/")) + s.append("/"); + s.append(arg); + } + return s.toString(); + } + // + // + // + //// public static void checkCase(String filename) { + //// File f = new CSFile(filename); + //// if (!f.getName().equals(filename)) + //// throw new FHIRException("Filename ") + //// + //// } + // + // public static String nmtokenize(String cs) { + // StringBuilder s = new StringBuilder(); + // for (int i = 0; i < cs.length(); i++) { + // char c = cs.charAt(i); + // if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_') + // s.append(c); + // else if (c != ' ') + // s.append("."+Integer.toString(c)); + // } + // return s.toString(); + // } + // + // + // public static boolean isToken(String tail) { + // if (tail == null || tail.length() == 0) + // return false; + // boolean result = isAlphabetic(tail.charAt(0)); + // for (int i = 1; i < tail.length(); i++) { + // result = result && (isAlphabetic(tail.charAt(i)) || isDigit(tail.charAt(i)) || (tail.charAt(i) == '_') || (tail.charAt(i) == '[') || (tail.charAt(i) == ']')); + // } + // return result; + // } + // + // + // private static boolean isDigit(char c) { + // return (c >= '0') && (c <= '9'); + // } + // + // + // private static boolean isAlphabetic(char c) { + // return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')); + // } + // + // + // public static String getDirectoryForFile(String filepath) { + // File f = new File(filepath); + // return f.getParent(); + // } + // + // public static String appendPeriod(String s) { + // if (Utilities.noString(s)) + // return s; + // s = s.trim(); + // if (s.endsWith(".") || s.endsWith("?")) + // return s; + // return s+"."; + // } + // + // + // public static String removePeriod(String s) { + // if (Utilities.noString(s)) + // return s; + // if (s.endsWith(".")) + // return s.substring(0, s.length()-1); + // return s; + // } + // + // + // public static String stripBOM(String string) { + // return string.replace("\uFEFF", ""); + // } + // + // + // public static String oidTail(String id) { + // if (id == null || !id.contains(".")) + // return id; + // return id.substring(id.lastIndexOf(".")+1); + // } + // + // + // public static String oidRoot(String id) { + // if (id == null || !id.contains(".")) + // return id; + // return id.substring(0, id.indexOf(".")); + // } + // + public static String escapeJava(String doco) { + if (doco == null) + return ""; + + StringBuilder b = new StringBuilder(); + for (char c : doco.toCharArray()) { + if (c == '\r') + b.append("\\r"); + else if (c == '\n') + b.append("\\n"); + else if (c == '"') + b.append("\\\""); + else if (c == '\\') + b.append("\\\\"); + else + b.append(c); + } + return b.toString(); + } + // + // + // public static String[] splitByCamelCase(String name) { + // List parts = new ArrayList(); + // StringBuilder b = new StringBuilder(); + // for (int i = 0; i < name.length(); i++) { + // if (i > 0 && Character.isUpperCase(name.charAt(i))) { + // parts.add(b.toString()); + // b = new StringBuilder(); + // } + // b.append(Character.toLowerCase(name.charAt(i))); + // } + // parts.add(b.toString()); + // return parts.toArray(new String[] {} ); + // } + // + // + // public static String encodeUri(String v) { + // return v.replace(" ", "%20").replace("?", "%3F").replace("=", "%3D"); + // } + // + // + // public static String normalize(String s) { if (noString(s)) return null; - StringBuilder b = new StringBuilder(); - boolean isWhitespace = false; - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (!Character.isWhitespace(c)) { - b.append(Character.toLowerCase(c)); - isWhitespace = false; - } else if (!isWhitespace) { - b.append(' '); - isWhitespace = true; - } - } - return b.toString().trim(); - } -// -// public static String normalizeSameCase(String s) { -// if (noString(s)) -// return null; -// StringBuilder b = new StringBuilder(); -// boolean isWhitespace = false; -// for (int i = 0; i < s.length(); i++) { -// char c = s.charAt(i); -// if (!Character.isWhitespace(c)) { -// b.append(c); -// isWhitespace = false; -// } else if (!isWhitespace) { -// b.append(' '); -// isWhitespace = true; -// } -// } -// return b.toString().trim(); -// } -// -// -// public static void copyFileToDirectory(File source, File destDir) throws IOException { -// copyFile(source, new File(path(destDir.getAbsolutePath(), source.getName()))); -// } -// -// -// public static boolean isWhitespace(String s) { -// boolean ok = true; -// for (int i = 0; i < s.length(); i++) -// ok = ok && Character.isWhitespace(s.charAt(i)); -// return ok; -// -// } -// -// -// public static String URLEncode(String string) { -// try { -// return URLEncoder.encode(string, "UTF-8"); -// } catch (UnsupportedEncodingException e) { -// throw new Error(e.getMessage()); -// } -// } -// -// - public static boolean charInSet(char value, char... array) { - for (int i : array) - if (value == i) - return true; - return false; - } -// -// -// public static boolean charInRange(char ch, char a, char z) { -// return ch >= a && ch <= z; -// } -// - public static boolean existsInList(String value, String... array) { - if (value == null) - return false; - for (String s : array) - if (value.equals(s)) - return true; - return false; - } + StringBuilder b = new StringBuilder(); + boolean isWhitespace = false; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (!Character.isWhitespace(c)) { + b.append(Character.toLowerCase(c)); + isWhitespace = false; + } else if (!isWhitespace) { + b.append(' '); + isWhitespace = true; + } + } + return b.toString().trim(); + } + // + // public static String normalizeSameCase(String s) { + // if (noString(s)) + // return null; + // StringBuilder b = new StringBuilder(); + // boolean isWhitespace = false; + // for (int i = 0; i < s.length(); i++) { + // char c = s.charAt(i); + // if (!Character.isWhitespace(c)) { + // b.append(c); + // isWhitespace = false; + // } else if (!isWhitespace) { + // b.append(' '); + // isWhitespace = true; + // } + // } + // return b.toString().trim(); + // } + // + // + // public static void copyFileToDirectory(File source, File destDir) throws IOException { + // copyFile(source, new File(path(destDir.getAbsolutePath(), source.getName()))); + // } + // + // + // public static boolean isWhitespace(String s) { + // boolean ok = true; + // for (int i = 0; i < s.length(); i++) + // ok = ok && Character.isWhitespace(s.charAt(i)); + // return ok; + // + // } + // + // + // public static String URLEncode(String string) { + // try { + // return URLEncoder.encode(string, "UTF-8"); + // } catch (UnsupportedEncodingException e) { + // throw new Error(e.getMessage()); + // } + // } + // + // + public static boolean charInSet(char value, char... array) { + for (int i : array) + if (value == i) + return true; + return false; + } + // + // + // public static boolean charInRange(char ch, char a, char z) { + // return ch >= a && ch <= z; + // } + // + public static boolean existsInList(String value, String... array) { + if (value == null) + return false; + for (String s : array) + if (value.equals(s)) + return true; + return false; + } - public static boolean existsInList(int value, int... array) { - for (int i : array) - if (value == i) - return true; - return false; - } + public static boolean existsInList(int value, int... array) { + for (int i : array) + if (value == i) + return true; + return false; + } - public static boolean existsInListNC(String value, String... array) { - for (String s : array) - if (value.equalsIgnoreCase(s)) - return true; - return false; - } -// -// -// public static String getFileNameForName(String name) { -// return name.toLowerCase(); -// } -// -// public static void deleteTempFiles() throws IOException { -// File file = createTempFile("test", "test"); -// String folder = getDirectoryForFile(file.getAbsolutePath()); -// String[] list = new File(folder).list(new FilenameFilter() { -// public boolean accept(File dir, String name) { -// return name.startsWith("ohfu-"); -// } -// }); -// if (list != null) { -// for (String n : list) { -// new File(path(folder, n)).delete(); -// } -// } -// } -// -// public static File createTempFile(String prefix, String suffix) throws IOException { -// // this allows use to eaily identify all our dtemp files and delete them, since delete on Exit doesn't really work. -// File file = File.createTempFile("ohfu-"+prefix, suffix); -// file.deleteOnExit(); -// return file; -// } -// -// -// public static boolean isAsciiChar(char ch) { -// return ch >= ' ' && ch <= '~'; -// } -// -// -// public static String makeUuidUrn() { -// return "urn:uuid:"+UUID.randomUUID().toString().toLowerCase(); -// } -// - public static boolean isURL(String s) { - boolean ok = s.matches("^http(s{0,1})://[a-zA-Z0-9_/\\-\\.]+\\.([A-Za-z/]{2,5})[a-zA-Z0-9_/\\&\\?\\=\\-\\.\\~\\%]*"); - return ok; - } -// -// -// public static String escapeJson(String value) { -// if (value == null) -// return ""; -// -// StringBuilder b = new StringBuilder(); -// for (char c : value.toCharArray()) { -// if (c == '\r') -// b.append("\\r"); -// else if (c == '\n') -// b.append("\\n"); -// else if (c == '"') -// b.append("\\\""); -// else if (c == '\'') -// b.append("\\'"); -// else if (c == '\\') -// b.append("\\\\"); -// else -// b.append(c); -// } -// return b.toString(); -// } -// -// public static String humanize(String code) { -// StringBuilder b = new StringBuilder(); -// boolean lastBreak = true; -// for (char c : code.toCharArray()) { -// if (Character.isLetter(c)) { -// if (lastBreak) -// b.append(Character.toUpperCase(c)); -// else { -// if (Character.isUpperCase(c)) -// b.append(" "); -// b.append(c); -// } -// lastBreak = false; -// } else { -// b.append(" "); -// lastBreak = true; -// } -// } -// if (b.length() == 0) -// return code; -// else -// return b.toString(); -// } -// -// - public static String uncapitalize(String s) { - if( s == null ) return null; - if( s.length() == 0 ) return s; - if( s.length() == 1 ) return s.toLowerCase(); - - return s.substring(0, 1).toLowerCase() + s.substring(1); - } + public static boolean existsInListNC(String value, String... array) { + for (String s : array) + if (value.equalsIgnoreCase(s)) + return true; + return false; + } + // + // + // public static String getFileNameForName(String name) { + // return name.toLowerCase(); + // } + // + // public static void deleteTempFiles() throws IOException { + // File file = createTempFile("test", "test"); + // String folder = getDirectoryForFile(file.getAbsolutePath()); + // String[] list = new File(folder).list(new FilenameFilter() { + // public boolean accept(File dir, String name) { + // return name.startsWith("ohfu-"); + // } + // }); + // if (list != null) { + // for (String n : list) { + // new File(path(folder, n)).delete(); + // } + // } + // } + // + // public static File createTempFile(String prefix, String suffix) throws IOException { + // // this allows use to eaily identify all our dtemp files and delete them, since delete on Exit doesn't really work. + // File file = File.createTempFile("ohfu-"+prefix, suffix); + // file.deleteOnExit(); + // return file; + // } + // + // + // public static boolean isAsciiChar(char ch) { + // return ch >= ' ' && ch <= '~'; + // } + // + // + // public static String makeUuidUrn() { + // return "urn:uuid:"+UUID.randomUUID().toString().toLowerCase(); + // } + // + public static boolean isURL(String s) { + boolean ok = s.matches("^http(s{0,1})://[a-zA-Z0-9_/\\-\\.]+\\.([A-Za-z/]{2,5})[a-zA-Z0-9_/\\&\\?\\=\\-\\.\\~\\%]*"); + return ok; + } + // + // + // public static String escapeJson(String value) { + // if (value == null) + // return ""; + // + // StringBuilder b = new StringBuilder(); + // for (char c : value.toCharArray()) { + // if (c == '\r') + // b.append("\\r"); + // else if (c == '\n') + // b.append("\\n"); + // else if (c == '"') + // b.append("\\\""); + // else if (c == '\'') + // b.append("\\'"); + // else if (c == '\\') + // b.append("\\\\"); + // else + // b.append(c); + // } + // return b.toString(); + // } + // + // public static String humanize(String code) { + // StringBuilder b = new StringBuilder(); + // boolean lastBreak = true; + // for (char c : code.toCharArray()) { + // if (Character.isLetter(c)) { + // if (lastBreak) + // b.append(Character.toUpperCase(c)); + // else { + // if (Character.isUpperCase(c)) + // b.append(" "); + // b.append(c); + // } + // lastBreak = false; + // } else { + // b.append(" "); + // lastBreak = true; + // } + // } + // if (b.length() == 0) + // return code; + // else + // return b.toString(); + // } + // + // + public static String uncapitalize(String s) { + if( s == null ) return null; + if( s.length() == 0 ) return s; + if( s.length() == 1 ) return s.toLowerCase(); + + return s.substring(0, 1).toLowerCase() + s.substring(1); + } - public static int charCount(String s, char c) { - int res = 0; - for (char ch : s.toCharArray()) - if (ch == c) - res++; - return res; - } + public static int charCount(String s, char c) { + int res = 0; + for (char ch : s.toCharArray()) + if (ch == c) + res++; + return res; + } -// -// // http://stackoverflow.com/questions/3780406/how-to-play-a-sound-alert-in-a-java-application -// public static float SAMPLE_RATE = 8000f; -// -// public static void tone(int hz, int msecs) { -// tone(hz, msecs, 1.0); -// } -// -// public static void tone(int hz, int msecs, double vol) { -// try { -// byte[] buf = new byte[1]; -// AudioFormat af = -// new AudioFormat( -// SAMPLE_RATE, // sampleRate -// 8, // sampleSizeInBits -// 1, // channels -// true, // signed -// false); // bigEndian -// SourceDataLine sdl; -// sdl = AudioSystem.getSourceDataLine(af); -// sdl.open(af); -// sdl.start(); -// for (int i=0; i < msecs*8; i++) { -// double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI; -// buf[0] = (byte)(Math.sin(angle) * 127.0 * vol); -// sdl.write(buf,0,1); -// } -// sdl.drain(); -// sdl.stop(); -// sdl.close(); -// } catch (Exception e) { -// } -// } -// -// -// public static boolean isOid(String cc) { -// return cc.matches(OID_REGEX) && cc.lastIndexOf('.') > 5; -// } -// -// -// public static boolean equals(String one, String two) { -// if (one == null && two == null) -// return true; -// if (one == null || two == null) -// return false; -// return one.equals(two); -// } -// -// -// public static void deleteAllFiles(String folder, String type) { -// File src = new File(folder); -// String[] files = src.list(); -// for (String f : files) { -// if (new File(folder+File.separator+f).isDirectory()) { -// deleteAllFiles(folder+File.separator+f, type); -// } else if (f.endsWith(type)) { -// new File(folder+File.separator+f).delete(); -// } -// } -// -// } -// -// public static boolean compareIgnoreWhitespace(File f1, File f2) throws IOException { -// InputStream in1 = null; -// InputStream in2 = null; -// try { -// in1 = new BufferedInputStream(new FileInputStream(f1)); -// in2 = new BufferedInputStream(new FileInputStream(f2)); -// -// int expectedByte = in1.read(); -// while (expectedByte != -1) { -// boolean w1 = isWhitespace(expectedByte); -// if (w1) -// while (isWhitespace(expectedByte)) -// expectedByte = in1.read(); -// int foundByte = in2.read(); -// if (w1) { -// if (!isWhitespace(foundByte)) -// return false; -// while (isWhitespace(foundByte)) -// foundByte = in2.read(); -// } -// if (expectedByte != foundByte) -// return false; -// expectedByte = in1.read(); -// } -// if (in2.read() != -1) { -// return false; -// } -// return true; -// } finally { -// if (in1 != null) { -// try { -// in1.close(); -// } catch (IOException e) {} -// } -// if (in2 != null) { -// try { -// in2.close(); -// } catch (IOException e) {} -// } -// } -// } -// -// private static boolean isWhitespace(int b) { -// return b == 9 || b == 10 || b == 13 || b == 32; -// } -// -// -// public static boolean compareIgnoreWhitespace(String fn1, String fn2) throws IOException { -// return compareIgnoreWhitespace(new File(fn1), new File(fn2)); -// } -// -// - public static boolean isAbsoluteUrl(String ref) { - return ref != null && ref.startsWith("http:") || ref.startsWith("https:") || ref.startsWith("urn:uuid:") || ref.startsWith("urn:oid:") ; - } + // + // // http://stackoverflow.com/questions/3780406/how-to-play-a-sound-alert-in-a-java-application + // public static float SAMPLE_RATE = 8000f; + // + // public static void tone(int hz, int msecs) { + // tone(hz, msecs, 1.0); + // } + // + // public static void tone(int hz, int msecs, double vol) { + // try { + // byte[] buf = new byte[1]; + // AudioFormat af = + // new AudioFormat( + // SAMPLE_RATE, // sampleRate + // 8, // sampleSizeInBits + // 1, // channels + // true, // signed + // false); // bigEndian + // SourceDataLine sdl; + // sdl = AudioSystem.getSourceDataLine(af); + // sdl.open(af); + // sdl.start(); + // for (int i=0; i < msecs*8; i++) { + // double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI; + // buf[0] = (byte)(Math.sin(angle) * 127.0 * vol); + // sdl.write(buf,0,1); + // } + // sdl.drain(); + // sdl.stop(); + // sdl.close(); + // } catch (Exception e) { + // } + // } + // + // + // public static boolean isOid(String cc) { + // return cc.matches(OID_REGEX) && cc.lastIndexOf('.') > 5; + // } + // + // + // public static boolean equals(String one, String two) { + // if (one == null && two == null) + // return true; + // if (one == null || two == null) + // return false; + // return one.equals(two); + // } + // + // + // public static void deleteAllFiles(String folder, String type) { + // File src = new File(folder); + // String[] files = src.list(); + // for (String f : files) { + // if (new File(folder+File.separator+f).isDirectory()) { + // deleteAllFiles(folder+File.separator+f, type); + // } else if (f.endsWith(type)) { + // new File(folder+File.separator+f).delete(); + // } + // } + // + // } + // + // public static boolean compareIgnoreWhitespace(File f1, File f2) throws IOException { + // InputStream in1 = null; + // InputStream in2 = null; + // try { + // in1 = new BufferedInputStream(new FileInputStream(f1)); + // in2 = new BufferedInputStream(new FileInputStream(f2)); + // + // int expectedByte = in1.read(); + // while (expectedByte != -1) { + // boolean w1 = isWhitespace(expectedByte); + // if (w1) + // while (isWhitespace(expectedByte)) + // expectedByte = in1.read(); + // int foundByte = in2.read(); + // if (w1) { + // if (!isWhitespace(foundByte)) + // return false; + // while (isWhitespace(foundByte)) + // foundByte = in2.read(); + // } + // if (expectedByte != foundByte) + // return false; + // expectedByte = in1.read(); + // } + // if (in2.read() != -1) { + // return false; + // } + // return true; + // } finally { + // if (in1 != null) { + // try { + // in1.close(); + // } catch (IOException e) {} + // } + // if (in2 != null) { + // try { + // in2.close(); + // } catch (IOException e) {} + // } + // } + // } + // + // private static boolean isWhitespace(int b) { + // return b == 9 || b == 10 || b == 13 || b == 32; + // } + // + // + // public static boolean compareIgnoreWhitespace(String fn1, String fn2) throws IOException { + // return compareIgnoreWhitespace(new File(fn1), new File(fn2)); + // } + // + // + public static boolean isAbsoluteUrl(String ref) { + //FIXME null access on ref cause by OR clause. + return ref != null && ref.startsWith("http:") || ref.startsWith("https:") || ref.startsWith("urn:uuid:") || ref.startsWith("urn:oid:") ; + } - public static boolean equivalent(String l, String r) { - if (Utilities.noString(l) && Utilities.noString(r)) - return true; - if (Utilities.noString(l) || Utilities.noString(r)) - return false; - return l.toLowerCase().equals(r.toLowerCase()); - } + public static boolean equivalent(String l, String r) { + if (Utilities.noString(l) && Utilities.noString(r)) + return true; + if (Utilities.noString(l) || Utilities.noString(r)) + return false; + return l.toLowerCase().equals(r.toLowerCase()); + } - public static boolean equivalentNumber(String l, String r) { - if (Utilities.noString(l) && Utilities.noString(r)) - return true; - if (Utilities.noString(l) || Utilities.noString(r)) - return false; - l = l.toLowerCase().trim(); - r = r.toLowerCase().trim(); // not that this should make any difference - return l.startsWith(r) || r.startsWith(l); - } -// -// -// public static String getFileExtension(String fn) { -// return fn.contains(".") ? fn.substring(fn.lastIndexOf(".")+1) : ""; -// } -// -// -// public static String unCamelCase(String name) { -// StringBuilder b = new StringBuilder(); -// boolean first = true; -// for (char c : name.toCharArray()) { -// if (Character.isUpperCase(c)) { -// if (!first) -// b.append(" "); -// b.append(Character.toLowerCase(c)); -// } else -// b.append(c); -// first = false; -// } -// return b.toString(); -// } -// -// -// public static boolean isAbsoluteFileName(String source) { -// if (isWindows()) -// return (source.length() > 2 && source.charAt(1) == ':') || source.startsWith("\\\\"); -// else -// return source.startsWith("//"); -// } -// -// -// private static boolean isWindows() { -// return System.getProperty("os.name").startsWith("Windows"); -// } -// -// + public static boolean equivalentNumber(String l, String r) { + if (Utilities.noString(l) && Utilities.noString(r)) + return true; + if (Utilities.noString(l) || Utilities.noString(r)) + return false; + l = l.toLowerCase().trim(); + r = r.toLowerCase().trim(); // not that this should make any difference + return l.startsWith(r) || r.startsWith(l); + } + // + // + // public static String getFileExtension(String fn) { + // return fn.contains(".") ? fn.substring(fn.lastIndexOf(".")+1) : ""; + // } + // + // + // public static String unCamelCase(String name) { + // StringBuilder b = new StringBuilder(); + // boolean first = true; + // for (char c : name.toCharArray()) { + // if (Character.isUpperCase(c)) { + // if (!first) + // b.append(" "); + // b.append(Character.toLowerCase(c)); + // } else + // b.append(c); + // first = false; + // } + // return b.toString(); + // } + // + // + // public static boolean isAbsoluteFileName(String source) { + // if (isWindows()) + // return (source.length() > 2 && source.charAt(1) == ':') || source.startsWith("\\\\"); + // else + // return source.startsWith("//"); + // } + // + // + // private static boolean isWindows() { + // return System.getProperty("os.name").startsWith("Windows"); + // } + // + // } diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/ucum/Decimal.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/ucum/Decimal.java index 2728f61e9cd..8d7f34bf371 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/ucum/Decimal.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/ucum/Decimal.java @@ -175,10 +175,10 @@ public class Decimal { } private String delete(String value, int offset, int length) { - if (offset == 0) + if (offset == 0){ return value.substring(length); - else - return value.substring(0, offset)+value.substring(offset+length); + } + return value.substring(0, offset)+value.substring(offset+length); } private void setValueScientific(String value) throws UcumException { @@ -214,10 +214,10 @@ public class Decimal { } private String insert(String ins, String value, int offset) { - if (offset == 0) + if (offset == 0) { return ins+value; - else - return value.substring(0, offset)+ins+value.substring(offset); + } + return value.substring(0, offset)+ins+value.substring(offset); } @Override @@ -515,10 +515,10 @@ public class Decimal { int t = c + (dig(s1.charAt(i)) - dig(s2.charAt(i))); if (t < 0) { t = t + 10; - if (i == 0) + if (i == 0) { throw new Error("internal logic error"); - else - s1 = replaceChar(s1, i-1, cdig(dig(s1.charAt(i-1))-1)); + } + s1 = replaceChar(s1, i-1, cdig(dig(s1.charAt(i-1))-1)); } result[i] = cdig(t); } @@ -527,10 +527,10 @@ public class Decimal { } private String replaceChar(String s, int offset, char c) { - if (offset == 0) + if (offset == 0){ return String.valueOf(c)+s.substring(1); - else - return s.substring(0, offset)+c+s.substring(offset+1); + } + return s.substring(0, offset)+c+s.substring(offset+1); } @@ -772,10 +772,10 @@ public class Decimal { int i = 0; while (i < s.length() && s.charAt(i) == '0') i++; - if (i == s.length()) + if (i == s.length()){ return "0"; - else - return s.substring(i); + } + return s.substring(i); } public Decimal divInt(Decimal other) throws UcumException { diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/HierarchicalTableGenerator.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/HierarchicalTableGenerator.java index ef0d90139d2..88ba6ac1080 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/HierarchicalTableGenerator.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/HierarchicalTableGenerator.java @@ -180,28 +180,28 @@ public class HierarchicalTableGenerator { pieces.add(piece); return this; } - private List htmlToParagraphPieces(String html) { - List myPieces = new ArrayList(); - String[] paragraphs = html.replace("

", "").split("<\\/p>|
"); - for (int i=0;i htmlFormattingToPieces(String html) { - List myPieces = new ArrayList(); - //Todo: At least handle bold and italics and turn them into formatted spans. (Will need to handle nesting though) - myPieces.add(new Piece(null, html, null)); - - return myPieces; - } +// private List htmlToParagraphPieces(String html) { +// List myPieces = new ArrayList(); +// String[] paragraphs = html.replace("

", "").split("<\\/p>|
"); +// for (int i=0;i htmlFormattingToPieces(String html) { +// List myPieces = new ArrayList(); +// //Todo: At least handle bold and italics and turn them into formatted spans. (Will need to handle nesting though) +// myPieces.add(new Piece(null, html, null)); +// +// return myPieces; +// } public void addStyle(String style) { for (Piece p : pieces) p.addStyle(style); @@ -507,8 +507,8 @@ public class HierarchicalTableGenerator { b.append(new String(Base64.encodeBase64(bytes))); // files.put(filename, b.toString()); return b.toString(); - } else - return corePrefix+filename; + } + return corePrefix+filename; } @@ -558,22 +558,22 @@ public class HierarchicalTableGenerator { b.append(new String(encodeBase64)); files.put(filename, b.toString()); return b.toString(); - } else { - b.append("tbl_bck"); - for (Boolean i : indents) - b.append(i ? "0" : "1"); - if (hasChildren) - b.append("1"); - else - b.append("0"); - b.append(".png"); - String file = Utilities.path(dest, b.toString()); - if (!new File(file).exists()) { - FileOutputStream stream = new FileOutputStream(file); - genImage(indents, hasChildren, stream); - } - return b.toString(); } + b.append("tbl_bck"); + for (Boolean i : indents) + b.append(i ? "0" : "1"); + if (hasChildren) + b.append("1"); + else + b.append("0"); + b.append(".png"); + String file = Utilities.path(dest, b.toString()); + if (!new File(file).exists()) { + //FIXME resource leak + FileOutputStream stream = new FileOutputStream(file); + genImage(indents, hasChildren, stream); + } + return b.toString(); } diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/XhtmlDocument.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/XhtmlDocument.java index 114f187c296..a4c6b19fbdf 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/XhtmlDocument.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/XhtmlDocument.java @@ -25,7 +25,7 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ package org.hl7.fhir.utilities.xhtml; /* @@ -51,15 +51,17 @@ package org.hl7.fhir.utilities.xhtml; public class XhtmlDocument extends XhtmlNode { - public XhtmlDocument() { - super(NodeType.Document); - } + private static final long serialVersionUID = -5061185698841745693L; - public XhtmlNode getDocumentElement() { - for (XhtmlNode n : getChildNodes()) { - if (n.getNodeType() == NodeType.Element) - return n; - } - return null; - } + public XhtmlDocument() { + super(NodeType.Document); + } + + public XhtmlNode getDocumentElement() { + for (XhtmlNode n : getChildNodes()) { + if (n.getNodeType() == NodeType.Element) + return n; + } + return null; + } } diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/XhtmlNode.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/XhtmlNode.java index 4dac3bc76d5..a263b3d945c 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/XhtmlNode.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/XhtmlNode.java @@ -25,7 +25,7 @@ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWIS ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ + */ package org.hl7.fhir.utilities.xhtml; /* @@ -62,268 +62,268 @@ import ca.uhn.fhir.model.primitive.XhtmlDt; @ca.uhn.fhir.model.api.annotation.DatatypeDef(name="xhtml") public class XhtmlNode implements IBaseXhtml { - private static final long serialVersionUID = -4362547161441436492L; + private static final long serialVersionUID = -4362547161441436492L; - public static class Location { - private int line; - private int column; - public Location(int line, int column) { - super(); - this.line = line; - this.column = column; - } - public int getLine() { - return line; - } - public int getColumn() { - return column; - } - @Override - public String toString() { - return "Line "+Integer.toString(line)+", column "+Integer.toString(column); - } - } + public static class Location { + private int line; + private int column; + public Location(int line, int column) { + super(); + this.line = line; + this.column = column; + } + public int getLine() { + return line; + } + public int getColumn() { + return column; + } + @Override + public String toString() { + return "Line "+Integer.toString(line)+", column "+Integer.toString(column); + } + } - public static final String NBSP = Character.toString((char)0xa0); + public static final String NBSP = Character.toString((char)0xa0); private static final String DECL_XMLNS = " xmlns=\"http://www.w3.org/1999/xhtml\""; - - private Location location; - private NodeType nodeType; - private String name; - private Map attributes = new HashMap(); - private List childNodes = new ArrayList(); - private String content; - public XhtmlNode() { - super(); - } + private Location location; + private NodeType nodeType; + private String name; + private Map attributes = new HashMap(); + private List childNodes = new ArrayList(); + private String content; - - public XhtmlNode(NodeType nodeType, String name) { - super(); - this.nodeType = nodeType; - this.name = name; - } + public XhtmlNode() { + super(); + } - public XhtmlNode(NodeType nodeType) { - super(); - this.nodeType = nodeType; - } - public NodeType getNodeType() { - return nodeType; - } + public XhtmlNode(NodeType nodeType, String name) { + super(); + this.nodeType = nodeType; + this.name = name; + } - public void setNodeType(NodeType nodeType) { - this.nodeType = nodeType; - } + public XhtmlNode(NodeType nodeType) { + super(); + this.nodeType = nodeType; + } - public String getName() { - return name; - } + public NodeType getNodeType() { + return nodeType; + } - public void setName(String name) { - assert name.contains(":") == false : "Name should not contain any : but was " + name; - this.name = name; - } + public void setNodeType(NodeType nodeType) { + this.nodeType = nodeType; + } - public Map getAttributes() { - return attributes; - } + public String getName() { + return name; + } - public List getChildNodes() { - return childNodes; - } + public void setName(String name) { + assert name.contains(":") == false : "Name should not contain any : but was " + name; + this.name = name; + } - public String getContent() { - return content; - } + public Map getAttributes() { + return attributes; + } - public XhtmlNode setContent(String content) { - if (!(nodeType != NodeType.Text || nodeType != NodeType.Comment)) - throw new Error("Wrong node type"); - this.content = content; - return this; - } + public List getChildNodes() { + return childNodes; + } - public XhtmlNode addTag(String name) - { + public String getContent() { + return content; + } - if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) - throw new Error("Wrong node type. is "+nodeType.toString()); - XhtmlNode node = new XhtmlNode(NodeType.Element); - node.setName(name); - childNodes.add(node); - return node; - } + public XhtmlNode setContent(String content) { + if (!(nodeType != NodeType.Text || nodeType != NodeType.Comment)) + throw new Error("Wrong node type"); + this.content = content; + return this; + } - public XhtmlNode addTag(int index, String name) - { + public XhtmlNode addTag(String name) + { - if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) - throw new Error("Wrong node type. is "+nodeType.toString()); - XhtmlNode node = new XhtmlNode(NodeType.Element); - node.setName(name); - childNodes.add(index, node); - return node; - } + if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) + throw new Error("Wrong node type. is "+nodeType.toString()); + XhtmlNode node = new XhtmlNode(NodeType.Element); + node.setName(name); + childNodes.add(node); + return node; + } - public XhtmlNode addComment(String content) - { - if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) - throw new Error("Wrong node type"); - XhtmlNode node = new XhtmlNode(NodeType.Comment); - node.setContent(content); - childNodes.add(node); - return node; - } + public XhtmlNode addTag(int index, String name) + { - public XhtmlNode addDocType(String content) - { - if (!(nodeType == NodeType.Document)) - throw new Error("Wrong node type"); - XhtmlNode node = new XhtmlNode(NodeType.DocType); - node.setContent(content); - childNodes.add(node); - return node; - } + if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) + throw new Error("Wrong node type. is "+nodeType.toString()); + XhtmlNode node = new XhtmlNode(NodeType.Element); + node.setName(name); + childNodes.add(index, node); + return node; + } - public XhtmlNode addInstruction(String content) - { - if (!(nodeType == NodeType.Document)) - throw new Error("Wrong node type"); - XhtmlNode node = new XhtmlNode(NodeType.Instruction); - node.setContent(content); - childNodes.add(node); - return node; - } + public XhtmlNode addComment(String content) + { + if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) + throw new Error("Wrong node type"); + XhtmlNode node = new XhtmlNode(NodeType.Comment); + node.setContent(content); + childNodes.add(node); + return node; + } + + public XhtmlNode addDocType(String content) + { + if (!(nodeType == NodeType.Document)) + throw new Error("Wrong node type"); + XhtmlNode node = new XhtmlNode(NodeType.DocType); + node.setContent(content); + childNodes.add(node); + return node; + } + + public XhtmlNode addInstruction(String content) + { + if (!(nodeType == NodeType.Document)) + throw new Error("Wrong node type"); + XhtmlNode node = new XhtmlNode(NodeType.Instruction); + node.setContent(content); + childNodes.add(node); + return node; + } - public XhtmlNode addText(String content) - { - if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) - throw new Error("Wrong node type"); - if (content != null) { - XhtmlNode node = new XhtmlNode(NodeType.Text); - node.setContent(content); - childNodes.add(node); - return node; - } else - return null; - } + public XhtmlNode addText(String content) + { + if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) + throw new Error("Wrong node type"); + if (content != null) { + XhtmlNode node = new XhtmlNode(NodeType.Text); + node.setContent(content); + childNodes.add(node); + return node; + } + return null; + } - public XhtmlNode addText(int index, String content) - { - if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) - throw new Error("Wrong node type"); - if (content == null) - throw new Error("Content cannot be null"); - - XhtmlNode node = new XhtmlNode(NodeType.Text); - node.setContent(content); - childNodes.add(index, node); - return node; - } + public XhtmlNode addText(int index, String content) + { + if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) + throw new Error("Wrong node type"); + if (content == null) + throw new Error("Content cannot be null"); - public boolean allChildrenAreText() - { - boolean res = true; - for (XhtmlNode n : childNodes) - res = res && n.getNodeType() == NodeType.Text; - return res; - } + XhtmlNode node = new XhtmlNode(NodeType.Text); + node.setContent(content); + childNodes.add(index, node); + return node; + } - public XhtmlNode getElement(String name) - { - for (XhtmlNode n : childNodes) - if (n.getNodeType() == NodeType.Element && name.equals(n.getName())) - return n; - return null; - } + public boolean allChildrenAreText() + { + boolean res = true; + for (XhtmlNode n : childNodes) + res = res && n.getNodeType() == NodeType.Text; + return res; + } - public XhtmlNode getFirstElement() - { - for (XhtmlNode n : childNodes) - if (n.getNodeType() == NodeType.Element) - return n; - return null; - } + public XhtmlNode getElement(String name) + { + for (XhtmlNode n : childNodes) + if (n.getNodeType() == NodeType.Element && name.equals(n.getName())) + return n; + return null; + } - public String allText() { - StringBuilder b = new StringBuilder(); - for (XhtmlNode n : childNodes) - if (n.getNodeType() == NodeType.Text) - b.append(n.getContent()); - else if (n.getNodeType() == NodeType.Element) - b.append(n.allText()); - return b.toString(); - } + public XhtmlNode getFirstElement() + { + for (XhtmlNode n : childNodes) + if (n.getNodeType() == NodeType.Element) + return n; + return null; + } - public XhtmlNode attribute(String name, String value) { - if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) - throw new Error("Wrong node type"); - if (name == null) - throw new Error("name is null"); - if (value == null) - throw new Error("value is null"); - attributes.put(name, value); - return this; - } + public String allText() { + StringBuilder b = new StringBuilder(); + for (XhtmlNode n : childNodes) + if (n.getNodeType() == NodeType.Text) + b.append(n.getContent()); + else if (n.getNodeType() == NodeType.Element) + b.append(n.allText()); + return b.toString(); + } - public boolean hasAttribute(String name) { - return getAttributes().containsKey(name); - } + public XhtmlNode attribute(String name, String value) { + if (!(nodeType == NodeType.Element || nodeType == NodeType.Document)) + throw new Error("Wrong node type"); + if (name == null) + throw new Error("name is null"); + if (value == null) + throw new Error("value is null"); + attributes.put(name, value); + return this; + } - public String getAttribute(String name) { - return getAttributes().get(name); - } + public boolean hasAttribute(String name) { + return getAttributes().containsKey(name); + } - public XhtmlNode setAttribute(String name, String value) { - getAttributes().put(name, value); - return this; - } - - public XhtmlNode copy() { - XhtmlNode dst = new XhtmlNode(nodeType); - dst.name = name; - for (String n : attributes.keySet()) { - dst.attributes.put(n, attributes.get(n)); - } - for (XhtmlNode n : childNodes) - dst.childNodes.add(n.copy()); - dst.content = content; - return dst; - } + public String getAttribute(String name) { + return getAttributes().get(name); + } + + public XhtmlNode setAttribute(String name, String value) { + getAttributes().put(name, value); + return this; + } + + public XhtmlNode copy() { + XhtmlNode dst = new XhtmlNode(nodeType); + dst.name = name; + for (String n : attributes.keySet()) { + dst.attributes.put(n, attributes.get(n)); + } + for (XhtmlNode n : childNodes) + dst.childNodes.add(n.copy()); + dst.content = content; + return dst; + } @Override public boolean isEmpty() { - return (childNodes == null || childNodes.isEmpty()) && content == null; - } + return (childNodes == null || childNodes.isEmpty()) && content == null; + } public boolean equalsDeep(XhtmlNode other) { - if (other == null) { - return false; - } + if (other == null) { + return false; + } - if (!(nodeType == other.nodeType) || !compare(name, other.name) || !compare(content, other.content)) - return false; - if (attributes.size() != other.attributes.size()) - return false; - for (String an : attributes.keySet()) - if (!attributes.get(an).equals(other.attributes.get(an))) - return false; - if (childNodes.size() != other.childNodes.size()) - return false; + if (!(nodeType == other.nodeType) || !compare(name, other.name) || !compare(content, other.content)) + return false; + if (attributes.size() != other.attributes.size()) + return false; + for (String an : attributes.keySet()) + if (!attributes.get(an).equals(other.attributes.get(an))) + return false; + if (childNodes.size() != other.childNodes.size()) + return false; for (int i = 0; i < childNodes.size(); i++) { if (!compareDeep(childNodes.get(i), other.childNodes.get(i))) return false; } return true; - } + } private boolean compare(String s1, String s2) { if (s1 == null && s2 == null) @@ -331,7 +331,7 @@ public class XhtmlNode implements IBaseXhtml { if (s1 == null || s2 == null) return false; return s1.equals(s2); - } + } private static boolean compareDeep(XhtmlNode e1, XhtmlNode e2) { if (e1 == null && e2 == null) @@ -339,18 +339,18 @@ public class XhtmlNode implements IBaseXhtml { if (e1 == null || e2 == null) return false; return e1.equalsDeep(e2); - } - - public String getNsDecl() { - for (String an : attributes.keySet()) { - if (an.equals("xmlns")) { - return attributes.get(an); - } - } - return null; - } - - + } + + public String getNsDecl() { + for (String an : attributes.keySet()) { + if (an.equals("xmlns")) { + return attributes.get(an); + } + } + return null; + } + + @Override public String getValueAsString() { if (isEmpty()) { @@ -376,9 +376,9 @@ public class XhtmlNode implements IBaseXhtml { if (isBlank(theValue)) { return; } - + String val = theValue.trim(); - + if (!val.startsWith("<")) { val = "" + val + ""; } @@ -387,7 +387,7 @@ public class XhtmlNode implements IBaseXhtml { } val = XhtmlDt.preprocessXhtmlNamespaceDeclaration(val); - + try { // TODO: this is ugly XhtmlNode fragment = new XhtmlParser().parseFragment(val); @@ -400,61 +400,64 @@ public class XhtmlNode implements IBaseXhtml { // TODO: composer shouldn't throw exception like this throw new RuntimeException(e); } - + } - public XhtmlNode getElementByIndex(int i) { - int c = 0; - for (XhtmlNode n : childNodes) - if (n.getNodeType() == NodeType.Element) { - if (c == i) - return n; - else - c++; - } - return null; - } + public XhtmlNode getElementByIndex(int i) { + int c = 0; + for (XhtmlNode n : childNodes) + if (n.getNodeType() == NodeType.Element) { + if (c == i){ + return n; + } + c++; + } + return null; + } -@Override -public String getValue() { - return getValueAsString(); -} + @Override + public String getValue() { + return getValueAsString(); + } -@Override -public XhtmlNode setValue(String theValue) throws IllegalArgumentException { - setValueAsString(theValue); - return this; -} + @Override + public XhtmlNode setValue(String theValue) throws IllegalArgumentException { + setValueAsString(theValue); + return this; + } -/** - * Returns false - */ -public boolean hasFormatComment() { - return false; -} + /** + * Returns false + */ + @Override + public boolean hasFormatComment() { + return false; + } -/** - * NOT SUPPORTED - Throws {@link UnsupportedOperationException} - */ -public List getFormatCommentsPre() { - throw new UnsupportedOperationException(); -} + /** + * NOT SUPPORTED - Throws {@link UnsupportedOperationException} + */ + @Override + public List getFormatCommentsPre() { + throw new UnsupportedOperationException(); + } -/** - * NOT SUPPORTED - Throws {@link UnsupportedOperationException} - */ -public List getFormatCommentsPost() { - throw new UnsupportedOperationException(); -} + /** + * NOT SUPPORTED - Throws {@link UnsupportedOperationException} + */ + @Override + public List getFormatCommentsPost() { + throw new UnsupportedOperationException(); + } -public Location getLocation() { - return location; -} + public Location getLocation() { + return location; + } -public void setLocation(Location location) { - this.location = location; -} + public void setLocation(Location location) { + this.location = location; + } } diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/XhtmlParser.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/XhtmlParser.java index 1a54dc7db73..dda22dde031 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/XhtmlParser.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xhtml/XhtmlParser.java @@ -227,17 +227,17 @@ public class XhtmlParser { if (validatorMode) return true; boolean ok = attributes.contains(attr) || attributes.contains(elem + "." + attr); - if (ok) + if (ok) { return true; - else - switch (policy) { - case Accept: - return true; - case Drop: - return false; - case Reject: - throw new FHIRFormatError("Illegal HTML attribute " + elem + "." + attr); - } + } + switch (policy) { + case Accept: + return true; + case Drop: + return false; + case Reject: + throw new FHIRFormatError("Illegal HTML attribute " + elem + "." + attr); + } if ((elem + "." + attr).equals("img.src") && !(value.startsWith("#") || value.startsWith("http:") || value.startsWith("https:"))) { switch (policy) { @@ -306,17 +306,17 @@ public class XhtmlParser { if (validatorMode) return true; boolean ok = elements.contains(name); - if (ok) + if (ok){ return true; - else - switch (policy) { - case Accept: - return true; - case Drop: - return false; - case Reject: - throw new FHIRFormatError("Illegal HTML element " + name); - } + } + switch (policy) { + case Accept: + return true; + case Drop: + return false; + case Reject: + throw new FHIRFormatError("Illegal HTML element " + name); + } return false; } @@ -458,26 +458,25 @@ public class XhtmlParser { else if (peekChar() == '/') { readChar(); QName n = new QName(readToTagEnd()); - if (node.getName().equals(n.getName())) + if (node.getName().equals(n.getName())){ return; - else { - if (mustBeWellFormed) - throw new FHIRFormatError("Malformed XHTML: Found \"\" expecting \"\"" + descLoc()); - for (int i = parents.size() - 1; i >= 0; i--) { - if (parents.get(i).getName().equals(n)) - unwindPoint = parents.get(i); - } - if (unwindPoint != null) { - for (int i = parents.size(); i > 0; i--) { - if (i < parents.size() && parents.get(i) == unwindPoint) - return; - if (i == parents.size()) { - parents.get(i - 1).getChildNodes().addAll(node.getChildNodes()); - node.getChildNodes().clear(); - } else { - parents.get(i - 1).getChildNodes().addAll(parents.get(i).getChildNodes()); - parents.get(i).getChildNodes().clear(); - } + } + if (mustBeWellFormed) + throw new FHIRFormatError("Malformed XHTML: Found \"\" expecting \"\"" + descLoc()); + for (int i = parents.size() - 1; i >= 0; i--) { + if (parents.get(i).getName().equals(n)) + unwindPoint = parents.get(i); + } + if (unwindPoint != null) { + for (int i = parents.size(); i > 0; i--) { + if (i < parents.size() && parents.get(i) == unwindPoint) + return; + if (i == parents.size()) { + parents.get(i - 1).getChildNodes().addAll(node.getChildNodes()); + node.getChildNodes().clear(); + } else { + parents.get(i - 1).getChildNodes().addAll(parents.get(i).getChildNodes()); + parents.get(i).getChildNodes().clear(); } } } diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xml/XMLUtil.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xml/XMLUtil.java index c943109b184..b36b8d0d704 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xml/XMLUtil.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xml/XMLUtil.java @@ -275,38 +275,37 @@ public class XMLUtil { * @return escape string */ public static String escapeXML(String rawContent, String charset, boolean isNoLines) { - if (rawContent == null) + if (rawContent == null){ return ""; - else { - StringBuffer sb = new StringBuffer(); + } + StringBuffer sb = new StringBuffer(); - for (int i = 0; i < rawContent.length(); i++) { - char ch = rawContent.charAt(i); - if (ch == '\'') - sb.append("'"); - else if (ch == '&') - sb.append("&"); - else if (ch == '"') - sb.append("""); - else if (ch == '<') - sb.append("<"); - else if (ch == '>') - sb.append(">"); - else if (ch > '~' && charset != null && charSetImpliesAscii(charset)) - // TODO - why is hashcode the only way to get the unicode number for the character - // in jre 5.0? - sb.append("&#x"+Integer.toHexString(new Character(ch).hashCode()).toUpperCase()+";"); - else if (isNoLines) { - if (ch == '\r') - sb.append(" "); - else if (ch != '\n') - sb.append(ch); - } - else + for (int i = 0; i < rawContent.length(); i++) { + char ch = rawContent.charAt(i); + if (ch == '\'') + sb.append("'"); + else if (ch == '&') + sb.append("&"); + else if (ch == '"') + sb.append("""); + else if (ch == '<') + sb.append("<"); + else if (ch == '>') + sb.append(">"); + else if (ch > '~' && charset != null && charSetImpliesAscii(charset)) + // TODO - why is hashcode the only way to get the unicode number for the character + // in jre 5.0? + sb.append("&#x"+Integer.toHexString(new Character(ch).hashCode()).toUpperCase()+";"); + else if (isNoLines) { + if (ch == '\r') + sb.append(" "); + else if (ch != '\n') sb.append(ch); } - return sb.toString(); + else + sb.append(ch); } + return sb.toString(); } public static Element getFirstChild(Element e) { @@ -435,6 +434,7 @@ public class XMLUtil { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); DocumentBuilder builder = factory.newDocumentBuilder(); + //FIXME resource leak return builder.parse(new FileInputStream(filename)); } diff --git a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xml/XMLWriter.java b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xml/XMLWriter.java index f66a0915b2c..ab739b9390d 100644 --- a/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xml/XMLWriter.java +++ b/hapi-fhir-base/src/main/java/org/hl7/fhir/utilities/xml/XMLWriter.java @@ -401,10 +401,10 @@ public class XMLWriter extends OutputStreamWriter implements IXMLWriter { @Override public String getDefaultNamespace() { XMLNamespace ns = findDefaultNamespace(); - if (ns == null) + if (ns == null) { return null; - else - return ns.getNamespace(); + } + return ns.getNamespace(); } /* (non-Javadoc) @@ -519,10 +519,10 @@ public class XMLWriter extends OutputStreamWriter implements IXMLWriter { writePendingComment(); pendingClose = false; } - - if (name == null) { - throw new IOException("name is null"); - } +//death code +// if (name == null) { +// throw new IOException("name is null"); +// } newLevelIfRequired(); levels.current().setName(name); levels.current().setNamespace(namespace); @@ -615,23 +615,22 @@ public class XMLWriter extends OutputStreamWriter implements IXMLWriter { checkStarted(); if (levels.empty()) { throw new IOException("Called exit one too many times"); + } + if (pendingClose) { + write("/>"); + writePendingComment(); + pendingClose = false; } else { - if (pendingClose) { - write("/>"); - writePendingComment(); - pendingClose = false; - } else { - if (levels.current().hasChildren()) - writePretty(); - write("'); - } - levels.pop(); + if (levels.current().hasChildren()) + writePretty(); + write("'); } + levels.pop(); } /* (non-Javadoc) @@ -830,8 +829,8 @@ public class XMLWriter extends OutputStreamWriter implements IXMLWriter { for (int i = 0; i < levels.size() - 1; i++) write(" "); return (levels.size() - 1) * 2; - } else - return 0; + } + return 0; } public int getLineType() { diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/parser/json/JsonLikeStructureTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/parser/json/JsonLikeStructureTest.java index 925340ac1b8..bc120a0e2c6 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/parser/json/JsonLikeStructureTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/parser/json/JsonLikeStructureTest.java @@ -7,11 +7,9 @@ import java.io.StringReader; import org.junit.Test; -import ca.uhn.fhir.context.FhirContext; - public class JsonLikeStructureTest { - private static FhirContext ourCtx; - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(JsonLikeStructureTest.class); +// private static FhirContext ourCtx; +// private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(JsonLikeStructureTest.class); private static final String TEST_STRUCTURELOADING_DATA = "{" + diff --git a/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/UrlUtilTest.java b/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/UrlUtilTest.java index f3b689e29ea..d55b7a9a1cc 100644 --- a/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/UrlUtilTest.java +++ b/hapi-fhir-base/src/test/java/ca/uhn/fhir/util/UrlUtilTest.java @@ -1,11 +1,11 @@ package ca.uhn.fhir.util; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; import org.junit.Test; -import ca.uhn.fhir.util.UrlUtil.UrlParts; - public class UrlUtilTest { @Test diff --git a/hapi-fhir-structures-dstu2/pom.xml b/hapi-fhir-structures-dstu2/pom.xml index f5cd1d325aa..53a0dadd33a 100644 --- a/hapi-fhir-structures-dstu2/pom.xml +++ b/hapi-fhir-structures-dstu2/pom.xml @@ -99,7 +99,7 @@ net.sf.json-lib json-lib - 2.4 + jdk15 test @@ -116,7 +116,7 @@ net.sf.json-lib json-lib - 2.4 + jdk15-sources test @@ -139,7 +139,7 @@ directory-naming naming-java - 0.8 + test diff --git a/hapi-fhir-structures-hl7org-dstu2/pom.xml b/hapi-fhir-structures-hl7org-dstu2/pom.xml index c04497c465c..95a218e25ac 100644 --- a/hapi-fhir-structures-hl7org-dstu2/pom.xml +++ b/hapi-fhir-structures-hl7org-dstu2/pom.xml @@ -121,7 +121,7 @@ net.sf.json-lib json-lib - 2.4 + jdk15 test @@ -142,7 +142,7 @@ net.sf.json-lib json-lib - 2.4 + jdk15-sources test @@ -165,7 +165,7 @@ directory-naming naming-java - 0.8 + test