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 1278f2a5e37..bbe33bf50bd 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 @@ -7,6 +7,7 @@ import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.Validate; import org.apache.commons.lang3.time.DateUtils; import org.apache.commons.lang3.time.FastDateFormat; @@ -16,14 +17,15 @@ import ca.uhn.fhir.model.api.TemporalPrecisionEnum; import ca.uhn.fhir.parser.DataFormatException; public abstract class BaseDateTimeDt extends BasePrimitive { + static final long NANOS_PER_MILLIS = 1000000L; + static final long NANOS_PER_SECOND = 1000000000L; private static final FastDateFormat ourHumanDateFormat = FastDateFormat.getDateInstance(FastDateFormat.MEDIUM); private static final FastDateFormat ourHumanDateTimeFormat = FastDateFormat.getDateTimeInstance(FastDateFormat.MEDIUM, FastDateFormat.MEDIUM); private String myFractionalSeconds; - private TemporalPrecisionEnum myPrecision = TemporalPrecisionEnum.SECOND; + private TemporalPrecisionEnum myPrecision = null; private TimeZone myTimeZone; - private boolean myTimeZoneZulu = false; /** @@ -186,11 +188,13 @@ public abstract class BaseDateTimeDt extends BasePrimitive { if (getValue() == null) { return null; } - GregorianCalendar cal = new GregorianCalendar(); - cal.setTime(getValue()); + GregorianCalendar cal; if (getTimeZone() != null) { - cal.setTimeZone(getTimeZone()); + cal = new GregorianCalendar(getTimeZone()); + } else { + cal = new GregorianCalendar(); } + cal.setTime(getValue()); return cal; } @@ -199,6 +203,9 @@ public abstract class BaseDateTimeDt extends BasePrimitive { */ abstract boolean isPrecisionAllowed(TemporalPrecisionEnum thePrecision); + /** + * Returns true if the timezone is set to GMT-0:00 (Z) + */ public boolean isTimeZoneZulu() { return myTimeZoneZulu; } @@ -213,7 +220,7 @@ public abstract class BaseDateTimeDt extends BasePrimitive { Validate.notNull(getValue(), getClass().getSimpleName() + " contains null value"); return DateUtils.isSameDay(new Date(), getValue()); } - + private void leftPadWithZeros(int theInteger, int theLength, StringBuilder theTarget) { String string = Integer.toString(theInteger); for (int i = string.length(); i < theLength; i++) { @@ -228,16 +235,16 @@ public abstract class BaseDateTimeDt extends BasePrimitive { cal.setTimeZone(TimeZone.getDefault()); String value = theValue; boolean fractionalSecondsSet = false; - - if (value.length() > 0 && (value.charAt(0) == ' ' || value.charAt(value.length()-1) == ' ')) { + + if (value.length() > 0 && (value.charAt(0) == ' ' || value.charAt(value.length() - 1) == ' ')) { value = value.trim(); } - + int length = value.length(); if (length == 0) { return null; } - + if (length < 4) { throwBadDateFormat(value); } @@ -325,7 +332,7 @@ public abstract class BaseDateTimeDt extends BasePrimitive { if (fractionalSecondsSet == false) { myFractionalSeconds = ""; } - + setPrecision(precision); return cal.getTime(); @@ -394,12 +401,12 @@ public abstract class BaseDateTimeDt extends BasePrimitive { /** * Sets the value for this type using the given Java Date object as the time, and using the default precision for - * this datatype, as well as the local timezone as determined by the local operating + * this datatype (unless the precision is already set), as well as the local timezone as determined by the local operating * system. Both of these properties may be modified in subsequent calls if neccesary. */ @Override public BaseDateTimeDt setValue(Date theValue) { - setValue(theValue, getDefaultPrecisionForDatatype()); + setValue(theValue, getPrecision()); return this; } @@ -415,7 +422,9 @@ public abstract class BaseDateTimeDt extends BasePrimitive { * @throws DataFormatException */ public void setValue(Date theValue, TemporalPrecisionEnum thePrecision) throws DataFormatException { - setTimeZone(TimeZone.getDefault()); + if (getTimeZone() == null) { + setTimeZone(TimeZone.getDefault()); + } myPrecision = thePrecision; myFractionalSeconds = ""; if (theValue != null) { @@ -490,11 +499,195 @@ public abstract class BaseDateTimeDt extends BasePrimitive { } } - private void validateLengthIsAtLeast(String theValue, int theLength) { if (theValue.length() < theLength) { throwBadDateFormat(theValue); } } + /** + * Returns the year, e.g. 2015 + */ + public Integer getYear() { + return getFieldValue(Calendar.YEAR); + } + + /** + * Returns the month with 0-index, e.g. 0=January + */ + public Integer getMonth() { + return getFieldValue(Calendar.MONTH); + } + + /** + * Returns the month with 1-index, e.g. 1=the first day of the month + */ + public Integer getDay() { + return getFieldValue(Calendar.DAY_OF_MONTH); + } + + /** + * Returns the hour of the day in a 24h clock, e.g. 13=1pm + */ + public Integer getHour() { + return getFieldValue(Calendar.HOUR_OF_DAY); + } + + /** + * Returns the minute of the hour in the range 0-59 + */ + public Integer getMinute() { + return getFieldValue(Calendar.MINUTE); + } + + /** + * Returns the second of the minute in the range 0-59 + */ + public Integer getSecond() { + return getFieldValue(Calendar.SECOND); + } + + /** + * Returns the milliseconds within the current second. + *

+ * Note that this method returns the + * same value as {@link #getNanos()} but with less precision. + *

+ */ + public Integer getMillis() { + return getFieldValue(Calendar.MILLISECOND); + } + + /** + * Returns the nanoseconds within the current second + *

+ * Note that this method returns the + * same value as {@link #getMillis()} but with more precision. + *

+ */ + public Long getNanos() { + if (isBlank(myFractionalSeconds)) { + return null; + } + String retVal = StringUtils.rightPad(myFractionalSeconds, 9, '0'); + retVal = retVal.substring(0, 9); + return Long.parseLong(retVal); + } + + /** + * Sets the year, e.g. 2015 + */ + public BaseDateTimeDt setYear(int theYear) { + setFieldValue(Calendar.YEAR, theYear, null, 0, 9999); + return this; + } + + /** + * Sets the month with 0-index, e.g. 0=January + */ + public BaseDateTimeDt setMonth(int theMonth) { + setFieldValue(Calendar.MONTH, theMonth, null, 0, 11); + return this; + } + + /** + * Sets the month with 1-index, e.g. 1=the first day of the month + */ + public BaseDateTimeDt setDay(int theDay) { + setFieldValue(Calendar.DAY_OF_MONTH, theDay, null, 0, 31); + return this; + } + + /** + * Sets the hour of the day in a 24h clock, e.g. 13=1pm + */ + public BaseDateTimeDt setHour(int theHour) { + setFieldValue(Calendar.HOUR_OF_DAY, theHour, null, 0, 23); + return this; + } + + /** + * Sets the minute of the hour in the range 0-59 + */ + public BaseDateTimeDt setMinute(int theMinute) { + setFieldValue(Calendar.MINUTE, theMinute, null, 0, 59); + return this; + } + + /** + * Sets the second of the minute in the range 0-59 + */ + public BaseDateTimeDt setSecond(int theSecond) { + setFieldValue(Calendar.SECOND, theSecond, null, 0, 59); + return this; + } + + /** + * Sets the milliseconds within the current second. + *

+ * Note that this method sets the + * same value as {@link #setNanos(long)} but with less precision. + *

+ */ + public BaseDateTimeDt setMillis(int theMillis) { + setFieldValue(Calendar.MILLISECOND, theMillis, null, 0, 999); + return this; + } + + /** + * Sets the nanoseconds within the current second + *

+ * Note that this method sets the + * same value as {@link #setMillis(int)} but with more precision. + *

+ */ + 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') { + fractionalSeconds = fractionalSeconds.substring(0, i); + break; + } + } + int millis = (int)(theNanos / NANOS_PER_MILLIS); + setFieldValue(Calendar.MILLISECOND, millis, fractionalSeconds, 0, 999); + return this; + } + + private void setFieldValue(int theField, int theValue, String theFractionalSeconds, int theMinimum, int theMaximum) { + validateValueInRange(theValue, theMinimum, theMaximum); + Calendar cal; + if (getValue() == null) { + cal = new GregorianCalendar(0, 0, 0); + } else { + cal = getValueAsCalendar(); + } + if (theField != -1) { + cal.set(theField, theValue); + } + if (theFractionalSeconds != null) { + myFractionalSeconds = theFractionalSeconds; + } else if (theField == Calendar.MILLISECOND) { + myFractionalSeconds = StringUtils.leftPad(Integer.toString(theValue), 3, '0'); + } + super.setValue(cal.getTime()); + } + + private void validateValueInRange(long theValue, long theMinimum, long theMaximum) { + if (theValue < theMinimum || theValue > theMaximum) { + throw new IllegalArgumentException("Value " + theValue + " is not between allowable range: " + theMinimum + " - " + theMaximum); + } + } + + private Integer getFieldValue(int theField) { + if (getValue() == null) { + return null; + } + Calendar cal = getValueAsCalendar(); + return cal.get(theField); + } + } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/InstantDt.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/InstantDt.java index cfcb828d0f1..5787e8e644b 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/InstantDt.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/InstantDt.java @@ -185,5 +185,4 @@ public class InstantDt extends BaseDateTimeDt { return DEFAULT_PRECISION; } - } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/UriDt.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/UriDt.java index e67b9273a67..8e9153f6d11 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/UriDt.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/model/primitive/UriDt.java @@ -32,22 +32,6 @@ import ca.uhn.fhir.model.api.annotation.SimpleSetter; @DatatypeDef(name = "uri") public class UriDt extends BasePrimitive { - /** - * Creates a new UriDt instance which uses the given OID as the content (and prepends "urn:oid:" to the OID string - * in the value of the newly created UriDt, per the FHIR specification). - * - * @param theOid - * The OID to use (null is acceptable and will result in a UriDt instance with a - * null value) - * @return A new UriDt instance - */ - public static UriDt fromOid(String theOid) { - if (theOid == null) { - return new UriDt(); - } - return new UriDt("urn:oid:" + theOid); - } - private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(UriDt.class); /** @@ -119,18 +103,15 @@ public class UriDt extends BasePrimitive { URI retVal; try { retVal = new URI(theValue).normalize(); - } catch (URISyntaxException e1) { - ourLog.debug("Failed to normalize URL '{}', message was: {}", theValue, e1.toString()); + String urlString = retVal.toString(); + if (urlString.endsWith("/") && urlString.length() > 1) { + retVal = new URI(urlString.substring(0, urlString.length() - 1)); + } + } catch (URISyntaxException e) { + ourLog.debug("Failed to normalize URL '{}', message was: {}", theValue, e.toString()); return theValue; } - String urlString = retVal.toString(); - if (urlString.endsWith("/") && urlString.length() > 1) { - try { - retVal = new URI(urlString.substring(0, urlString.length() - 1)); - } catch (URISyntaxException e) { - ourLog.debug("Failed to normalize URL '{}', message was: {}", urlString, e.toString()); - } - } + return retVal.toASCIIString(); } @@ -139,4 +120,20 @@ public class UriDt extends BasePrimitive { return theValue; } + /** + * Creates a new UriDt instance which uses the given OID as the content (and prepends "urn:oid:" to the OID string + * in the value of the newly created UriDt, per the FHIR specification). + * + * @param theOid + * The OID to use (null is acceptable and will result in a UriDt instance with a + * null value) + * @return A new UriDt instance + */ + public static UriDt fromOid(String theOid) { + if (theOid == null) { + return new UriDt(); + } + return new UriDt("urn:oid:" + theOid); + } + } 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 ed1f69379f0..3a35fec3b2b 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 @@ -29,7 +29,6 @@ import java.util.List; import org.hl7.fhir.instance.model.api.IPrimitiveType; import ca.uhn.fhir.model.api.IQueryParameterAnd; -import ca.uhn.fhir.model.primitive.DateTimeDt; import ca.uhn.fhir.parser.DataFormatException; import ca.uhn.fhir.rest.method.QualifiedParamList; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; @@ -301,7 +300,9 @@ public class DateRangeParam implements IQueryParameterAnd { } /** - * Sets the range from a pair of dates, inclusive on both ends + * Sets the range from a pair of dates, inclusive on both ends. Note that if + * theLowerBound is after theUpperBound, thie method will automatically reverse + * the order of the arguments in order to create an inclusive range. * * @param theLowerBound * A qualified date param representing the lower date bound (optionally may include time), e.g. @@ -313,8 +314,18 @@ public class DateRangeParam implements IQueryParameterAnd { * theUpperBound may both be populated, or one may be null, but it is not valid for both to be null. */ public void setRangeFromDatesInclusive(IPrimitiveType theLowerBound, IPrimitiveType theUpperBound) { - myLowerBound = theLowerBound != null ? new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, theLowerBound) : null; - myUpperBound = theUpperBound != null ? new DateParam(ParamPrefixEnum.LESSTHAN_OR_EQUALS, theUpperBound) : null; + IPrimitiveType lowerBound = theLowerBound; + IPrimitiveType upperBound = theUpperBound; + if (lowerBound != null && lowerBound.getValue() != null && upperBound != null && upperBound.getValue() != null) { + if (lowerBound.getValue().after(upperBound.getValue())) { + IPrimitiveType temp = lowerBound; + lowerBound = upperBound; + upperBound = temp; + } + } + + myLowerBound = lowerBound != null ? new DateParam(ParamPrefixEnum.GREATERTHAN_OR_EQUALS, lowerBound) : null; + myUpperBound = upperBound != null ? new DateParam(ParamPrefixEnum.LESSTHAN_OR_EQUALS, upperBound) : null; validateAndThrowDataFormatExceptionIfInvalid(); } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/NonPrettyPrintWriterWrapper.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/NonPrettyPrintWriterWrapper.java index 147831528e9..98cf1c08cf7 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/NonPrettyPrintWriterWrapper.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/util/NonPrettyPrintWriterWrapper.java @@ -45,26 +45,31 @@ public class NonPrettyPrintWriterWrapper implements XMLStreamWriter { } @Override + @CoverageIgnore public String getPrefix(String theUri) throws XMLStreamException { return myTarget.getPrefix(theUri); } @Override + @CoverageIgnore public void setPrefix(String thePrefix, String theUri) throws XMLStreamException { myTarget.setPrefix(thePrefix, theUri); } @Override + @CoverageIgnore public void setDefaultNamespace(String theUri) throws XMLStreamException { myTarget.setDefaultNamespace(theUri); } @Override + @CoverageIgnore public void setNamespaceContext(NamespaceContext theContext) throws XMLStreamException { myTarget.setNamespaceContext(theContext); } @Override + @CoverageIgnore public NamespaceContext getNamespaceContext() { return myTarget.getNamespaceContext(); } @@ -94,16 +99,19 @@ public class NonPrettyPrintWriterWrapper implements XMLStreamWriter { } @Override + @CoverageIgnore public void writeEmptyElement(String theNamespaceURI, String theLocalName) throws XMLStreamException { myTarget.writeEmptyElement(theNamespaceURI, theLocalName); } @Override + @CoverageIgnore public void writeEmptyElement(String thePrefix, String theLocalName, String theNamespaceURI) throws XMLStreamException { myTarget.writeEmptyElement(thePrefix, theLocalName, theNamespaceURI); } @Override + @CoverageIgnore public void writeEmptyElement(String theLocalName) throws XMLStreamException { myTarget.writeEmptyElement(theLocalName); } @@ -127,11 +135,13 @@ public class NonPrettyPrintWriterWrapper implements XMLStreamWriter { } @Override + @CoverageIgnore public void writeAttribute(String thePrefix, String theNamespaceURI, String theLocalName, String theValue) throws XMLStreamException { myTarget.writeAttribute(thePrefix, theNamespaceURI, theLocalName, theValue); } @Override + @CoverageIgnore public void writeAttribute(String theNamespaceURI, String theLocalName, String theValue) throws XMLStreamException { myTarget.writeAttribute(theNamespaceURI, theLocalName, theValue); } @@ -152,36 +162,43 @@ public class NonPrettyPrintWriterWrapper implements XMLStreamWriter { } @Override + @CoverageIgnore public void writeProcessingInstruction(String theTarget) throws XMLStreamException { myTarget.writeProcessingInstruction(theTarget); } @Override + @CoverageIgnore public void writeProcessingInstruction(String theTarget, String theData) throws XMLStreamException { myTarget.writeProcessingInstruction(theTarget, theData); } @Override + @CoverageIgnore public void writeCData(String theData) throws XMLStreamException { myTarget.writeCData(theData); } @Override + @CoverageIgnore public void writeDTD(String theDtd) throws XMLStreamException { myTarget.writeDTD(theDtd); } @Override + @CoverageIgnore public void writeEntityRef(String theName) throws XMLStreamException { myTarget.writeEntityRef(theName); } @Override + @CoverageIgnore public void writeStartDocument() throws XMLStreamException { myTarget.writeStartDocument(); } @Override + @CoverageIgnore public void writeStartDocument(String theVersion) throws XMLStreamException { myTarget.writeStartDocument(theVersion); } @@ -206,9 +223,7 @@ public class NonPrettyPrintWriterWrapper implements XMLStreamWriter { } static void writeCharacters(char[] theText, int theStart, int theLen, XMLStreamWriter target, int insidePre) throws XMLStreamException { - if (theLen == 0) { - return; - } else { + if (theLen > 0) { if (insidePre > 0) { target.writeCharacters(theText, theStart, theLen); } else { @@ -240,6 +255,7 @@ public class NonPrettyPrintWriterWrapper implements XMLStreamWriter { } @Override + @CoverageIgnore public Object getProperty(String theName) throws IllegalArgumentException { return myTarget.getProperty(theName); } 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 d66bdd56fe2..7ac653d5286 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 @@ -1,37 +1,19 @@ package ca.uhn.fhir.util; -/* - * #%L - * HAPI FHIR - Core Library - * %% - * Copyright (C) 2014 - 2016 University Health Network - * %% - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * #L% - */ - - -import java.io.IOException; import java.net.ServerSocket; -import java.util.ArrayList; -import java.util.List; /** * Provides server ports */ +@CoverageIgnore public class PortUtil { - private static List ourPorts = new ArrayList(); + /* + * Non instantiable + */ + private PortUtil() { + // nothing + } /** * This is really only used for unit tests but is included in the library so it can be reused across modules. Use with caution. @@ -41,20 +23,13 @@ public class PortUtil { try { server = new ServerSocket(0); int port = server.getLocalPort(); - ourPorts.add(port); server.close(); Thread.sleep(500); return port; - } catch (IOException e) { - throw new Error(e); - } catch (InterruptedException e) { + } catch (Exception e) { throw new Error(e); } } - public static List list() { - return ourPorts; - } - } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/FhirValidator.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/FhirValidator.java index 944fbfc04cc..23eb930024e 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/FhirValidator.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/FhirValidator.java @@ -61,7 +61,7 @@ public class FhirValidator { myContext = theFhirContext; if (ourPhlocPresentOnClasspath == null) { - ourPhlocPresentOnClasspath = SchematronProvider.isScematronAvailable(theFhirContext); + ourPhlocPresentOnClasspath = SchematronProvider.isSchematronAvailable(theFhirContext); } } diff --git a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/schematron/SchematronProvider.java b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/schematron/SchematronProvider.java index 65b82856284..0f8c90a02ba 100644 --- a/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/schematron/SchematronProvider.java +++ b/hapi-fhir-base/src/main/java/ca/uhn/fhir/validation/schematron/SchematronProvider.java @@ -23,6 +23,7 @@ package ca.uhn.fhir.validation.schematron; import java.lang.reflect.Constructor; import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.util.CoverageIgnore; import ca.uhn.fhir.validation.FhirValidator; import ca.uhn.fhir.validation.IValidatorModule; @@ -32,7 +33,8 @@ public class SchematronProvider { private static final String I18N_KEY_NO_PHLOC_WARNING = FhirValidator.class.getName() + ".noPhlocWarningOnStartup"; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirValidator.class); - public static boolean isScematronAvailable(FhirContext theFhirContext) { + @CoverageIgnore + public static boolean isSchematronAvailable(FhirContext theFhirContext) { try { Class.forName("com.phloc.schematron.ISchematronResource"); return true; @@ -42,6 +44,8 @@ public class SchematronProvider { } } + @SuppressWarnings("unchecked") + @CoverageIgnore public static Class getSchematronValidatorClass() { try { return (Class) Class.forName("ca.uhn.fhir.validation.schematron.SchematronBaseValidator"); @@ -50,6 +54,7 @@ public class SchematronProvider { } } + @CoverageIgnore public static IValidatorModule getSchematronValidatorInstance(FhirContext myContext) { try { Class cls = getSchematronValidatorClass(); diff --git a/hapi-fhir-base/src/main/resources/ca/uhn/fhir/i18n/hapi-messages.properties b/hapi-fhir-base/src/main/resources/ca/uhn/fhir/i18n/hapi-messages.properties index 6bde1a93a7f..a300ce63f50 100644 --- a/hapi-fhir-base/src/main/resources/ca/uhn/fhir/i18n/hapi-messages.properties +++ b/hapi-fhir-base/src/main/resources/ca/uhn/fhir/i18n/hapi-messages.properties @@ -77,5 +77,10 @@ ca.uhn.fhir.jpa.dao.BaseHapiFhirResourceDao.successfulUpdate=Successfully update ca.uhn.fhir.jpa.dao.SearchBuilder.invalidQuantityPrefix=Unable to handle quantity prefix "{0}" for value: {1} ca.uhn.fhir.jpa.dao.SearchBuilder.invalidNumberPrefix=Unable to handle number prefix "{0}" for value: {1} +ca.uhn.fhir.jpa.provider.BaseJpaProvider.cantCombintAtAndSince=Unable to combine _at and _since parameters for history operation + ca.uhn.fhir.jpa.term.BaseHapiTerminologySvc.cannotCreateDuplicateCodeSystemUri=Can not create multiple code systems with URI "{0}", already have one with resource ID: {1} -ca.uhn.fhir.jpa.term.BaseHapiTerminologySvc.expansionTooLarge=Expansion of ValueSet produced too many codes (maximum {0}) - Operation aborted! \ No newline at end of file +ca.uhn.fhir.jpa.term.BaseHapiTerminologySvc.expansionTooLarge=Expansion of ValueSet produced too many codes (maximum {0}) - Operation aborted! +ca.uhn.fhir.jpa.term.BaseHapiTerminologySvc.expansionTooLarge=Expansion of ValueSet produced too many codes (maximum {0}) - Operation aborted! + + \ No newline at end of file diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaProvider.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaProvider.java index 35cdd4b4ade..38721d139fb 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaProvider.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaProvider.java @@ -1,5 +1,7 @@ package ca.uhn.fhir.jpa.provider; +import java.util.Date; + /* * #%L * HAPI FHIR JPA Server @@ -28,9 +30,10 @@ import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils; import org.jboss.logging.MDC; -import org.springframework.beans.factory.annotation.Autowired; import ca.uhn.fhir.context.FhirContext; +import ca.uhn.fhir.rest.param.DateRangeParam; +import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; public class BaseJpaProvider { @@ -41,6 +44,9 @@ public class BaseJpaProvider { private FhirContext myContext; + /** + * @param theRequest The servlet request + */ public void endRequest(HttpServletRequest theRequest) { MDC.remove(REMOTE_ADDR); MDC.remove(REMOTE_UA); @@ -54,10 +60,25 @@ public class BaseJpaProvider { return myContext; } + protected DateRangeParam processSinceOrAt(Date theSince, DateRangeParam theAt) { + boolean haveAt = theAt != null && (theAt.getLowerBoundAsInstant() != null || theAt.getUpperBoundAsInstant() != null); + if (haveAt && theSince != null) { + String msg = getContext().getLocalizer().getMessage(BaseJpaProvider.class, "cantCombintAtAndSince"); + throw new InvalidRequestException(msg); + } + + if (haveAt) { + return theAt; + } + + return new DateRangeParam(theSince, null); + } + public void setContext(FhirContext theContext) { myContext = theContext; } + public void startRequest(HttpServletRequest theRequest) { if (theRequest == null) { return; diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProvider.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProvider.java index d7f4edb58b8..a3743ffa542 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProvider.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaResourceProvider.java @@ -65,24 +65,29 @@ public abstract class BaseJpaResourceProvider extends B HttpServletRequest theRequest, @IdParam IIdType theId, @Since Date theSince, -// @At DateRangeParam theAt, + @At DateRangeParam theAt, RequestDetails theRequestDetails) { //@formatter:on startRequest(theRequest); try { -// DateRangeParam sinceOrAt = processSinceOrAt(theSince) - return myDao.history(theId, theSince, null, theRequestDetails); + DateRangeParam sinceOrAt = processSinceOrAt(theSince, theAt); + return myDao.history(theId, sinceOrAt.getLowerBoundAsInstant(), sinceOrAt.getUpperBoundAsInstant(), theRequestDetails); } finally { endRequest(theRequest); } } @History - public IBundleProvider getHistoryForResourceType(HttpServletRequest theRequest, @Since Date theDate, RequestDetails theRequestDetails) { + public IBundleProvider getHistoryForResourceType( + HttpServletRequest theRequest, + @Since Date theSince, + @At DateRangeParam theAt, + RequestDetails theRequestDetails) { startRequest(theRequest); try { - return myDao.history(theDate, null, theRequestDetails); + DateRangeParam sinceOrAt = processSinceOrAt(theSince, theAt); + return myDao.history(sinceOrAt.getLowerBoundAsInstant(), sinceOrAt.getUpperBoundAsInstant(), theRequestDetails); } finally { endRequest(theRequest); } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaSystemProvider.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaSystemProvider.java index 510e3c6e5f8..6420142436a 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaSystemProvider.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/BaseJpaSystemProvider.java @@ -28,10 +28,12 @@ import org.springframework.beans.factory.annotation.Required; import ca.uhn.fhir.jpa.dao.IFhirSystemDao; import ca.uhn.fhir.model.api.TagList; +import ca.uhn.fhir.rest.annotation.At; import ca.uhn.fhir.rest.annotation.GetTags; import ca.uhn.fhir.rest.annotation.History; import ca.uhn.fhir.rest.annotation.Since; import ca.uhn.fhir.rest.method.RequestDetails; +import ca.uhn.fhir.rest.param.DateRangeParam; import ca.uhn.fhir.rest.server.IBundleProvider; public class BaseJpaSystemProvider extends BaseJpaProvider { @@ -48,10 +50,11 @@ public class BaseJpaSystemProvider extends BaseJpaProvider { } @History - public IBundleProvider historyServer(HttpServletRequest theRequest, @Since Date theDate, RequestDetails theRequestDetails) { + public IBundleProvider historyServer(HttpServletRequest theRequest, @Since Date theDate, @At DateRangeParam theAt, RequestDetails theRequestDetails) { startRequest(theRequest); try { - return myDao.history(theDate, null, theRequestDetails); + DateRangeParam range = super.processSinceOrAt(theDate, theAt); + return myDao.history(range.getLowerBoundAsInstant(), range.getUpperBoundAsInstant(), theRequestDetails); } finally { endRequest(theRequest); } diff --git a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/dstu3/BaseJpaResourceProviderValueSetDstu3.java b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/dstu3/BaseJpaResourceProviderValueSetDstu3.java index 934eebf6a86..a868f5f144f 100644 --- a/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/dstu3/BaseJpaResourceProviderValueSetDstu3.java +++ b/hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/provider/dstu3/BaseJpaResourceProviderValueSetDstu3.java @@ -62,7 +62,7 @@ public class BaseJpaResourceProviderValueSetDstu3 extends JpaResourceProviderDst } if (moreThanOneTrue(haveId, haveIdentifier, haveValueSet)) { - throw new InvalidRequestException("$expand must EITHER be invoked at the type level, or have an identifier specified, or have a ValueSet specified. Can not combine these options."); + throw new InvalidRequestException("$expand must EITHER be invoked at the instance level, or have an identifier specified, or have a ValueSet specified. Can not combine these options."); } startRequest(theServletRequest); diff --git a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/BaseFhirDaoTest.java b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/BaseFhirDaoTest.java index 9d585f5179f..60cb93220a6 100644 --- a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/BaseFhirDaoTest.java +++ b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/BaseFhirDaoTest.java @@ -40,5 +40,11 @@ public class BaseFhirDaoTest extends BaseJpaTest { observation.setEffective(period); } + + + @Override + protected FhirContext getContext() { + return ourCtx; + } } diff --git a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/BaseJpaTest.java b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/BaseJpaTest.java index c6ab1cbb57e..6ed250b8d55 100644 --- a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/BaseJpaTest.java +++ b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/BaseJpaTest.java @@ -16,6 +16,7 @@ import javax.persistence.EntityManager; import org.apache.commons.io.IOUtils; import org.hibernate.search.jpa.Search; import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent; +import org.hl7.fhir.instance.model.api.IBaseBundle; import org.hl7.fhir.instance.model.api.IBaseResource; import org.hl7.fhir.instance.model.api.IIdType; import org.junit.AfterClass; @@ -26,6 +27,7 @@ import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; +import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.jpa.entity.ForcedId; import ca.uhn.fhir.jpa.entity.ResourceHistoryTable; import ca.uhn.fhir.jpa.entity.ResourceHistoryTag; @@ -55,9 +57,10 @@ import ca.uhn.fhir.rest.method.IRequestOperationCallback; import ca.uhn.fhir.rest.server.IBundleProvider; import ca.uhn.fhir.rest.server.interceptor.IServerInterceptor; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; +import ca.uhn.fhir.util.BundleUtil; import ca.uhn.fhir.util.TestUtil; -public class BaseJpaTest { +public abstract class BaseJpaTest { private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BaseJpaTest.class); protected ServletRequestDetails mySrd; @@ -74,6 +77,32 @@ public class BaseJpaTest { return theSearch.getResources(0, theSearch.size()); } + protected abstract FhirContext getContext(); + + protected List toUnqualifiedVersionlessIdValues(IBaseBundle theFound) { + List retVal = new ArrayList(); + + List res = BundleUtil.toListOfResources(getContext(), theFound); + int size = res.size(); + ourLog.info("Found {} results", size); + for (IBaseResource next : res) { + retVal.add(next.getIdElement().toUnqualifiedVersionless().getValue()); + } + return retVal; + } + + protected List toUnqualifiedIdValues(IBaseBundle theFound) { + List retVal = new ArrayList(); + + List res = BundleUtil.toListOfResources(getContext(), theFound); + int size = res.size(); + ourLog.info("Found {} results", size); + for (IBaseResource next : res) { + retVal.add(next.getIdElement().toUnqualified().getValue()); + } + return retVal; + } + protected List toUnqualifiedVersionlessIds(Bundle theFound) { List retVal = new ArrayList(); for (Entry next : theFound.getEntry()) { diff --git a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/FhirResourceDaoDstu1Test.java b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/FhirResourceDaoDstu1Test.java index 57afd48dad1..4f4952780fb 100644 --- a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/FhirResourceDaoDstu1Test.java +++ b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/FhirResourceDaoDstu1Test.java @@ -30,18 +30,22 @@ import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.util.TestUtil; @SuppressWarnings("unused") -public class FhirResourceDaoDstu1Test extends BaseJpaTest { - +public class FhirResourceDaoDstu1Test extends BaseJpaTest { + private static AnnotationConfigApplicationContext ourAppCtx; + private static FhirContext ourCtx; private static IFhirResourceDao ourDeviceDao; private static IFhirResourceDao ourDiagnosticReportDao; private static IFhirResourceDao ourEncounterDao; - private static AnnotationConfigApplicationContext ourAppCtx; private static IFhirResourceDao ourLocationDao; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirResourceDaoDstu1Test.class); private static IFhirResourceDao ourObservationDao; private static IFhirResourceDao ourOrganizationDao; private static IFhirResourceDao ourPatientDao; - private static FhirContext ourCtx; + + @Override + protected FhirContext getContext() { + return ourCtx; + } @Test public void testCreateDuplicateIdFails() { @@ -64,7 +68,7 @@ public class FhirResourceDaoDstu1Test extends BaseJpaTest { assertThat(e.getMessage(), containsString("Can not create entity with ID[" + methodName + "], a resource with this ID already exists")); } } - + @Test public void testCreateNumericIdFails() { Patient p = new Patient(); @@ -125,6 +129,12 @@ public class FhirResourceDaoDstu1Test extends BaseJpaTest { } + @AfterClass + public static void afterClassClearContext() { + ourAppCtx.close(); + TestUtil.clearAllStaticFieldsForUnitTest(); + } + @SuppressWarnings("unchecked") @BeforeClass public static void beforeClass() { @@ -139,10 +149,4 @@ public class FhirResourceDaoDstu1Test extends BaseJpaTest { ourCtx = ourAppCtx.getBean(FhirContext.class); } - @AfterClass - public static void afterClassClearContext() { - ourAppCtx.close(); - TestUtil.clearAllStaticFieldsForUnitTest(); - } - } diff --git a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu1Test.java b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu1Test.java index 24172c52d0f..efa516ad851 100644 --- a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu1Test.java +++ b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/FhirSystemDaoDstu1Test.java @@ -50,30 +50,28 @@ import ca.uhn.fhir.rest.server.IBundleProvider; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.util.TestUtil; -public class FhirSystemDaoDstu1Test extends BaseJpaTest { +public class FhirSystemDaoDstu1Test extends BaseJpaTest { private static AnnotationConfigApplicationContext ourCtx; + private static EntityManager ourEntityManager; private static FhirContext ourFhirContext; private static IFhirResourceDao ourLocationDao; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirSystemDaoDstu1Test.class); private static IFhirResourceDao ourObservationDao; private static IFhirResourceDao ourPatientDao; private static IFhirSystemDao, MetaDt> ourSystemDao; - private static EntityManager ourEntityManager; private static PlatformTransactionManager ourTxManager; - @AfterClass - public static void afterClassClearContext() { - ourCtx.close(); - TestUtil.clearAllStaticFieldsForUnitTest(); - } - - @Before public void before() { super.purgeDatabase(ourEntityManager, ourTxManager); } + @Override + protected FhirContext getContext() { + return ourFhirContext; + } + @Test public void testGetResourceCounts() { Observation obs = new Observation(); @@ -147,7 +145,7 @@ public class FhirSystemDaoDstu1Test extends BaseJpaTest { assertEquals(1, values.size()); } - + @Test public void testPersistWithSimpleLink() { Patient patient = new Patient(); @@ -378,11 +376,10 @@ public class FhirSystemDaoDstu1Test extends BaseJpaTest { String encodeResourceToString = ourFhirContext.newXmlParser().setPrettyPrint(true).encodeResourceToString(response.get(0)); ourLog.info(encodeResourceToString); - + assertThat(encodeResourceToString, not(containsString("smsp"))); } - /** * This is the correct way to do this, not {@link #testTransactionWithCidIds()} */ @@ -479,6 +476,11 @@ public class FhirSystemDaoDstu1Test extends BaseJpaTest { } + @AfterClass + public static void afterClassClearContext() { + ourCtx.close(); + TestUtil.clearAllStaticFieldsForUnitTest(); + } @SuppressWarnings("unchecked") @BeforeClass diff --git a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/BaseJpaDstu2Test.java b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/BaseJpaDstu2Test.java index 20f21dd7e01..55246ee55ee 100644 --- a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/BaseJpaDstu2Test.java +++ b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/BaseJpaDstu2Test.java @@ -73,31 +73,17 @@ import ca.uhn.fhir.util.TestUtil; //@formatter:on public abstract class BaseJpaDstu2Test extends BaseJpaTest { - @AfterClass - public static void afterClassClearContext() throws Exception { - TestUtil.clearAllStaticFieldsForUnitTest(); - } - - @Autowired protected ApplicationContext myAppCtx; @Autowired - protected IFulltextSearchSvc mySearchDao; - @Autowired - @Qualifier("myConceptMapDaoDstu2") - protected IFhirResourceDao myConceptMapDao; - @Autowired @Qualifier("myAppointmentDaoDstu2") protected IFhirResourceDao myAppointmentDao; @Autowired @Qualifier("myBundleDaoDstu2") protected IFhirResourceDao myBundleDao; @Autowired - @Qualifier("myMedicationDaoDstu2") - protected IFhirResourceDao myMedicationDao; - @Autowired - @Qualifier("myMedicationOrderDaoDstu2") - protected IFhirResourceDao myMedicationOrderDao; + @Qualifier("myConceptMapDaoDstu2") + protected IFhirResourceDao myConceptMapDao; @Autowired protected DaoConfig myDaoConfig; @Autowired @@ -112,11 +98,9 @@ public abstract class BaseJpaDstu2Test extends BaseJpaTest { @Autowired @Qualifier("myEncounterDaoDstu2") protected IFhirResourceDao myEncounterDao; - -// @PersistenceContext() + // @PersistenceContext() @Autowired protected EntityManager myEntityManager; - @Autowired @Qualifier("myFhirContextDstu2") protected FhirContext myFhirCtx; @@ -127,6 +111,17 @@ public abstract class BaseJpaDstu2Test extends BaseJpaTest { @Autowired @Qualifier("myLocationDaoDstu2") protected IFhirResourceDao myLocationDao; + +@Autowired + @Qualifier("myMediaDaoDstu2") + protected IFhirResourceDao myMediaDao; + + @Autowired + @Qualifier("myMedicationDaoDstu2") + protected IFhirResourceDao myMedicationDao; + @Autowired + @Qualifier("myMedicationOrderDaoDstu2") + protected IFhirResourceDao myMedicationOrderDao; @Autowired @Qualifier("myObservationDaoDstu2") protected IFhirResourceDao myObservationDao; @@ -137,9 +132,6 @@ public abstract class BaseJpaDstu2Test extends BaseJpaTest { @Qualifier("myPatientDaoDstu2") protected IFhirResourceDaoPatient myPatientDao; @Autowired - @Qualifier("myMediaDaoDstu2") - protected IFhirResourceDao myMediaDao; - @Autowired @Qualifier("myPractitionerDaoDstu2") protected IFhirResourceDao myPractitionerDao; @Autowired @@ -152,6 +144,8 @@ public abstract class BaseJpaDstu2Test extends BaseJpaTest { @Qualifier("myResourceProvidersDstu2") protected Object myResourceProviders; @Autowired + protected IFulltextSearchSvc mySearchDao; + @Autowired @Qualifier("myStructureDefinitionDaoDstu2") protected IFhirResourceDao myStructureDefinitionDao; @Autowired @@ -171,21 +165,11 @@ public abstract class BaseJpaDstu2Test extends BaseJpaTest { @Autowired @Qualifier("myValueSetDaoDstu2") protected IFhirResourceDaoValueSet myValueSetDao; - @Before public void beforeCreateInterceptor() { myInterceptor = mock(IServerInterceptor.class); myDaoConfig.setInterceptors(myInterceptor); } - - @Before - public void beforeResetConfig() { - myDaoConfig.setHardSearchLimit(1000); - myDaoConfig.setHardTagListLimit(1000); - myDaoConfig.setIncludeLimit(2000); - myDaoConfig.setAllowExternalReferences(new DaoConfig().isAllowExternalReferences()); - } - @Before @Transactional public void beforeFlushFT() { @@ -204,6 +188,19 @@ public abstract class BaseJpaDstu2Test extends BaseJpaTest { purgeDatabase(entityManager, myTxManager); } + @Before + public void beforeResetConfig() { + myDaoConfig.setHardSearchLimit(1000); + myDaoConfig.setHardTagListLimit(1000); + myDaoConfig.setIncludeLimit(2000); + myDaoConfig.setAllowExternalReferences(new DaoConfig().isAllowExternalReferences()); + } + + @Override + protected FhirContext getContext() { + return myFhirCtx; + } + protected T loadResourceFromClasspath(Class type, String resourceName) throws IOException { InputStream stream = FhirResourceDaoDstu2SearchNoFtTest.class.getResourceAsStream(resourceName); if (stream == null) { @@ -221,4 +218,9 @@ public abstract class BaseJpaDstu2Test extends BaseJpaTest { return retVal; } + @AfterClass + public static void afterClassClearContext() throws Exception { + TestUtil.clearAllStaticFieldsForUnitTest(); + } + } diff --git a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchFtTest.java b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchFtTest.java index 8b5922804a4..00c4037b85f 100644 --- a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchFtTest.java +++ b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchFtTest.java @@ -29,11 +29,10 @@ import ca.uhn.fhir.rest.param.StringAndListParam; import ca.uhn.fhir.rest.param.StringOrListParam; import ca.uhn.fhir.rest.param.StringParam; import ca.uhn.fhir.rest.server.Constants; -import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.util.TestUtil; public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { - + private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirResourceDaoDstu2SearchFtTest.class); @AfterClass @@ -41,7 +40,6 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { TestUtil.clearAllStaticFieldsForUnitTest(); } - @Test public void testSuggestIgnoresBase64Content() { Patient patient = new Patient(); @@ -52,11 +50,11 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { med.getSubject().setReference(ptId); med.getSubtype().setText("Systolic Blood Pressure"); med.getContent().setContentType("LCws"); - med.getContent().setData(new Base64BinaryDt(new byte[] {44,44,44,44,44,44,44,44})); + med.getContent().setData(new Base64BinaryDt(new byte[] { 44, 44, 44, 44, 44, 44, 44, 44 })); med.getContent().setTitle("bbbb syst"); myMediaDao.create(med, mySrd); ourLog.info(myFhirCtx.newJsonParser().encodeResourceToString(med)); - + List output = mySearchDao.suggestKeywords("Patient/" + ptId.getIdPart() + "/$everything", "_content", "press"); ourLog.info("Found: " + output); assertEquals(2, output.size()); @@ -76,12 +74,12 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { assertEquals("bbbb syst", output.get(1).getTerm()); assertEquals("Systolic", output.get(2).getTerm()); assertEquals("Systolic Blood Pressure", output.get(3).getTerm()); - + output = mySearchDao.suggestKeywords("Patient/" + ptId.getIdPart() + "/$everything", "_content", "LCws"); ourLog.info("Found: " + output); assertEquals(0, output.size()); } - + @Test public void testSuggest() { Patient patient = new Patient(); @@ -137,7 +135,7 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { assertEquals(2, output.size()); assertEquals("HELLO", output.get(0).getTerm()); assertEquals("ZXC HELLO", output.get(1).getTerm()); - + output = mySearchDao.suggestKeywords("Patient/" + ptId.getIdPart() + "/$everything", "_content", "Z"); ourLog.info("Found: " + output); assertEquals(0, output.size()); @@ -149,8 +147,7 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { assertEquals("ZXC HELLO", output.get(1).getTerm()); } - - + @Test public void testSearchAndReindex() { Patient patient; @@ -210,7 +207,7 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { Device dev1 = new Device(); dev1.setManufacturer("Some Manufacturer"); IIdType devId1 = myDeviceDao.create(dev1, mySrd).getId().toUnqualifiedVersionless(); - + Device dev2 = new Device(); dev2.setManufacturer("Some Manufacturer 2"); myDeviceDao.create(dev2, mySrd).getId().toUnqualifiedVersionless(); @@ -234,14 +231,14 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { obs3.getCode().addCoding().setCode("CODE3"); obs3.setValue(new StringDt("obsvalue3")); IIdType obsId3 = myObservationDao.create(obs3, mySrd).getId().toUnqualifiedVersionless(); - + HttpServletRequest request; List actual; request = mock(HttpServletRequest.class); StringAndListParam param; - - ourLog.info("Pt1:{} Pt2:{} Obs1:{} Obs2:{} Obs3:{}", new Object[] {ptId1.getIdPart(), ptId2.getIdPart(), obsId1.getIdPart(), obsId2.getIdPart(), obsId3.getIdPart()}); - + + ourLog.info("Pt1:{} Pt2:{} Obs1:{} Obs2:{} Obs3:{}", new Object[] { ptId1.getIdPart(), ptId2.getIdPart(), obsId1.getIdPart(), obsId2.getIdPart(), obsId3.getIdPart() }); + param = new StringAndListParam(); param.addAnd(new StringOrListParam().addOr(new StringParam("obsvalue1"))); actual = toUnqualifiedVersionlessIds(myPatientDao.patientInstanceEverything(request, ptId1, null, null, null, param, null, mySrd)); @@ -259,7 +256,7 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { /* * Add another match */ - + Observation obs4 = new Observation(); obs4.getSubject().setReference(ptId1); obs4.getCode().addCoding().setCode("CODE1"); @@ -275,7 +272,7 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { /* * Make one previous match no longer match */ - + obs1 = new Observation(); obs1.setId(obsId1); obs1.getSubject().setReference(ptId1); @@ -289,7 +286,7 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { assertThat(actual, containsInAnyOrder(ptId1, obsId4)); } - + @Test public void testEverythingTypeWithContentFilter() { Patient pt1 = new Patient(); @@ -303,7 +300,7 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { Device dev1 = new Device(); dev1.setManufacturer("Some Manufacturer"); IIdType devId1 = myDeviceDao.create(dev1, mySrd).getId().toUnqualifiedVersionless(); - + Device dev2 = new Device(); dev2.setManufacturer("Some Manufacturer 2"); IIdType devId2 = myDeviceDao.create(dev2, mySrd).getId().toUnqualifiedVersionless(); @@ -326,14 +323,14 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { obs3.getCode().addCoding().setCode("CODE3"); obs3.setValue(new StringDt("obsvalue3")); IIdType obsId3 = myObservationDao.create(obs3, mySrd).getId().toUnqualifiedVersionless(); - + HttpServletRequest request; List actual; request = mock(HttpServletRequest.class); StringAndListParam param; - - ourLog.info("Pt1:{} Pt2:{} Obs1:{} Obs2:{} Obs3:{}", new Object[] {ptId1.getIdPart(), ptId2.getIdPart(), obsId1.getIdPart(), obsId2.getIdPart(), obsId3.getIdPart()}); - + + ourLog.info("Pt1:{} Pt2:{} Obs1:{} Obs2:{} Obs3:{}", new Object[] { ptId1.getIdPart(), ptId2.getIdPart(), obsId1.getIdPart(), obsId2.getIdPart(), obsId3.getIdPart() }); + param = new StringAndListParam(); param.addAnd(new StringOrListParam().addOr(new StringParam("obsvalue1"))); actual = toUnqualifiedVersionlessIds(myPatientDao.patientTypeEverything(request, null, null, null, param, null, mySrd)); @@ -346,7 +343,7 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { /* * Add another match */ - + Observation obs4 = new Observation(); obs4.getSubject().setReference(ptId1); obs4.getCode().addCoding().setCode("CODE1"); @@ -362,7 +359,7 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { /* * Make one previous match no longer match */ - + obs1 = new Observation(); obs1.setId(obsId1); obs1.getSubject().setReference(ptId1); @@ -377,10 +374,8 @@ public class FhirResourceDaoDstu2SearchFtTest extends BaseJpaDstu2Test { } - /** - * When processing transactions, we do two passes. Make sure we don't update the lucene index twice since that would - * be inefficient + * When processing transactions, we do two passes. Make sure we don't update the lucene index twice since that would be inefficient */ @Test public void testSearchDontReindexForUpdateWithIndexDisabled() { diff --git a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchNoFtTest.java b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchNoFtTest.java index 9550e04736a..6122a1fbfa6 100644 --- a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchNoFtTest.java +++ b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu2/FhirResourceDaoDstu2SearchNoFtTest.java @@ -792,19 +792,19 @@ public class FhirResourceDaoDstu2SearchNoFtTest extends BaseJpaDstu2Test { { SearchParameterMap params = new SearchParameterMap(); List patients = toUnqualifiedVersionlessIds(myPatientDao.search(params)); - assertThat(patients, hasItems(id1a, id1b, id2)); + assertThat(patients, containsInAnyOrder(id1a, id1b, id2)); } { SearchParameterMap params = new SearchParameterMap(); params.setLastUpdated(new DateRangeParam(beforeAny, null)); List patients = toUnqualifiedVersionlessIds(myPatientDao.search(params)); - assertThat(patients, hasItems(id1a, id1b, id2)); + assertThat(patients, containsInAnyOrder(id1a, id1b, id2)); } { SearchParameterMap params = new SearchParameterMap(); params.setLastUpdated(new DateRangeParam(beforeR2, null)); List patients = toUnqualifiedVersionlessIds(myPatientDao.search(params)); - assertThat(patients, hasItems(id2)); + assertThat(patients, containsInAnyOrder(id2)); assertThat(patients, not(hasItems(id1a, id1b))); } { @@ -812,13 +812,13 @@ public class FhirResourceDaoDstu2SearchNoFtTest extends BaseJpaDstu2Test { params.setLastUpdated(new DateRangeParam(beforeAny, beforeR2)); List patients = toUnqualifiedVersionlessIds(myPatientDao.search(params)); assertThat(patients.toString(), patients, not(hasItems(id2))); - assertThat(patients.toString(), patients, (hasItems(id1a, id1b))); + assertThat(patients.toString(), patients, (containsInAnyOrder(id1a, id1b))); } { SearchParameterMap params = new SearchParameterMap(); params.setLastUpdated(new DateRangeParam(null, beforeR2)); List patients = toUnqualifiedVersionlessIds(myPatientDao.search(params)); - assertThat(patients, (hasItems(id1a, id1b))); + assertThat(patients, (containsInAnyOrder(id1a, id1b))); assertThat(patients, not(hasItems(id2))); } } diff --git a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/BaseJpaDstu3Test.java b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/BaseJpaDstu3Test.java index 8a1a7c4895e..128bdc43fc3 100644 --- a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/BaseJpaDstu3Test.java +++ b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/dao/dstu3/BaseJpaDstu3Test.java @@ -106,9 +106,6 @@ public abstract class BaseJpaDstu3Test extends BaseJpaTest { @Qualifier("myCarePlanDaoDstu3") protected IFhirResourceDao myCarePlanDao; @Autowired - @Qualifier("myConditionDaoDstu3") - protected IFhirResourceDao myConditionDao; - @Autowired @Qualifier("myCodeSystemDaoDstu3") protected IFhirResourceDao myCodeSystemDao; @Autowired @@ -118,6 +115,9 @@ public abstract class BaseJpaDstu3Test extends BaseJpaTest { @Qualifier("myConceptMapDaoDstu3") protected IFhirResourceDao myConceptMapDao; @Autowired + @Qualifier("myConditionDaoDstu3") + protected IFhirResourceDao myConditionDao; + @Autowired protected DaoConfig myDaoConfig; @Autowired @Qualifier("myDeviceDaoDstu3") @@ -213,7 +213,6 @@ public abstract class BaseJpaDstu3Test extends BaseJpaTest { @Autowired @Qualifier("myValueSetDaoDstu3") protected IFhirResourceDaoValueSet myValueSetDao; - @After() public void afterGrabCaches() { ourValueSetDao = myValueSetDao; @@ -251,6 +250,11 @@ public abstract class BaseJpaDstu3Test extends BaseJpaTest { myDaoConfig.setIncludeLimit(2000); } + @Override + protected FhirContext getContext() { + return myFhirCtx; + } + protected T loadResourceFromClasspath(Class type, String resourceName) throws IOException { InputStream stream = FhirResourceDaoDstu2SearchNoFtTest.class.getResourceAsStream(resourceName); if (stream == null) { diff --git a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/ResourceProviderDstu1Test.java b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/ResourceProviderDstu1Test.java index 68fc988a5d6..377b781c5da 100644 --- a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/ResourceProviderDstu1Test.java +++ b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/ResourceProviderDstu1Test.java @@ -63,7 +63,6 @@ import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; -import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.util.TestUtil; public class ResourceProviderDstu1Test extends BaseJpaTest { @@ -88,6 +87,10 @@ public class ResourceProviderDstu1Test extends BaseJpaTest { TestUtil.clearAllStaticFieldsForUnitTest(); } + @Override + protected FhirContext getContext() { + return ourCtx; + } // private static JpaConformanceProvider ourConfProvider; @@ -121,11 +124,11 @@ public class ResourceProviderDstu1Test extends BaseJpaTest { } ourClient.transaction().withResources(resources).prettyPrint().encodedXml().execute(); - Bundle found = ourClient.search().forResource(Organization.class).where(Organization.NAME.matches().value("testCountParam_01")).limitTo(10).execute(); + Bundle found = ourClient.search().forResource(Organization.class).where(Organization.NAME.matches().value("testCountParam_01")).count(10).execute(); assertEquals(100, found.getTotalResults().getValue().intValue()); assertEquals(10, found.getEntries().size()); - found = ourClient.search().forResource(Organization.class).where(Organization.NAME.matches().value("testCountParam_01")).limitTo(999).execute(); + found = ourClient.search().forResource(Organization.class).where(Organization.NAME.matches().value("testCountParam_01")).count(999).execute(); assertEquals(100, found.getTotalResults().getValue().intValue()); assertEquals(50, found.getEntries().size()); diff --git a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/SystemProviderDstu1Test.java b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/SystemProviderDstu1Test.java index 93a76fc81f0..9639ec9a27d 100644 --- a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/SystemProviderDstu1Test.java +++ b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/SystemProviderDstu1Test.java @@ -3,7 +3,8 @@ package ca.uhn.fhir.jpa.provider; import static org.hamcrest.Matchers.blankOrNullString; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; -import static org.junit.Assert.*; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; import java.io.InputStream; @@ -11,13 +12,10 @@ import org.apache.commons.io.IOUtils; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; -import org.hamcrest.text.IsBlankString; -import org.hl7.fhir.instance.model.api.IBaseResource; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; import ca.uhn.fhir.context.FhirContext; import ca.uhn.fhir.jpa.config.TestDstu1Config; @@ -32,19 +30,22 @@ import ca.uhn.fhir.model.dstu.resource.Observation; import ca.uhn.fhir.model.dstu.resource.Organization; import ca.uhn.fhir.model.dstu.resource.Patient; import ca.uhn.fhir.model.dstu.resource.Questionnaire; -import ca.uhn.fhir.model.dstu2.resource.Bundle; -import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.rest.client.IGenericClient; import ca.uhn.fhir.rest.server.RestfulServer; import ca.uhn.fhir.util.TestUtil; -public class SystemProviderDstu1Test extends BaseJpaTest { +public class SystemProviderDstu1Test extends BaseJpaTest { + private static AnnotationConfigApplicationContext ourAppCtx; + private static IGenericClient ourClient; + private static FhirContext ourCtx; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(SystemProviderDstu1Test.class); private static Server ourServer; - private static AnnotationConfigApplicationContext ourAppCtx; - private static FhirContext ourCtx; - private static IGenericClient ourClient; + + @Override + protected FhirContext getContext() { + return ourCtx; + } @Test public void testTransactionFromBundle() throws Exception { @@ -53,7 +54,7 @@ public class SystemProviderDstu1Test extends BaseJpaTest { String bundle = IOUtils.toString(bundleRes); String response = ourClient.transaction().withBundle(bundle).prettyPrint().execute(); ourLog.info(response); - + ca.uhn.fhir.model.api.Bundle respBundle = ourCtx.newXmlParser().parseBundle(response); assertEquals(3, respBundle.size()); for (int i = 1; i < 3; i++) { @@ -62,10 +63,15 @@ public class SystemProviderDstu1Test extends BaseJpaTest { assertThat(nextValue, not(blankOrNullString())); assertThat(nextValue, not(containsString("cid"))); } - + + } + + @AfterClass + public static void afterClassClearContext() throws Exception { + ourServer.stop(); + ourAppCtx.stop(); + TestUtil.clearAllStaticFieldsForUnitTest(); } - - @SuppressWarnings("unchecked") @BeforeClass @@ -108,22 +114,13 @@ public class SystemProviderDstu1Test extends BaseJpaTest { ourCtx = FhirContext.forDstu1(); restServer.setFhirContext(ourCtx); - + ourServer.setHandler(proxyHandler); ourServer.start(); - ourCtx.getRestfulClientFactory().setSocketTimeout(600 * 1000); ourClient = ourCtx.newRestfulGenericClient(serverBase); ourClient.setLogRequestAndResponse(true); } - @AfterClass - public static void afterClassClearContext() throws Exception { - ourServer.stop(); - ourAppCtx.stop(); - TestUtil.clearAllStaticFieldsForUnitTest(); - } - - } diff --git a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/ResourceProviderDstu3Test.java b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/ResourceProviderDstu3Test.java index 9196d0aed02..7cfcd5a64ba 100644 --- a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/ResourceProviderDstu3Test.java +++ b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/ResourceProviderDstu3Test.java @@ -7,6 +7,7 @@ import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.startsWith; import static org.hamcrest.Matchers.stringContainsInOrder; @@ -17,21 +18,17 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.forwardedUrlPattern; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketTimeoutException; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Date; -import java.util.HashMap; import java.util.List; -import java.util.Map; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; @@ -44,6 +41,7 @@ import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; +import org.hamcrest.Matchers; import org.hl7.fhir.dstu3.model.BaseResource; import org.hl7.fhir.dstu3.model.Bundle; import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent; @@ -98,27 +96,23 @@ import org.junit.AfterClass; import org.junit.Ignore; import org.junit.Test; -import ca.uhn.fhir.jpa.dao.SearchParameterMap; -import ca.uhn.fhir.model.api.IQueryParameterType; +import com.google.common.collect.Lists; + import ca.uhn.fhir.model.primitive.InstantDt; import ca.uhn.fhir.model.primitive.UriDt; import ca.uhn.fhir.rest.api.MethodOutcome; import ca.uhn.fhir.rest.api.SummaryEnum; import ca.uhn.fhir.rest.client.IGenericClient; import ca.uhn.fhir.rest.param.DateRangeParam; -import ca.uhn.fhir.rest.param.HasParam; import ca.uhn.fhir.rest.param.ParamPrefixEnum; import ca.uhn.fhir.rest.param.StringAndListParam; import ca.uhn.fhir.rest.param.StringOrListParam; import ca.uhn.fhir.rest.param.StringParam; -import ca.uhn.fhir.rest.param.TokenParam; import ca.uhn.fhir.rest.server.Constants; -import ca.uhn.fhir.rest.server.IBundleProvider; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.PreconditionFailedException; import ca.uhn.fhir.rest.server.exceptions.ResourceGoneException; import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; -import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.util.BundleUtil; import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.UrlUtil; @@ -131,21 +125,11 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { public static void afterClassClearContext() { TestUtil.clearAllStaticFieldsForUnitTest(); } - protected List toUnqualifiedVersionlessIdValues(IBaseBundle theFound) { - List retVal = new ArrayList(); - List res = BundleUtil.toListOfResources(myFhirCtx, theFound); - int size = res.size(); - ourLog.info("Found {} results", size); - for (IBaseResource next : res) { - retVal.add(next.getIdElement().toUnqualifiedVersionless().getValue()); - } - return retVal; - } @Test public void testHasParameter() throws Exception { - IIdType pid0, pid1; + IIdType pid0; { Patient patient = new Patient(); patient.addIdentifier().setSystem("urn:system").setValue("001"); @@ -156,7 +140,7 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { Patient patient = new Patient(); patient.addIdentifier().setSystem("urn:system").setValue("001"); patient.addName().addFamily("Tester").addGiven("Joe"); - pid1 = myPatientDao.create(patient, mySrd).getId().toUnqualifiedVersionless(); + myPatientDao.create(patient, mySrd).getId().toUnqualifiedVersionless(); } { Observation obs = new Observation(); @@ -168,7 +152,7 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { Device device = new Device(); device.addIdentifier().setValue("DEVICEID"); IIdType devId = myDeviceDao.create(device, mySrd).getId().toUnqualifiedVersionless(); - + Observation obs = new Observation(); obs.addIdentifier().setSystem("urn:system").setValue("NOLINK"); obs.setDevice(new Reference(devId)); @@ -176,10 +160,56 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { } String uri = ourServerBase + "/Patient?_has:Observation:subject:identifier=" + UrlUtil.escape("urn:system|FOO"); - List ids = searchAndReturnUnqualifiedIdValues(uri); + List ids = searchAndReturnUnqualifiedVersionlessIdValues(uri); assertThat(ids, contains(pid0.getValue())); } - + + @Test + public void testHistoryWithAtParameter() throws Exception { + String methodName = "testHistoryWithFromAndTo"; + + Patient patient = new Patient(); + patient.addName().addFamily(methodName); + IIdType id = myPatientDao.create(patient, mySrd).getId().toUnqualifiedVersionless(); + + List preDates = Lists.newArrayList(); + List ids = Lists.newArrayList(); + for (int i = 0; i < 10; i++) { + Thread.sleep(10); + preDates.add(new Date()); + patient.setId(id); + patient.getName().get(0).getFamily().get(0).setValue(methodName + "_i"); + ids.add(myPatientDao.update(patient, mySrd).getId().toUnqualified().getValue()); + } + + List idValues; + + idValues = searchAndReturnUnqualifiedIdValues(ourServerBase + "/Patient/" + id.getIdPart() + "/_history?_at=gt" + toStr(preDates.get(0)) + "&_at=lt" + toStr(preDates.get(3))); + assertThat(idValues, contains(ids.get(2), ids.get(1), ids.get(0))); + + idValues = searchAndReturnUnqualifiedIdValues(ourServerBase + "/Patient/_history?_at=gt" + toStr(preDates.get(0)) + "&_at=lt" + toStr(preDates.get(3))); + assertThat(idValues, contains(ids.get(2), ids.get(1), ids.get(0))); + + idValues = searchAndReturnUnqualifiedIdValues(ourServerBase + "/_history?_at=gt" + toStr(preDates.get(0)) + "&_at=lt" + toStr(preDates.get(3))); + assertThat(idValues, contains(ids.get(2), ids.get(1), ids.get(0))); + + idValues = searchAndReturnUnqualifiedIdValues(ourServerBase + "/_history?_at=gt2060"); + assertThat(idValues, empty()); + + idValues = searchAndReturnUnqualifiedIdValues(ourServerBase + "/_history?_at=" + InstantDt.withCurrentTime().getYear()); + assertThat(idValues, hasSize(10)); // 10 is the page size + + idValues = searchAndReturnUnqualifiedIdValues(ourServerBase + "/_history?_at=ge" + InstantDt.withCurrentTime().getYear()); + assertThat(idValues, hasSize(10)); + + idValues = searchAndReturnUnqualifiedIdValues(ourServerBase + "/_history?_at=gt" + InstantDt.withCurrentTime().getYear()); + assertThat(idValues, hasSize(0)); + } + + private String toStr(Date theDate) { + return new InstantDt(theDate).getValueAsString(); + } + @Test public void testHasParameterNoResults() throws Exception { @@ -194,12 +224,11 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { } } - - private List searchAndReturnUnqualifiedIdValues(String uri) throws IOException, ClientProtocolException { + + private List searchAndReturnUnqualifiedVersionlessIdValues(String uri) throws IOException, ClientProtocolException { List ids; HttpGet get = new HttpGet(uri); - - + CloseableHttpResponse response = ourHttpClient.execute(get); try { String resp = IOUtils.toString(response.getEntity().getContent()); @@ -212,8 +241,22 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { return ids; } - - + private List searchAndReturnUnqualifiedIdValues(String uri) throws IOException, ClientProtocolException { + List ids; + HttpGet get = new HttpGet(uri); + + CloseableHttpResponse response = ourHttpClient.execute(get); + try { + String resp = IOUtils.toString(response.getEntity().getContent()); + ourLog.info(resp); + Bundle bundle = myFhirCtx.newXmlParser().parseResource(Bundle.class, resp); + ids = toUnqualifiedIdValues(bundle); + } finally { + IOUtils.closeQuietly(response); + } + return ids; + } + /** * Issue submitted by Bryn */ @@ -224,7 +267,6 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { ourClient.create().resource(input).execute().getResource(); } - @Test public void testSearchByExtendedChars() throws Exception { for (int i = 0; i < 10; i++) { @@ -233,7 +275,7 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { p.addIdentifier().setValue("ID" + i); myPatientDao.create(p, mySrd); } - + String uri = ourServerBase + "/Patient?name=" + URLEncoder.encode("Jernelöv", "UTF-8") + "&_count=5&_pretty=true"; ourLog.info("URI: {}", uri); HttpGet get = new HttpGet(uri); @@ -242,22 +284,20 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { assertEquals(200, resp.getStatusLine().getStatusCode()); String output = IOUtils.toString(resp.getEntity().getContent()); ourLog.info(output); - + Bundle b = myFhirCtx.newXmlParser().parseResource(Bundle.class, output); - + assertEquals("http://localhost:" + ourPort + "/fhir/context/Patient?_count=5&_pretty=true&name=Jernel%C3%B6v", b.getLink("self").getUrl()); - + Patient p = (Patient) b.getEntry().get(0).getResource(); assertEquals("Jernelöv", p.getName().get(0).getFamily().get(0).getValue()); - + } finally { IOUtils.closeQuietly(resp.getEntity().getContent()); } - - + } - - + @Override public void before() throws Exception { super.before(); @@ -576,7 +616,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { ourLog.info(responseString); assertEquals(400, response.getStatusLine().getStatusCode()); OperationOutcome oo = myFhirCtx.newXmlParser().parseResource(OperationOutcome.class, responseString); - assertEquals("Can not create resource with ID \"2\", ID must not be supplied on a create (POST) operation (use an HTTP PUT / update operation if you wish to supply an ID)", oo.getIssue().get(0).getDiagnostics()); + assertEquals("Can not create resource with ID \"2\", ID must not be supplied on a create (POST) operation (use an HTTP PUT / update operation if you wish to supply an ID)", + oo.getIssue().get(0).getDiagnostics()); } finally { response.getEntity().getContent().close(); @@ -659,7 +700,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { //@formatter:on fail(); } catch (PreconditionFailedException e) { - assertEquals("HTTP 412 Precondition Failed: Failed to DELETE resource with match URL \"Patient?identifier=testDeleteConditionalMultiple\" because this search matched 2 resources", e.getMessage()); + assertEquals("HTTP 412 Precondition Failed: Failed to DELETE resource with match URL \"Patient?identifier=testDeleteConditionalMultiple\" because this search matched 2 resources", + e.getMessage()); } // Not deleted yet.. @@ -791,8 +833,7 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { } /* - * Try it with a raw socket call. The Apache client won't let us use the unescaped "|" in the URL but we want to - * make sure that works too.. + * Try it with a raw socket call. The Apache client won't let us use the unescaped "|" in the URL but we want to make sure that works too.. */ Socket sock = new Socket(); sock.setSoTimeout(3000); @@ -1326,7 +1367,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { response.close(); } - get = new HttpGet(ourServerBase + "/Patient/" + pId.getIdPart() + "/$everything?_lastUpdated=%3E" + new InstantType(new Date(time2)).getValueAsString() + "&_lastUpdated=%3C" + new InstantType(new Date(time3)).getValueAsString()); + get = new HttpGet(ourServerBase + "/Patient/" + pId.getIdPart() + "/$everything?_lastUpdated=%3E" + new InstantType(new Date(time2)).getValueAsString() + "&_lastUpdated=%3C" + + new InstantType(new Date(time3)).getValueAsString()); response = ourHttpClient.execute(get); try { assertEquals(200, response.getStatusLine().getStatusCode()); @@ -1918,7 +1960,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { Patient patient = new Patient(); patient.addIdentifier().setSystem("urn:system").setValue("testSearchTokenParam001"); patient.addName().addFamily("Tester").addGiven("testSearchTokenParam1"); - patient.addCommunication().getLanguage().setText("testSearchTokenParamComText").addCoding().setCode("testSearchTokenParamCode").setSystem("testSearchTokenParamSystem").setDisplay("testSearchTokenParamDisplay"); + patient.addCommunication().getLanguage().setText("testSearchTokenParamComText").addCoding().setCode("testSearchTokenParamCode").setSystem("testSearchTokenParamSystem") + .setDisplay("testSearchTokenParamDisplay"); myPatientDao.create(patient, mySrd); patient = new Patient(); @@ -2635,7 +2678,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { ourLog.info(responseString); assertEquals(400, response.getStatusLine().getStatusCode()); OperationOutcome oo = myFhirCtx.newXmlParser().parseResource(OperationOutcome.class, responseString); - assertThat(oo.getIssue().get(0).getDiagnostics(), containsString("Can not update resource, resource body must contain an ID element which matches the request URL for update (PUT) operation - Resource body ID of \"333\" does not match URL ID of \"2\"")); + assertThat(oo.getIssue().get(0).getDiagnostics(), containsString( + "Can not update resource, resource body must contain an ID element which matches the request URL for update (PUT) operation - Resource body ID of \"333\" does not match URL ID of \"2\"")); } finally { response.close(); } @@ -2659,7 +2703,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { ourLog.info(resp); assertEquals(412, response.getStatusLine().getStatusCode()); assertThat(resp, not(containsString("Resource has no id"))); - assertThat(resp, stringContainsInOrder(">ERROR<", "[Patient.contact]", "
SHALL at least contain a contact's details or a reference to an organization", ""));
+			assertThat(resp,
+					stringContainsInOrder(">ERROR<", "[Patient.contact]", "
SHALL at least contain a contact's details or a reference to an organization", ""));
 		} finally {
 			IOUtils.closeQuietly(response.getEntity().getContent());
 			response.close();
@@ -2785,7 +2830,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test {
 			assertEquals(200, response.getStatusLine().getStatusCode());
 			assertThat(resp, not(containsString("Resource has no id")));
 			assertThat(resp, containsString("
No issues detected during validation
")); - assertThat(resp, stringContainsInOrder("", "", "", "", "")); + assertThat(resp, + stringContainsInOrder("", "", "", "", "")); } finally { IOUtils.closeQuietly(response.getEntity().getContent()); response.close(); @@ -2810,7 +2856,8 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { assertEquals(200, response.getStatusLine().getStatusCode()); assertThat(resp, not(containsString("Resource has no id"))); assertThat(resp, containsString("
No issues detected during validation
")); - assertThat(resp, stringContainsInOrder("", "", "", "", "")); + assertThat(resp, + stringContainsInOrder("", "", "", "", "")); } finally { IOUtils.closeQuietly(response.getEntity().getContent()); response.close(); @@ -2831,17 +2878,17 @@ public class ResourceProviderDstu3Test extends BaseResourceProviderDstu3Test { String resp = IOUtils.toString(response.getEntity().getContent()); ourLog.info(resp); assertEquals(200, response.getStatusLine().getStatusCode()); - assertThat(resp, containsString("")); + assertThat(resp, containsString("")); assertThat(resp, containsString("")); - assertThat(resp, containsString("")); + assertThat(resp, containsString("")); assertThat(resp, containsString("")); assertThat(resp, containsString("")); - assertThat(resp, containsString("")); + assertThat(resp, containsString("")); assertThat(resp, containsString("")); assertThat(resp, containsString("")); assertThat(resp, containsString("")); assertThat(resp, containsString("")); - assertThat(resp, containsString("")); + assertThat(resp, containsString("")); assertThat(resp, containsString("")); assertThat(resp, containsString("")); } finally { diff --git a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/ResourceProviderDstu3ValueSetTest.java b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/ResourceProviderDstu3ValueSetTest.java index 1e7ab182bdf..a5e0330712f 100644 --- a/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/ResourceProviderDstu3ValueSetTest.java +++ b/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/ResourceProviderDstu3ValueSetTest.java @@ -172,7 +172,7 @@ public class ResourceProviderDstu3ValueSetTest extends BaseResourceProviderDstu3 .execute(); fail(); } catch (InvalidRequestException e) { - assertEquals("HTTP 400 Bad Request: $expand must EITHER be invoked at the type level, or have an identifier specified, or have a ValueSet specified. Can not combine these options.", e.getMessage()); + assertEquals("HTTP 400 Bad Request: $expand must EITHER be invoked at the instance level, or have an identifier specified, or have a ValueSet specified. Can not combine these options.", e.getMessage()); } //@formatter:on @@ -188,7 +188,7 @@ public class ResourceProviderDstu3ValueSetTest extends BaseResourceProviderDstu3 .execute(); fail(); } catch (InvalidRequestException e) { - assertEquals("HTTP 400 Bad Request: $expand must EITHER be invoked at the type level, or have an identifier specified, or have a ValueSet specified. Can not combine these options.", e.getMessage()); + assertEquals("HTTP 400 Bad Request: $expand must EITHER be invoked at the instance level, or have an identifier specified, or have a ValueSet specified. Can not combine these options.", e.getMessage()); } //@formatter:on diff --git a/hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/param/DateRangeParamTest.java b/hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/param/DateRangeParamTest.java index c465c84f54b..bc7783f1b3c 100644 --- a/hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/param/DateRangeParamTest.java +++ b/hapi-fhir-structures-dstu/src/test/java/ca/uhn/fhir/rest/param/DateRangeParamTest.java @@ -46,6 +46,13 @@ public class DateRangeParamTest { DateRangeParam range = new DateRangeParam(startDateTime, endDateTime); assertEquals("2009-12-31T19:00:00.000-05:00", range.getValuesAsQueryTokens().get(0).getValueAsString()); + assertEquals("2009-12-31T19:00:00.100-05:00", range.getValuesAsQueryTokens().get(1).getValueAsString()); + + // Now try with arguments reversed (should still create same range) + range = new DateRangeParam(endDateTime, startDateTime); + assertEquals("2009-12-31T19:00:00.000-05:00", range.getValuesAsQueryTokens().get(0).getValueAsString()); + assertEquals("2009-12-31T19:00:00.100-05:00", range.getValuesAsQueryTokens().get(1).getValueAsString()); + } finally { TimeZone.setDefault(tz); } diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/model/primitive/BaseDateTimeDtDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/model/primitive/BaseDateTimeDtDstu2Test.java index b898bd501d2..d983eb467b2 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/model/primitive/BaseDateTimeDtDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/model/primitive/BaseDateTimeDtDstu2Test.java @@ -32,10 +32,126 @@ public class BaseDateTimeDtDstu2Test { private static FhirContext ourCtx = FhirContext.forDstu2(); private static Locale ourDefaultLocale; private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BaseDateTimeDtDstu2Test.class); - private SimpleDateFormat myDateInstantParser; - private FastDateFormat myDateInstantZoneParser; + + @Test + public void testSetPartialsYearFromExisting() { + InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00"); + dt.setYear(2016); + assertEquals(2016, dt.getYear().intValue()); + String valueAsString = dt.getValueAsString(); + ourLog.info(valueAsString); + assertEquals("2016-03-11T15:44:13.27564757855254768473697463986328969635-08:00", valueAsString); + } + + @Test + public void testSetPartialsMonthFromExisting() { + InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00"); + dt.setMonth(3); + assertEquals(3, dt.getMonth().intValue()); + String valueAsString = dt.getValueAsString(); + ourLog.info(valueAsString); + assertEquals("2011-04-11T15:44:13.27564757855254768473697463986328969635-08:00", valueAsString); + } + + @Test + public void testSetPartialsDayFromExisting() { + InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00"); + dt.setDay(15); + assertEquals(15, dt.getDay().intValue()); + String valueAsString = dt.getValueAsString(); + ourLog.info(valueAsString); + assertEquals("2011-03-15T15:44:13.27564757855254768473697463986328969635-08:00", valueAsString); + } + + @Test + public void testSetPartialsHourFromExisting() { + InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00"); + dt.setHour(23); + assertEquals(23, dt.getHour().intValue()); + String valueAsString = dt.getValueAsString(); + ourLog.info(valueAsString); + assertEquals("2011-03-11T23:44:13.27564757855254768473697463986328969635-08:00", valueAsString); + } + + @Test + public void testSetPartialsMinuteFromExisting() { + InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00"); + dt.setMinute(54); + assertEquals(54, dt.getMinute().intValue()); + String valueAsString = dt.getValueAsString(); + ourLog.info(valueAsString); + assertEquals("2011-03-11T15:54:13.27564757855254768473697463986328969635-08:00", valueAsString); + } + + @Test + public void testSetPartialsSecondFromExisting() { + InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00"); + dt.setSecond(1); + assertEquals(1, dt.getSecond().intValue()); + String valueAsString = dt.getValueAsString(); + ourLog.info(valueAsString); + assertEquals("2011-03-11T15:44:01.27564757855254768473697463986328969635-08:00", valueAsString); + } + + @Test + public void testSetPartialsMillisFromExisting() { + InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00"); + dt.setMillis(12); + assertEquals(12, dt.getMillis().intValue()); + assertEquals(12 * BaseDateTimeDt.NANOS_PER_MILLIS, dt.getNanos().longValue()); + String valueAsString = dt.getValueAsString(); + ourLog.info(valueAsString); + assertEquals("2011-03-11T15:44:13.012-08:00", valueAsString); + } + + @Test + public void testSetPartialsNanosFromExisting() { + InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00"); + dt.setNanos(100000000L); + assertEquals(100000000L, dt.getNanos().longValue()); + assertEquals(100, dt.getMillis().intValue()); + String valueAsString = dt.getValueAsString(); + ourLog.info(valueAsString); + assertEquals("2011-03-11T15:44:13.100-08:00", valueAsString); + } + + @Test + public void testSetPartialsInvalid() { + InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00"); + dt.setNanos(0); + dt.setNanos(BaseDateTimeDt.NANOS_PER_SECOND - 1); + try { + dt.setNanos(BaseDateTimeDt.NANOS_PER_SECOND); + } catch (IllegalArgumentException e) { + assertEquals("Value 1000000000 is not between allowable range: 0 - 999999999", e.getMessage()); + } + } + + @Test + public void testGetPartials() { + InstantDt dt = new InstantDt("2011-03-11T15:44:13.27564757855254768473697463986328969635-08:00"); + assertEquals(2011, dt.getYear().intValue()); + assertEquals(2, dt.getMonth().intValue()); + assertEquals(11, dt.getDay().intValue()); + assertEquals(15, dt.getHour().intValue()); + assertEquals(44, dt.getMinute().intValue()); + assertEquals(13, dt.getSecond().intValue()); + assertEquals(275, dt.getMillis().intValue()); + assertEquals(275647578L, dt.getNanos().longValue()); + + dt = new InstantDt(); + assertEquals(null, dt.getYear()); + assertEquals(null, dt.getMonth()); + assertEquals(null, dt.getDay()); + assertEquals(null, dt.getHour()); + assertEquals(null, dt.getMinute()); + assertEquals(null, dt.getSecond()); + assertEquals(null, dt.getMillis()); + assertEquals(null, dt.getNanos()); + } + @Before public void before() { myDateInstantParser = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); @@ -49,7 +165,7 @@ public class BaseDateTimeDtDstu2Test { dt.setTimeZoneZulu(true); assertEquals("1995-11-15T04:58:08Z", dt.getValueAsString()); } - + /** * Test for #57 */ @@ -194,10 +310,10 @@ public class BaseDateTimeDtDstu2Test { @Test public void testGetValueAsCalendar() { assertNull(new InstantDt().getValueAsCalendar()); - + InstantDt dt = new InstantDt("2011-01-03T07:11:22.002-08:00"); GregorianCalendar cal = dt.getValueAsCalendar(); - + assertEquals(2011, cal.get(Calendar.YEAR)); assertEquals(7, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(2, cal.get(Calendar.MILLISECOND)); diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/model/primitive/UriDtTest.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/model/primitive/UriDtTest.java new file mode 100644 index 00000000000..b371a8c984d --- /dev/null +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/model/primitive/UriDtTest.java @@ -0,0 +1,56 @@ +package ca.uhn.fhir.model.primitive; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class UriDtTest { + + @Test + public void testFromOid() { + UriDt uri = UriDt.fromOid("0.1.2.3.4"); + assertEquals("urn:oid:0.1.2.3.4", uri.getValue()); + } + + @Test + public void testFromOidNull() { + UriDt uri = UriDt.fromOid(null); + assertEquals(null, uri.getValue()); + } + + @Test + public void testEqualsObject() { + UriDt dt = new UriDt("http://example.com/foo"); + assertTrue(dt.equals(dt)); + assertFalse(dt.equals(null)); + assertFalse(dt.equals(new UriDt())); + assertTrue(dt.equals(new UriDt("http://example.com/foo"))); + assertTrue(dt.equals(new UriDt("http://example.com/foo/"))); + assertFalse(dt.equals(new UriDt("http://blah.com/foo/"))); + assertFalse(dt.equals(new StringDt("http://example.com/foo"))); + } + + @Test + public void testEqualsString() { + UriDt dt = new UriDt("http://example.com/foo"); + assertTrue(dt.equals("http://example.com/foo")); + } + + @Test + public void testHashCode() { + UriDt dt = new UriDt("http://example.com/foo"); + assertEquals(-1671329151, dt.hashCode()); + + dt = new UriDt(); + assertEquals(31, dt.hashCode()); + + } + + @Test + public void testSetInvalid() { + UriDt dt = new UriDt(); + dt.setValue("blah : // AA"); + dt.hashCode(); + } + +} diff --git a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/parser/XmlParserDstu2Test.java b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/parser/XmlParserDstu2Test.java index 0f3fcfc00e3..c3f9d24b228 100644 --- a/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/parser/XmlParserDstu2Test.java +++ b/hapi-fhir-structures-dstu2/src/test/java/ca/uhn/fhir/parser/XmlParserDstu2Test.java @@ -1040,8 +1040,11 @@ public class XmlParserDstu2Test { } + /** + * Make sure whitespace is preserved for pre tags + */ @Test - public void testEncodeDivWithPre() { + public void testEncodeDivWithPrePrettyPrint() { Patient p = new Patient(); p.getText().setDiv("
\n\n

A P TAG

line1\nline2\nline3  BOLD

"); @@ -1059,6 +1062,28 @@ public class XmlParserDstu2Test { } + /** + * Make sure whitespace is preserved for pre tags + */ + @Test + public void testEncodeDivWithPreNonPrettyPrint() { + + Patient p = new Patient(); + p.getText().setDiv("
\n\n

A P TAG

line1\nline2\nline3  BOLD

"); + + String output = ourCtx.newXmlParser().setPrettyPrint(false).encodeResourceToString(p); + ourLog.info(output); + + //@formatter:off + assertThat(output, stringContainsInOrder( + "A P TAG

", + "

line1\nline2\nline3  BOLD
" + )); + //@formatter:on + + } + @Test public void testEncodeDoesntIncludeUuidId() { Patient p = new Patient(); diff --git a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/parser/XmlParserDstu3Test.java b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/parser/XmlParserDstu3Test.java index 2cbc238f7c8..213a0e0a208 100644 --- a/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/parser/XmlParserDstu3Test.java +++ b/hapi-fhir-structures-dstu3/src/test/java/ca/uhn/fhir/parser/XmlParserDstu3Test.java @@ -119,8 +119,31 @@ public class XmlParserDstu3Test { ourCtx.setNarrativeGenerator(null); } + /** + * Make sure whitespace is preserved for pre tags + */ @Test - public void testEncodeDivWithPre() { + public void testEncodeDivWithPreNonPrettyPrint() { + + Patient p = new Patient(); + p.getText().setDivAsString("
\n\n

A P TAG

line1\nline2\nline3  BOLD

"); + + String output = ourCtx.newXmlParser().setPrettyPrint(false).encodeResourceToString(p); + ourLog.info(output); + + //@formatter:off + assertThat(output, stringContainsInOrder( + "A P TAG

", + "

line1\nline2\nline3  BOLD
" + )); + //@formatter:on + + } + + + @Test + public void testEncodeDivWithPrePrettyPrint() { Patient p = new Patient(); p.getText().setDivAsString("
\n\n

A P TAG

line1\nline2\nline3  BOLD

");