Clean up terminology uploading

This commit is contained in:
jamesagnew 2018-07-15 15:22:52 -04:00
parent 36b4ed28e4
commit 43ac912033
13 changed files with 421 additions and 305 deletions

View File

@ -1,7 +1,34 @@
package ca.uhn.fhir.context; package ca.uhn.fhir.context;
import ca.uhn.fhir.context.api.AddProfileTagEnum;
import ca.uhn.fhir.context.support.IContextValidationSupport;
import ca.uhn.fhir.fluentpath.IFluentPath;
import ca.uhn.fhir.i18n.HapiLocalizer;
import ca.uhn.fhir.model.api.IElement;
import ca.uhn.fhir.model.api.IFhirVersion;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.view.ViewGenerator;
import ca.uhn.fhir.narrative.INarrativeGenerator;
import ca.uhn.fhir.parser.*;
import ca.uhn.fhir.rest.api.IVersionSpecificBundleFactory;
import ca.uhn.fhir.rest.client.api.IBasicClient;
import ca.uhn.fhir.rest.client.api.IGenericClient;
import ca.uhn.fhir.rest.client.api.IRestfulClient;
import ca.uhn.fhir.rest.client.api.IRestfulClientFactory;
import ca.uhn.fhir.util.FhirTerser;
import ca.uhn.fhir.util.ReflectionUtil;
import ca.uhn.fhir.util.VersionUtil;
import ca.uhn.fhir.validation.FhirValidator;
import org.apache.commons.lang3.Validate;
import org.hl7.fhir.instance.model.api.IBase;
import org.hl7.fhir.instance.model.api.IBaseBundle;
import org.hl7.fhir.instance.model.api.IBaseResource;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.Map.Entry;
/* /*
* #%L * #%L
@ -23,26 +50,6 @@ import java.lang.reflect.Method;
* #L% * #L%
*/ */
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.Map.Entry;
import org.apache.commons.lang3.Validate;
import org.hl7.fhir.instance.model.api.*;
import ca.uhn.fhir.context.api.AddProfileTagEnum;
import ca.uhn.fhir.context.support.IContextValidationSupport;
import ca.uhn.fhir.fluentpath.IFluentPath;
import ca.uhn.fhir.i18n.HapiLocalizer;
import ca.uhn.fhir.model.api.*;
import ca.uhn.fhir.model.view.ViewGenerator;
import ca.uhn.fhir.narrative.INarrativeGenerator;
import ca.uhn.fhir.parser.*;
import ca.uhn.fhir.rest.api.IVersionSpecificBundleFactory;
import ca.uhn.fhir.rest.client.api.*;
import ca.uhn.fhir.util.*;
import ca.uhn.fhir.validation.FhirValidator;
/** /**
* The FHIR context is the central starting point for the use of the HAPI FHIR API. It should be created once, and then * The FHIR context is the central starting point for the use of the HAPI FHIR API. It should be created once, and then
* used as a factory for various other types of objects (parsers, clients, etc.). * used as a factory for various other types of objects (parsers, clients, etc.).
@ -68,6 +75,7 @@ public class FhirContext {
private static final List<Class<? extends IBaseResource>> EMPTY_LIST = Collections.emptyList(); private static final List<Class<? extends IBaseResource>> EMPTY_LIST = Collections.emptyList();
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirContext.class); private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(FhirContext.class);
private final IFhirVersion myVersion;
private AddProfileTagEnum myAddProfileTagWhenEncoding = AddProfileTagEnum.ONLY_FOR_CUSTOM; private AddProfileTagEnum myAddProfileTagWhenEncoding = AddProfileTagEnum.ONLY_FOR_CUSTOM;
private volatile Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> myClassToElementDefinition = Collections.emptyMap(); private volatile Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> myClassToElementDefinition = Collections.emptyMap();
private ArrayList<Class<? extends IBase>> myCustomTypes; private ArrayList<Class<? extends IBase>> myCustomTypes;
@ -87,9 +95,6 @@ public class FhirContext {
private volatile IRestfulClientFactory myRestfulClientFactory; private volatile IRestfulClientFactory myRestfulClientFactory;
private volatile RuntimeChildUndeclaredExtensionDefinition myRuntimeChildUndeclaredExtensionDefinition; private volatile RuntimeChildUndeclaredExtensionDefinition myRuntimeChildUndeclaredExtensionDefinition;
private IContextValidationSupport<?, ?, ?, ?, ?, ?> myValidationSupport; private IContextValidationSupport<?, ?, ?, ?, ?, ?> myValidationSupport;
private final IFhirVersion myVersion;
private Map<FhirVersionEnum, Map<String, Class<? extends IBaseResource>>> myVersionToNameToResourceType = Collections.emptyMap(); private Map<FhirVersionEnum, Map<String, Class<? extends IBaseResource>>> myVersionToNameToResourceType = Collections.emptyMap();
/** /**
@ -208,6 +213,30 @@ public class FhirContext {
return myAddProfileTagWhenEncoding; return myAddProfileTagWhenEncoding;
} }
/**
* When encoding resources, this setting configures the parser to include
* an entry in the resource's metadata section which indicates which profile(s) the
* resource claims to conform to. The default is {@link AddProfileTagEnum#ONLY_FOR_CUSTOM}.
* <p>
* This feature is intended for situations where custom resource types are being used,
* avoiding the need to manually add profile declarations for these custom types.
* </p>
* <p>
* See <a href="http://jamesagnew.gihhub.io/hapi-fhir/doc_extensions.html">Profiling and Extensions</a>
* for more information on using custom types.
* </p>
* <p>
* Note that this feature automatically adds the profile, but leaves any profile tags
* which have been manually added in place as well.
* </p>
*
* @param theAddProfileTagWhenEncoding The add profile mode (must not be <code>null</code>)
*/
public void setAddProfileTagWhenEncoding(AddProfileTagEnum theAddProfileTagWhenEncoding) {
Validate.notNull(theAddProfileTagWhenEncoding, "theAddProfileTagWhenEncoding must not be null");
myAddProfileTagWhenEncoding = theAddProfileTagWhenEncoding;
}
Collection<RuntimeResourceDefinition> getAllResourceDefinitions() { Collection<RuntimeResourceDefinition> getAllResourceDefinitions() {
validateInitialized(); validateInitialized();
return myNameToResourceDefinition.values(); return myNameToResourceDefinition.values();
@ -249,7 +278,9 @@ public class FhirContext {
return myNameToElementDefinition.get(theElementName.toLowerCase()); return myNameToElementDefinition.get(theElementName.toLowerCase());
} }
/** For unit tests only */ /**
* For unit tests only
*/
int getElementDefinitionCount() { int getElementDefinitionCount() {
validateInitialized(); validateInitialized();
return myClassToElementDefinition.size(); return myClassToElementDefinition.size();
@ -274,10 +305,22 @@ public class FhirContext {
return myLocalizer; return myLocalizer;
} }
/**
* This feature is not yet in its final state and should be considered an internal part of HAPI for now - use with
* caution
*/
public void setLocalizer(HapiLocalizer theMessages) {
myLocalizer = theMessages;
}
public INarrativeGenerator getNarrativeGenerator() { public INarrativeGenerator getNarrativeGenerator() {
return myNarrativeGenerator; return myNarrativeGenerator;
} }
public void setNarrativeGenerator(INarrativeGenerator theNarrativeGenerator) {
myNarrativeGenerator = theNarrativeGenerator;
}
/** /**
* Returns the parser options object which will be used to supply default * Returns the parser options object which will be used to supply default
* options to newly created parsers * options to newly created parsers
@ -288,6 +331,17 @@ public class FhirContext {
return myParserOptions; return myParserOptions;
} }
/**
* Sets the parser options object which will be used to supply default
* options to newly created parsers
*
* @param theParserOptions The parser options object - Must not be <code>null</code>
*/
public void setParserOptions(ParserOptions theParserOptions) {
Validate.notNull(theParserOptions, "theParserOptions must not be null");
myParserOptions = theParserOptions;
}
/** /**
* Get the configured performance options * Get the configured performance options
*/ */
@ -295,6 +349,32 @@ public class FhirContext {
return myPerformanceOptions; return myPerformanceOptions;
} }
// /**
// * Return an unmodifiable collection containing all known resource definitions
// */
// public Collection<RuntimeResourceDefinition> getResourceDefinitions() {
//
// Set<Class<? extends IBase>> datatypes = Collections.emptySet();
// Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> existing = Collections.emptyMap();
// HashMap<String, Class<? extends IBaseResource>> types = new HashMap<String, Class<? extends IBaseResource>>();
// ModelScanner.scanVersionPropertyFile(datatypes, types, myVersion.getVersion(), existing);
// for (int next : types.)
//
// return Collections.unmodifiableCollection(myIdToResourceDefinition.values());
// }
/**
* Sets the configured performance options
*
* @see PerformanceOptionsEnum for a list of available options
*/
public void setPerformanceOptions(Collection<PerformanceOptionsEnum> theOptions) {
myPerformanceOptions.clear();
if (theOptions != null) {
myPerformanceOptions.addAll(theOptions);
}
}
/** /**
* Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed * Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
* for extending the core library. * for extending the core library.
@ -359,8 +439,12 @@ public class FhirContext {
* <p> * <p>
* Note that this method is case insensitive! * Note that this method is case insensitive!
* </p> * </p>
*
* @throws DataFormatException If the resource name is not known
*/ */
public RuntimeResourceDefinition getResourceDefinition(String theResourceName) { // Multiple spots in HAPI FHIR and Smile CDR depend on DataFormatException being
// thrown by this method, don't change that.
public RuntimeResourceDefinition getResourceDefinition(String theResourceName) throws DataFormatException {
validateInitialized(); validateInitialized();
Validate.notBlank(theResourceName, "theResourceName must not be blank"); Validate.notBlank(theResourceName, "theResourceName must not be blank");
@ -380,20 +464,6 @@ public class FhirContext {
return retVal; return retVal;
} }
// /**
// * Return an unmodifiable collection containing all known resource definitions
// */
// public Collection<RuntimeResourceDefinition> getResourceDefinitions() {
//
// Set<Class<? extends IBase>> datatypes = Collections.emptySet();
// Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> existing = Collections.emptyMap();
// HashMap<String, Class<? extends IBaseResource>> types = new HashMap<String, Class<? extends IBaseResource>>();
// ModelScanner.scanVersionPropertyFile(datatypes, types, myVersion.getVersion(), existing);
// for (int next : types.)
//
// return Collections.unmodifiableCollection(myIdToResourceDefinition.values());
// }
/** /**
* Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed * Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
* for extending the core library. * for extending the core library.
@ -412,6 +482,36 @@ public class FhirContext {
return myIdToResourceDefinition.values(); return myIdToResourceDefinition.values();
} }
/**
* Returns an unmodifiable set containing all resource names known to this
* context
*/
public Set<String> getResourceNames() {
Set<String> resourceNames = new HashSet<>();
if (myNameToResourceDefinition.isEmpty()) {
Properties props = new Properties();
try {
props.load(myVersion.getFhirVersionPropertiesFile());
} catch (IOException theE) {
throw new ConfigurationException("Failed to load version properties file");
}
Enumeration<?> propNames = props.propertyNames();
while (propNames.hasMoreElements()) {
String next = (String) propNames.nextElement();
if (next.startsWith("resource.")) {
resourceNames.add(next.substring("resource.".length()).trim());
}
}
}
for (RuntimeResourceDefinition next : myNameToResourceDefinition.values()) {
resourceNames.add(next.getName());
}
return Collections.unmodifiableSet(resourceNames);
}
/** /**
* Get the restful client factory. If no factory has been set, this will be initialized with * Get the restful client factory. If no factory has been set, this will be initialized with
* a new ApacheRestfulClientFactory. * a new ApacheRestfulClientFactory.
@ -429,6 +529,16 @@ public class FhirContext {
return myRestfulClientFactory; return myRestfulClientFactory;
} }
/**
* Set the restful client factory
*
* @param theRestfulClientFactory
*/
public void setRestfulClientFactory(IRestfulClientFactory theRestfulClientFactory) {
Validate.notNull(theRestfulClientFactory, "theRestfulClientFactory must not be null");
this.myRestfulClientFactory = theRestfulClientFactory;
}
public RuntimeChildUndeclaredExtensionDefinition getRuntimeChildUndeclaredExtensionDefinition() { public RuntimeChildUndeclaredExtensionDefinition getRuntimeChildUndeclaredExtensionDefinition() {
validateInitialized(); validateInitialized();
return myRuntimeChildUndeclaredExtensionDefinition; return myRuntimeChildUndeclaredExtensionDefinition;
@ -448,6 +558,15 @@ public class FhirContext {
return myValidationSupport; return myValidationSupport;
} }
/**
* Sets the validation support module to use for this context. The validation support module
* is used to supply underlying infrastructure such as conformance resources (StructureDefinition, ValueSet, etc)
* as well as to provide terminology services to modules such as the validator and FluentPath executor
*/
public void setValidationSupport(IContextValidationSupport<?, ?, ?, ?, ?, ?> theValidationSupport) {
myValidationSupport = theValidationSupport;
}
public IFhirVersion getVersion() { public IFhirVersion getVersion() {
return myVersion; return myVersion;
} }
@ -519,13 +638,10 @@ public class FhirContext {
* without incurring any performance penalty * without incurring any performance penalty
* </p> * </p>
* *
* @param theClientType * @param theClientType The client type, which is an interface type to be instantiated
* The client type, which is an interface type to be instantiated * @param theServerBase The URL of the base for the restful FHIR server to connect to
* @param theServerBase
* The URL of the base for the restful FHIR server to connect to
* @return A newly created client * @return A newly created client
* @throws ConfigurationException * @throws ConfigurationException If the interface type is not an interface
* If the interface type is not an interface
*/ */
public <T extends IRestfulClient> T newRestfulClient(Class<T> theClientType, String theServerBase) { public <T extends IRestfulClient> T newRestfulClient(Class<T> theClientType, String theServerBase) {
return getRestfulClientFactory().newClient(theClientType, theServerBase); return getRestfulClientFactory().newClient(theClientType, theServerBase);
@ -541,8 +657,7 @@ public class FhirContext {
* without incurring any performance penalty * without incurring any performance penalty
* </p> * </p>
* *
* @param theServerBase * @param theServerBase The URL of the base for the restful FHIR server to connect to
* The URL of the base for the restful FHIR server to connect to
*/ */
public IGenericClient newRestfulGenericClient(String theServerBase) { public IGenericClient newRestfulGenericClient(String theServerBase) {
return getRestfulClientFactory().newGenericClient(theServerBase); return getRestfulClientFactory().newGenericClient(theServerBase);
@ -593,8 +708,7 @@ public class FhirContext {
* threads are able to call any methods on this context. * threads are able to call any methods on this context.
* </p> * </p>
* *
* @param theType * @param theType The custom type to add (must not be <code>null</code>)
* The custom type to add (must not be <code>null</code>)
*/ */
public void registerCustomType(Class<? extends IBase> theType) { public void registerCustomType(Class<? extends IBase> theType) {
Validate.notNull(theType, "theType must not be null"); Validate.notNull(theType, "theType must not be null");
@ -613,8 +727,7 @@ public class FhirContext {
* threads are able to call any methods on this context. * threads are able to call any methods on this context.
* </p> * </p>
* *
* @param theTypes * @param theTypes The custom types to add (must not be <code>null</code> or contain null elements in the collection)
* The custom types to add (must not be <code>null</code> or contain null elements in the collection)
*/ */
public void registerCustomTypes(Collection<Class<? extends IBase>> theTypes) { public void registerCustomTypes(Collection<Class<? extends IBase>> theTypes) {
Validate.notNull(theTypes, "theTypes must not be null"); Validate.notNull(theTypes, "theTypes must not be null");
@ -698,31 +811,6 @@ public class FhirContext {
return classToElementDefinition; return classToElementDefinition;
} }
/**
* When encoding resources, this setting configures the parser to include
* an entry in the resource's metadata section which indicates which profile(s) the
* resource claims to conform to. The default is {@link AddProfileTagEnum#ONLY_FOR_CUSTOM}.
* <p>
* This feature is intended for situations where custom resource types are being used,
* avoiding the need to manually add profile declarations for these custom types.
* </p>
* <p>
* See <a href="http://jamesagnew.gihhub.io/hapi-fhir/doc_extensions.html">Profiling and Extensions</a>
* for more information on using custom types.
* </p>
* <p>
* Note that this feature automatically adds the profile, but leaves any profile tags
* which have been manually added in place as well.
* </p>
*
* @param theAddProfileTagWhenEncoding
* The add profile mode (must not be <code>null</code>)
*/
public void setAddProfileTagWhenEncoding(AddProfileTagEnum theAddProfileTagWhenEncoding) {
Validate.notNull(theAddProfileTagWhenEncoding, "theAddProfileTagWhenEncoding must not be null");
myAddProfileTagWhenEncoding = theAddProfileTagWhenEncoding;
}
/** /**
* Sets the default type which will be used when parsing a resource that is found to be * Sets the default type which will be used when parsing a resource that is found to be
* of the given profile. * of the given profile.
@ -733,11 +821,9 @@ public class FhirContext {
* the <code>MyPatient</code> type will be used unless otherwise specified. * the <code>MyPatient</code> type will be used unless otherwise specified.
* </p> * </p>
* *
* @param theProfile * @param theProfile The profile string, e.g. <code>"http://example.com/some_patient_profile"</code>. Must not be
* The profile string, e.g. <code>"http://example.com/some_patient_profile"</code>. Must not be
* <code>null</code> or empty. * <code>null</code> or empty.
* @param theClass * @param theClass The resource type, or <code>null</code> to clear any existing type
* The resource type, or <code>null</code> to clear any existing type
*/ */
public void setDefaultTypeForProfile(String theProfile, Class<? extends IBaseResource> theClass) { public void setDefaultTypeForProfile(String theProfile, Class<? extends IBaseResource> theClass) {
Validate.notBlank(theProfile, "theProfile must not be null or empty"); Validate.notBlank(theProfile, "theProfile must not be null or empty");
@ -748,53 +834,16 @@ public class FhirContext {
} }
} }
/**
* This feature is not yet in its final state and should be considered an internal part of HAPI for now - use with
* caution
*/
public void setLocalizer(HapiLocalizer theMessages) {
myLocalizer = theMessages;
}
public void setNarrativeGenerator(INarrativeGenerator theNarrativeGenerator) {
myNarrativeGenerator = theNarrativeGenerator;
}
/** /**
* Sets a parser error handler to use by default on all parsers * Sets a parser error handler to use by default on all parsers
* *
* @param theParserErrorHandler * @param theParserErrorHandler The error handler
* The error handler
*/ */
public void setParserErrorHandler(IParserErrorHandler theParserErrorHandler) { public void setParserErrorHandler(IParserErrorHandler theParserErrorHandler) {
Validate.notNull(theParserErrorHandler, "theParserErrorHandler must not be null"); Validate.notNull(theParserErrorHandler, "theParserErrorHandler must not be null");
myParserErrorHandler = theParserErrorHandler; myParserErrorHandler = theParserErrorHandler;
} }
/**
* Sets the parser options object which will be used to supply default
* options to newly created parsers
*
* @param theParserOptions
* The parser options object - Must not be <code>null</code>
*/
public void setParserOptions(ParserOptions theParserOptions) {
Validate.notNull(theParserOptions, "theParserOptions must not be null");
myParserOptions = theParserOptions;
}
/**
* Sets the configured performance options
*
* @see PerformanceOptionsEnum for a list of available options
*/
public void setPerformanceOptions(Collection<PerformanceOptionsEnum> theOptions) {
myPerformanceOptions.clear();
if (theOptions != null) {
myPerformanceOptions.addAll(theOptions);
}
}
/** /**
* Sets the configured performance options * Sets the configured performance options
* *
@ -808,26 +857,7 @@ public class FhirContext {
setPerformanceOptions(asList); setPerformanceOptions(asList);
} }
/** @SuppressWarnings({"cast"})
* Set the restful client factory
*
* @param theRestfulClientFactory
*/
public void setRestfulClientFactory(IRestfulClientFactory theRestfulClientFactory) {
Validate.notNull(theRestfulClientFactory, "theRestfulClientFactory must not be null");
this.myRestfulClientFactory = theRestfulClientFactory;
}
/**
* Sets the validation support module to use for this context. The validation support module
* is used to supply underlying infrastructure such as conformance resources (StructureDefinition, ValueSet, etc)
* as well as to provide terminology services to modules such as the validator and FluentPath executor
*/
public void setValidationSupport(IContextValidationSupport<?, ?, ?, ?, ?, ?> theValidationSupport) {
myValidationSupport = theValidationSupport;
}
@SuppressWarnings({ "cast" })
private List<Class<? extends IElement>> toElementList(Collection<Class<? extends IBaseResource>> theResourceTypes) { private List<Class<? extends IElement>> toElementList(Collection<Class<? extends IBaseResource>> theResourceTypes) {
if (theResourceTypes == null) { if (theResourceTypes == null) {
return null; return null;
@ -858,13 +888,6 @@ public class FhirContext {
return new FhirContext(FhirVersionEnum.DSTU2); return new FhirContext(FhirVersionEnum.DSTU2);
} }
/**
* Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU2 DSTU2} (2016 May DSTU3 Snapshot)
*/
public static FhirContext forDstu2_1() {
return new FhirContext(FhirVersionEnum.DSTU2_1);
}
/** /**
* Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU2_HL7ORG DSTU2} (using the Reference * Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU2_HL7ORG DSTU2} (using the Reference
* Implementation Structures) * Implementation Structures)
@ -873,6 +896,13 @@ public class FhirContext {
return new FhirContext(FhirVersionEnum.DSTU2_HL7ORG); return new FhirContext(FhirVersionEnum.DSTU2_HL7ORG);
} }
/**
* Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU2 DSTU2} (2016 May DSTU3 Snapshot)
*/
public static FhirContext forDstu2_1() {
return new FhirContext(FhirVersionEnum.DSTU2_1);
}
/** /**
* Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU3 DSTU3} * Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU3 DSTU3}
* *
@ -891,7 +921,6 @@ public class FhirContext {
return new FhirContext(FhirVersionEnum.R4); return new FhirContext(FhirVersionEnum.R4);
} }
private static Collection<Class<? extends IBaseResource>> toCollection(Class<? extends IBaseResource> theResourceType) { private static Collection<Class<? extends IBaseResource>> toCollection(Class<? extends IBaseResource> theResourceType) {
ArrayList<Class<? extends IBaseResource>> retVal = new ArrayList<Class<? extends IBaseResource>>(1); ArrayList<Class<? extends IBaseResource>> retVal = new ArrayList<Class<? extends IBaseResource>>(1);
retVal.add(theResourceType); retVal.add(theResourceType);
@ -909,34 +938,4 @@ public class FhirContext {
} }
return retVal; return retVal;
} }
/**
* Returns an unmodifiable set containing all resource names known to this
* context
*/
public Set<String> getResourceNames() {
Set<String> resourceNames= new HashSet<>();
if (myNameToResourceDefinition.isEmpty()) {
Properties props = new Properties();
try {
props.load(myVersion.getFhirVersionPropertiesFile());
} catch (IOException theE) {
throw new ConfigurationException("Failed to load version properties file");
}
Enumeration<?> propNames = props.propertyNames();
while (propNames.hasMoreElements()){
String next = (String) propNames.nextElement();
if (next.startsWith("resource.")) {
resourceNames.add(next.substring("resource.".length()).trim());
}
}
}
for (RuntimeResourceDefinition next : myNameToResourceDefinition.values()) {
resourceNames.add(next.getName());
}
return Collections.unmodifiableSet(resourceNames);
}
} }

View File

@ -31,6 +31,13 @@
<appender-ref ref="STDOUT" /> <appender-ref ref="STDOUT" />
</logger> </logger>
<!--
It's useful to have this log when uploading big terminologies
-->
<logger name="ca.uhn.fhir.jpa.term.BaseHapiTerminologySvcImpl" additivity="false" level="info">
<appender-ref ref="STDOUT" />
</logger>
<root level="warn"> <root level="warn">
<appender-ref ref="STDOUT" /> <appender-ref ref="STDOUT" />

View File

@ -2060,10 +2060,6 @@ public abstract class BaseHapiFhirDao<T extends IBaseResource> implements IDao,
*/ */
if (theCreateNewHistoryEntry) { if (theCreateNewHistoryEntry) {
final ResourceHistoryTable historyEntry = theEntity.toHistory(); final ResourceHistoryTable historyEntry = theEntity.toHistory();
// if (theEntity.getVersion() > 1) {
// existing = myResourceHistoryTableDao.findForIdAndVersion(theEntity.getId(), theEntity.getVersion());
// ourLog.warn("Reusing existing history entry entity {}", theEntity.getIdDt().getValue());
// }
historyEntry.setEncoding(changed.getEncoding()); historyEntry.setEncoding(changed.getEncoding());
historyEntry.setResource(changed.getResource()); historyEntry.setResource(changed.getResource());

View File

@ -43,6 +43,9 @@ public interface ITermConceptDao extends JpaRepository<TermConcept, Long> {
@Query("SELECT t FROM TermConcept t WHERE t.myCodeSystem.myId = :cs_pid") @Query("SELECT t FROM TermConcept t WHERE t.myCodeSystem.myId = :cs_pid")
Slice<TermConcept> findByCodeSystemVersion(Pageable thePage, @Param("cs_pid") Long thePid); Slice<TermConcept> findByCodeSystemVersion(Pageable thePage, @Param("cs_pid") Long thePid);
@Query("SELECT COUNT(t) FROM TermConcept t WHERE t.myCodeSystem.myId = :cs_pid")
Integer countByCodeSystemVersion(@Param("cs_pid") Long thePid);
@Query("SELECT t FROM TermConcept t WHERE t.myIndexStatus = null") @Query("SELECT t FROM TermConcept t WHERE t.myIndexStatus = null")
Page<TermConcept> findResourcesRequiringReindexing(Pageable thePageRequest); Page<TermConcept> findResourcesRequiringReindexing(Pageable thePageRequest);

View File

@ -32,4 +32,7 @@ public interface ITermConceptDesignationDao extends JpaRepository<TermConceptDes
@Query("SELECT t FROM TermConceptDesignation t WHERE t.myCodeSystemVersion.myId = :csv_pid") @Query("SELECT t FROM TermConceptDesignation t WHERE t.myCodeSystemVersion.myId = :csv_pid")
Slice<TermConceptDesignation> findByCodeSystemVersion(Pageable thePage, @Param("csv_pid") Long thePid); Slice<TermConceptDesignation> findByCodeSystemVersion(Pageable thePage, @Param("csv_pid") Long thePid);
@Query("SELECT COUNT(t) FROM TermConceptDesignation t WHERE t.myCodeSystemVersion.myId = :csv_pid")
Integer countByCodeSystemVersion(@Param("csv_pid") Long thePid);
} }

View File

@ -31,6 +31,9 @@ import java.util.Collection;
public interface ITermConceptParentChildLinkDao extends JpaRepository<TermConceptParentChildLink, Long> { public interface ITermConceptParentChildLinkDao extends JpaRepository<TermConceptParentChildLink, Long> {
@Query("SELECT COUNT(t) FROM TermConceptParentChildLink t WHERE t.myCodeSystem.myId = :cs_pid")
Integer countByCodeSystemVersion(@Param("cs_pid") Long thePid);
@Query("SELECT t.myParentPid FROM TermConceptParentChildLink t WHERE t.myChildPid = :child_pid") @Query("SELECT t.myParentPid FROM TermConceptParentChildLink t WHERE t.myChildPid = :child_pid")
Collection<Long> findAllWithChild(@Param("child_pid") Long theConceptPid); Collection<Long> findAllWithChild(@Param("child_pid") Long theConceptPid);

View File

@ -32,4 +32,6 @@ public interface ITermConceptPropertyDao extends JpaRepository<TermConceptProper
@Query("SELECT t FROM TermConceptProperty t WHERE t.myCodeSystemVersion.myId = :cs_pid") @Query("SELECT t FROM TermConceptProperty t WHERE t.myCodeSystemVersion.myId = :cs_pid")
Slice<TermConceptProperty> findByCodeSystemVersion(Pageable thePage, @Param("cs_pid") Long thePid); Slice<TermConceptProperty> findByCodeSystemVersion(Pageable thePage, @Param("cs_pid") Long thePid);
@Query("SELECT COUNT(t) FROM TermConceptProperty t WHERE t.myCodeSystemVersion.myId = :cs_pid")
Integer countByCodeSystemVersion(@Param("cs_pid") Long thePid);
} }

View File

@ -25,6 +25,7 @@ import static org.apache.commons.lang3.StringUtils.isNotBlank;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.codec.binary.StringUtils; import org.apache.commons.codec.binary.StringUtils;
import org.hl7.fhir.dstu3.hapi.ctx.HapiWorkerContext; import org.hl7.fhir.dstu3.hapi.ctx.HapiWorkerContext;
@ -35,6 +36,8 @@ import org.hl7.fhir.dstu3.model.ValueSet.*;
import org.hl7.fhir.dstu3.terminologies.ValueSetExpander.ValueSetExpansionOutcome; import org.hl7.fhir.dstu3.terminologies.ValueSetExpander.ValueSetExpansionOutcome;
import org.hl7.fhir.instance.model.api.IIdType; import org.hl7.fhir.instance.model.api.IIdType;
import org.hl7.fhir.instance.model.api.IPrimitiveType; import org.hl7.fhir.instance.model.api.IPrimitiveType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Qualifier;
@ -223,6 +226,7 @@ public class FhirResourceDaoValueSetDstu3 extends FhirResourceDaoDstu3<ValueSet>
if (vs != null) { if (vs != null) {
ValueSet expansion = doExpand(vs); ValueSet expansion = doExpand(vs);
List<ValueSetExpansionContainsComponent> contains = expansion.getExpansion().getContains(); List<ValueSetExpansionContainsComponent> contains = expansion.getExpansion().getContains();
ValidateCodeResult result = validateCodeIsInContains(contains, toStringOrNull(theSystem), toStringOrNull(theCode), theCoding, theCodeableConcept); ValidateCodeResult result = validateCodeIsInContains(contains, toStringOrNull(theSystem), toStringOrNull(theCode), theCoding, theCodeableConcept);
if (result != null) { if (result != null) {
if (theDisplay != null && isNotBlank(theDisplay.getValue()) && isNotBlank(result.getDisplay())) { if (theDisplay != null && isNotBlank(theDisplay.getValue()) && isNotBlank(result.getDisplay())) {
@ -238,6 +242,9 @@ public class FhirResourceDaoValueSetDstu3 extends FhirResourceDaoDstu3<ValueSet>
} }
private static final Logger ourLog = LoggerFactory.getLogger(FhirResourceDaoValueSetDstu3.class);
private String toStringOrNull(IPrimitiveType<String> thePrimitive) { private String toStringOrNull(IPrimitiveType<String> thePrimitive) {
return thePrimitive != null ? thePrimitive.getValue() : null; return thePrimitive != null ? thePrimitive.getValue() : null;
} }

View File

@ -66,6 +66,7 @@ import org.springframework.context.ApplicationContextAware;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Slice; import org.springframework.data.domain.Slice;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.TransactionStatus;
@ -82,6 +83,7 @@ import javax.persistence.TypedQuery;
import javax.persistence.criteria.*; import javax.persistence.criteria.*;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.apache.commons.lang3.StringUtils.isBlank; import static org.apache.commons.lang3.StringUtils.isBlank;
@ -273,74 +275,43 @@ public abstract class BaseHapiTerminologySvcImpl implements IHapiTerminologySvc,
myEntityManager.flush(); myEntityManager.flush();
} }
public void deleteCodeSystemVersion(Long theCodeSystemVersionPid) { public void deleteCodeSystemVersion(final Long theCodeSystemVersionPid) {
ourLog.info(" * Deleting code system version {}", theCodeSystemVersionPid); ourLog.info(" * Deleting code system version {}", theCodeSystemVersionPid);
PageRequest page = PageRequest.of(0, 1000); PageRequest page1000 = PageRequest.of(0, 1000);
int count;
// Parent/Child links // Parent/Child links
ourLog.info(" * Deleting parent/child links"); {
count = 0; String descriptor = "parent/child links";
while (true) { Supplier<Slice<TermConceptParentChildLink>> loader = () -> myConceptParentChildLinkDao.findByCodeSystemVersion(page1000, theCodeSystemVersionPid);
Slice<TermConceptParentChildLink> link = myConceptParentChildLinkDao.findByCodeSystemVersion(page, theCodeSystemVersionPid); Supplier<Integer> counter = () -> myConceptParentChildLinkDao.countByCodeSystemVersion(theCodeSystemVersionPid);
if (link.hasContent() == false) { doDelete(descriptor, loader, counter, myConceptParentChildLinkDao);
break;
} }
myConceptParentChildLinkDao.deleteInBatch(link);
count += link.getNumberOfElements();
ourLog.info(" * {} parent/child links deleted", count);
}
myConceptParentChildLinkDao.flush();
// Properties // Properties
ourLog.info(" * Deleting properties"); {
count = 0; String descriptor = "concept properties";
while (true) { Supplier<Slice<TermConceptProperty>> loader = () -> myConceptPropertyDao.findByCodeSystemVersion(page1000, theCodeSystemVersionPid);
Slice<TermConceptProperty> link = myConceptPropertyDao.findByCodeSystemVersion(page, theCodeSystemVersionPid); Supplier<Integer> counter = () -> myConceptPropertyDao.countByCodeSystemVersion(theCodeSystemVersionPid);
if (link.hasContent() == false) { doDelete(descriptor, loader, counter, myConceptPropertyDao);
break;
} }
myConceptPropertyDao.deleteInBatch(link); // Designations
{
count += link.getNumberOfElements(); String descriptor = "concept designations";
ourLog.info(" * {} concept properties deleted", count); Supplier<Slice<TermConceptDesignation>> loader = () -> myConceptDesignationDao.findByCodeSystemVersion(page1000, theCodeSystemVersionPid);
Supplier<Integer> counter = () -> myConceptDesignationDao.countByCodeSystemVersion(theCodeSystemVersionPid);
doDelete(descriptor, loader, counter, myConceptDesignationDao);
} }
myConceptPropertyDao.flush();
// Properties
ourLog.info(" * Deleting designations");
count = 0;
while (true) {
Slice<TermConceptDesignation> link = myConceptDesignationDao.findByCodeSystemVersion(page, theCodeSystemVersionPid);
if (link.hasContent() == false) {
break;
}
myConceptDesignationDao.deleteInBatch(link);
count += link.getNumberOfElements();
ourLog.info(" * {} concept designations deleted", count);
}
myConceptDesignationDao.flush();
// Concepts // Concepts
ourLog.info(" * Deleting concepts"); {
count = 0; String descriptor = "concepts";
while (true) { // For some reason, concepts are much slower to delete, so use a smaller batch size
Slice<TermConcept> link = myConceptDao.findByCodeSystemVersion(page, theCodeSystemVersionPid); PageRequest page100 = PageRequest.of(0, 100);
if (link.hasContent() == false) { Supplier<Slice<TermConcept>> loader = () -> myConceptDao.findByCodeSystemVersion(page100, theCodeSystemVersionPid);
break; Supplier<Integer> counter = () -> myConceptDao.countByCodeSystemVersion(theCodeSystemVersionPid);
} doDelete(descriptor, loader, counter, myConceptDao);
myConceptDao.deleteInBatch(link);
myConceptDao.flush();
count += link.getNumberOfElements();
ourLog.info(" * {} concepts deleted", count);
} }
Optional<TermCodeSystem> codeSystemOpt = myCodeSystemDao.findWithCodeSystemVersionAsCurrentVersion(theCodeSystemVersionPid); Optional<TermCodeSystem> codeSystemOpt = myCodeSystemDao.findWithCodeSystemVersionAsCurrentVersion(theCodeSystemVersionPid);
@ -356,6 +327,26 @@ public abstract class BaseHapiTerminologySvcImpl implements IHapiTerminologySvc,
} }
private <T> void doDelete(String theDescriptor, Supplier<Slice<T>> theLoader, Supplier<Integer> theCounter, JpaRepository<T, ?> theDao) {
int count;
ourLog.info(" * Deleting {}", theDescriptor);
int totalCount = theCounter.get();
StopWatch sw = new StopWatch();
count = 0;
while (true) {
Slice<T> link = theLoader.get();
if (link.hasContent() == false) {
break;
}
theDao.deleteInBatch(link);
count += link.getNumberOfElements();
ourLog.info(" * {} {} deleted - {}/sec - ETA: {}", count, theDescriptor, sw.formatThroughput(count, TimeUnit.SECONDS), sw.getEstimatedTimeRemaining(count, totalCount));
}
theDao.flush();
}
public void deleteConceptMap(ResourceTable theResourceTable) { public void deleteConceptMap(ResourceTable theResourceTable) {
// Get existing entity so it can be deleted. // Get existing entity so it can be deleted.
Optional<TermConceptMap> optionalExistingTermConceptMapById = myConceptMapDao.findTermConceptMapByResourcePid(theResourceTable.getId()); Optional<TermConceptMap> optionalExistingTermConceptMapById = myConceptMapDao.findTermConceptMapByResourcePid(theResourceTable.getId());

View File

@ -2,6 +2,7 @@ package ca.uhn.fhir.jpa.provider.dstu3;
import ca.uhn.fhir.jpa.dao.IFhirResourceDao; import ca.uhn.fhir.jpa.dao.IFhirResourceDao;
import ca.uhn.fhir.jpa.dao.data.IResourceTableDao; import ca.uhn.fhir.jpa.dao.data.IResourceTableDao;
import ca.uhn.fhir.jpa.dao.r4.FhirResourceDaoR4TerminologyTest;
import ca.uhn.fhir.jpa.entity.ResourceTable; import ca.uhn.fhir.jpa.entity.ResourceTable;
import ca.uhn.fhir.jpa.entity.TermCodeSystemVersion; import ca.uhn.fhir.jpa.entity.TermCodeSystemVersion;
import ca.uhn.fhir.jpa.entity.TermConcept; import ca.uhn.fhir.jpa.entity.TermConcept;
@ -10,8 +11,11 @@ import ca.uhn.fhir.jpa.term.IHapiTerminologySvc;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.TestUtil;
import ca.uhn.fhir.util.UrlUtil;
import com.google.common.base.Charsets;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType; import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
@ -109,6 +113,16 @@ public class ResourceProviderDstu3ValueSetTest extends BaseResourceProviderDstu3
myLocalValueSetId = myValueSetDao.create(myLocalVs, mySrd).getId().toUnqualifiedVersionless(); myLocalValueSetId = myValueSetDao.create(myLocalVs, mySrd).getId().toUnqualifiedVersionless();
} }
private void createLocalVsWithIncludeConcept() {
myLocalVs = new ValueSet();
myLocalVs.setUrl(URL_MY_VALUE_SET);
ConceptSetComponent include = myLocalVs.getCompose().addInclude();
include.setSystem(URL_MY_CODE_SYSTEM);
include.addConcept().setCode("A");
include.addConcept().setCode("AA");
myLocalValueSetId = myValueSetDao.create(myLocalVs, mySrd).getId().toUnqualifiedVersionless();
}
private void createLocalVsWithUnknownCode(CodeSystem codeSystem) { private void createLocalVsWithUnknownCode(CodeSystem codeSystem) {
myLocalVs = new ValueSet(); myLocalVs = new ValueSet();
myLocalVs.setUrl(URL_MY_VALUE_SET); myLocalVs.setUrl(URL_MY_VALUE_SET);
@ -172,7 +186,7 @@ public class ResourceProviderDstu3ValueSetTest extends BaseResourceProviderDstu3
* $expand?identifier=foo is legacy.. It's actually not valid in FHIR as of STU3 * $expand?identifier=foo is legacy.. It's actually not valid in FHIR as of STU3
* but we supported it for longer than we should have so I don't want to delete * but we supported it for longer than we should have so I don't want to delete
* it right now. * it right now.
* * <p>
* https://groups.google.com/d/msgid/hapi-fhir/CAN2Cfy8kW%2BAOkgC6VjPsU3gRCpExCNZBmJdi-k5R_TWeyWH4tA%40mail.gmail.com?utm_medium=email&utm_source=footer * https://groups.google.com/d/msgid/hapi-fhir/CAN2Cfy8kW%2BAOkgC6VjPsU3gRCpExCNZBmJdi-k5R_TWeyWH4tA%40mail.gmail.com?utm_medium=email&utm_source=footer
*/ */
@Test @Test
@ -462,6 +476,29 @@ public class ResourceProviderDstu3ValueSetTest extends BaseResourceProviderDstu3
assertEquals(true, ((BooleanType) respParam.getParameter().get(0).getValue()).booleanValue()); assertEquals(true, ((BooleanType) respParam.getParameter().get(0).getValue()).booleanValue());
} }
@Test
public void testValidateCodeOperationByCodeAndSystemInstanceOnInstance() throws IOException {
createLocalCsAndVs();
createLocalVsWithIncludeConcept();
String url = ourServerBase +
"/ValueSet/" + myLocalValueSetId.getIdPart() + "/$validate-code?system=" +
UrlUtil.escapeUrlParam(FhirResourceDaoR4TerminologyTest.URL_MY_CODE_SYSTEM) +
"&code=AA";
ourLog.info("* Requesting: {}", url);
HttpGet request = new HttpGet(url);
request.addHeader("Accept", "application/fhir+json");
try (CloseableHttpResponse response = ourHttpClient.execute(request)) {
String respString = IOUtils.toString(response.getEntity().getContent(), Charsets.UTF_8);
ourLog.info(respString);
Parameters respParam = myFhirCtx.newJsonParser().parseResource(Parameters.class, respString);
assertTrue(((BooleanType) respParam.getParameter().get(0).getValue()).booleanValue());
}
}
@Test @Test
public void testValidateCodeOperationByCodeAndSystemType() { public void testValidateCodeOperationByCodeAndSystemType() {
//@formatter:off //@formatter:off

View File

@ -10,8 +10,11 @@ import ca.uhn.fhir.jpa.term.IHapiTerminologySvc;
import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException; import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails; import ca.uhn.fhir.rest.server.servlet.ServletRequestDetails;
import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.TestUtil;
import ca.uhn.fhir.util.UrlUtil;
import com.google.common.base.Charsets;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType; import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
@ -72,7 +75,6 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
} }
private void createLocalCsAndVs() { private void createLocalCsAndVs() {
//@formatter:off
CodeSystem codeSystem = new CodeSystem(); CodeSystem codeSystem = new CodeSystem();
codeSystem.setUrl(URL_MY_CODE_SYSTEM); codeSystem.setUrl(URL_MY_CODE_SYSTEM);
codeSystem.setContent(CodeSystemContentMode.COMPLETE); codeSystem.setContent(CodeSystemContentMode.COMPLETE);
@ -86,10 +88,17 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
.addConcept().setCode("B").setDisplay("Code B") .addConcept().setCode("B").setDisplay("Code B")
.addConcept(new ConceptDefinitionComponent().setCode("BA").setDisplay("Code BA")) .addConcept(new ConceptDefinitionComponent().setCode("BA").setDisplay("Code BA"))
.addConcept(new ConceptDefinitionComponent().setCode("BB").setDisplay("Code BB")); .addConcept(new ConceptDefinitionComponent().setCode("BB").setDisplay("Code BB"));
//@formatter:on
myCodeSystemDao.create(codeSystem, mySrd); myCodeSystemDao.create(codeSystem, mySrd);
}
createLocalVs(codeSystem); private void createLocalVsWithIncludeConcept() {
myLocalVs = new ValueSet();
myLocalVs.setUrl(URL_MY_VALUE_SET);
ConceptSetComponent include = myLocalVs.getCompose().addInclude();
include.setSystem(URL_MY_CODE_SYSTEM);
include.addConcept().setCode("A");
include.addConcept().setCode("AA");
myLocalValueSetId = myValueSetDao.create(myLocalVs, mySrd).getId().toUnqualifiedVersionless();
} }
private void createLocalVs(CodeSystem codeSystem) { private void createLocalVs(CodeSystem codeSystem) {
@ -97,7 +106,7 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
myLocalVs.setUrl(URL_MY_VALUE_SET); myLocalVs.setUrl(URL_MY_VALUE_SET);
ConceptSetComponent include = myLocalVs.getCompose().addInclude(); ConceptSetComponent include = myLocalVs.getCompose().addInclude();
include.setSystem(codeSystem.getUrl()); include.setSystem(codeSystem.getUrl());
include.addFilter().setProperty("concept").setOp(FilterOperator.ISA).setValue("childAA"); include.addFilter().setProperty("concept").setOp(FilterOperator.ISA).setValue("ParentA");
myLocalValueSetId = myValueSetDao.create(myLocalVs, mySrd).getId().toUnqualifiedVersionless(); myLocalValueSetId = myValueSetDao.create(myLocalVs, mySrd).getId().toUnqualifiedVersionless();
} }
@ -119,7 +128,7 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
} }
@Test @Test
public void testExpandById() throws IOException { public void testExpandById() {
//@formatter:off //@formatter:off
Parameters respParam = myClient Parameters respParam = myClient
.operation() .operation()
@ -149,7 +158,7 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
} }
@Test @Test
public void testExpandByIdWithFilter() throws IOException { public void testExpandByIdWithFilter() {
//@formatter:off //@formatter:off
Parameters respParam = myClient Parameters respParam = myClient
@ -208,7 +217,7 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
@Test @Test
public void testExpandInlineVsAgainstBuiltInCs() throws IOException { public void testExpandInlineVsAgainstBuiltInCs() {
createLocalVsPointingAtBuiltInCodeSystem(); createLocalVsPointingAtBuiltInCodeSystem();
assertNotNull(myLocalValueSetId); assertNotNull(myLocalValueSetId);
@ -229,7 +238,7 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
} }
@Test @Test
public void testExpandInlineVsAgainstExternalCs() throws IOException { public void testExpandInlineVsAgainstExternalCs() {
createExternalCsAndLocalVs(); createExternalCsAndLocalVs();
assertNotNull(myLocalVs); assertNotNull(myLocalVs);
myLocalVs.setId(""); myLocalVs.setId("");
@ -304,7 +313,7 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
} }
@Test @Test
public void testExpandLocalVsAgainstBuiltInCs() throws IOException { public void testExpandLocalVsAgainstBuiltInCs() {
createLocalVsPointingAtBuiltInCodeSystem(); createLocalVsPointingAtBuiltInCodeSystem();
assertNotNull(myLocalValueSetId); assertNotNull(myLocalValueSetId);
@ -325,7 +334,7 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
} }
@Test @Test
public void testExpandLocalVsAgainstExternalCs() throws IOException { public void testExpandLocalVsAgainstExternalCs() {
createExternalCsAndLocalVs(); createExternalCsAndLocalVs();
assertNotNull(myLocalValueSetId); assertNotNull(myLocalValueSetId);
@ -349,7 +358,7 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
} }
@Test @Test
public void testExpandLocalVsCanonicalAgainstExternalCs() throws IOException { public void testExpandLocalVsCanonicalAgainstExternalCs() {
createExternalCsAndLocalVs(); createExternalCsAndLocalVs();
assertNotNull(myLocalValueSetId); assertNotNull(myLocalValueSetId);
@ -373,7 +382,7 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
} }
@Test @Test
public void testExpandLocalVsWithUnknownCode() throws IOException { public void testExpandLocalVsWithUnknownCode() {
createExternalCsAndLocalVsWithUnknownCode(); createExternalCsAndLocalVsWithUnknownCode();
assertNotNull(myLocalValueSetId); assertNotNull(myLocalValueSetId);
@ -400,8 +409,7 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
HttpPost post = new HttpPost(ourServerBase + "/ValueSet/%24expand"); HttpPost post = new HttpPost(ourServerBase + "/ValueSet/%24expand");
post.setEntity(new StringEntity(string, ContentType.parse(ca.uhn.fhir.rest.api.Constants.CT_FHIR_JSON_NEW))); post.setEntity(new StringEntity(string, ContentType.parse(ca.uhn.fhir.rest.api.Constants.CT_FHIR_JSON_NEW)));
CloseableHttpResponse resp = ourHttpClient.execute(post); try (CloseableHttpResponse resp = ourHttpClient.execute(post)) {
try {
String respString = IOUtils.toString(resp.getEntity().getContent(), StandardCharsets.UTF_8); String respString = IOUtils.toString(resp.getEntity().getContent(), StandardCharsets.UTF_8);
ourLog.info(respString); ourLog.info(respString);
@ -411,14 +419,11 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
assertEquals(400, resp.getStatusLine().getStatusCode()); assertEquals(400, resp.getStatusLine().getStatusCode());
assertThat(respString, containsString("Unknown FilterOperator code 'n'")); assertThat(respString, containsString("Unknown FilterOperator code 'n'"));
} finally {
IOUtils.closeQuietly(resp);
} }
} }
@Test @Test
public void testValidateCodeOperationByCodeAndSystemInstance() { public void testValidateCodeOperationByCodeAndSystemInstance() {
//@formatter:off
Parameters respParam = myClient Parameters respParam = myClient
.operation() .operation()
.onInstance(myExtensionalVsId) .onInstance(myExtensionalVsId)
@ -426,7 +431,6 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
.withParameter(Parameters.class, "code", new CodeType("8495-4")) .withParameter(Parameters.class, "code", new CodeType("8495-4"))
.andParameter("system", new UriType("http://acme.org")) .andParameter("system", new UriType("http://acme.org"))
.execute(); .execute();
//@formatter:on
String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam); String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp); ourLog.info(resp);
@ -434,9 +438,51 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
assertEquals(true, ((BooleanType) respParam.getParameter().get(0).getValue()).booleanValue()); assertEquals(true, ((BooleanType) respParam.getParameter().get(0).getValue()).booleanValue());
} }
@Test
public void testValidateCodeOperationByCodeAndSystemInstanceOnType() throws IOException {
createLocalCsAndVs();
String url = ourServerBase +
"/ValueSet/$validate-code?system=" +
UrlUtil.escapeUrlParam(URL_MY_CODE_SYSTEM) +
"&code=AA";
HttpGet request = new HttpGet(url);
request.addHeader("Accept", "application/fhir+json");
try (CloseableHttpResponse response = ourHttpClient.execute(request)) {
String respString = IOUtils.toString(response.getEntity().getContent(), Charsets.UTF_8);
ourLog.info(respString);
Parameters respParam = myFhirCtx.newJsonParser().parseResource(Parameters.class, respString);
assertTrue(((BooleanType) respParam.getParameter().get(0).getValue()).booleanValue());
}
}
@Test
public void testValidateCodeOperationByCodeAndSystemInstanceOnInstance() throws IOException {
createLocalCsAndVs();
createLocalVsWithIncludeConcept();
String url = ourServerBase +
"/ValueSet/" + myLocalValueSetId.getIdPart() + "/$validate-code?system=" +
UrlUtil.escapeUrlParam(URL_MY_CODE_SYSTEM) +
"&code=AA";
ourLog.info("* Requesting: {}", url);
HttpGet request = new HttpGet(url);
request.addHeader("Accept", "application/fhir+json");
try (CloseableHttpResponse response = ourHttpClient.execute(request)) {
String respString = IOUtils.toString(response.getEntity().getContent(), Charsets.UTF_8);
ourLog.info(respString);
Parameters respParam = myFhirCtx.newJsonParser().parseResource(Parameters.class, respString);
assertTrue(((BooleanType) respParam.getParameter().get(0).getValue()).booleanValue());
}
}
@Test @Test
public void testValidateCodeOperationByCodeAndSystemType() { public void testValidateCodeOperationByCodeAndSystemType() {
//@formatter:off
Parameters respParam = myClient Parameters respParam = myClient
.operation() .operation()
.onType(ValueSet.class) .onType(ValueSet.class)
@ -444,7 +490,6 @@ public class ResourceProviderR4ValueSetTest extends BaseResourceProviderR4Test {
.withParameter(Parameters.class, "code", new CodeType("8450-9")) .withParameter(Parameters.class, "code", new CodeType("8450-9"))
.andParameter("system", new UriType("http://acme.org")) .andParameter("system", new UriType("http://acme.org"))
.execute(); .execute();
//@formatter:on
String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam); String resp = myFhirCtx.newXmlParser().setPrettyPrint(true).encodeResourceToString(respParam);
ourLog.info(resp); ourLog.info(resp);

View File

@ -2,6 +2,7 @@ package ca.uhn.fhir.jpa.term;
import ca.uhn.fhir.jpa.dao.DaoConfig; import ca.uhn.fhir.jpa.dao.DaoConfig;
import ca.uhn.fhir.jpa.dao.IFhirResourceDaoCodeSystem; import ca.uhn.fhir.jpa.dao.IFhirResourceDaoCodeSystem;
import ca.uhn.fhir.jpa.dao.IFhirResourceDaoValueSet;
import ca.uhn.fhir.jpa.dao.dstu3.BaseJpaDstu3Test; import ca.uhn.fhir.jpa.dao.dstu3.BaseJpaDstu3Test;
import ca.uhn.fhir.util.TestUtil; import ca.uhn.fhir.util.TestUtil;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
@ -52,17 +53,6 @@ public class TerminologyLoaderSvcIntegrationDstu3Test extends BaseJpaDstu3Test {
.findFirst(); .findFirst();
} }
private <T extends Type> Optional<T> getPropertyPart(Parameters theParameters, String thePropName, String thePart) {
return theParameters
.getParameter()
.stream()
.filter(t -> t.getName().equals(thePropName))
.flatMap(t -> t.getPart().stream())
.filter(t -> t.getName().equals(thePart))
.map(t -> (T) t.getValue())
.findFirst();
}
@Test @Test
public void testExpandWithPropertyCoding() throws Exception { public void testExpandWithPropertyCoding() throws Exception {
ZipCollectionBuilder files = new ZipCollectionBuilder(); ZipCollectionBuilder files = new ZipCollectionBuilder();
@ -169,7 +159,6 @@ public class TerminologyLoaderSvcIntegrationDstu3Test extends BaseJpaDstu3Test {
} }
@Test @Test
public void testLookupWithProperties2() throws Exception { public void testLookupWithProperties2() throws Exception {
ZipCollectionBuilder files = new ZipCollectionBuilder(); ZipCollectionBuilder files = new ZipCollectionBuilder();
@ -189,7 +178,6 @@ public class TerminologyLoaderSvcIntegrationDstu3Test extends BaseJpaDstu3Test {
assertEquals("Large unstained cells/100 leukocytes", propertyValue.get().getDisplay()); assertEquals("Large unstained cells/100 leukocytes", propertyValue.get().getDisplay());
} }
@Test @Test
public void testLookupWithPropertiesExplicit() throws Exception { public void testLookupWithPropertiesExplicit() throws Exception {
ZipCollectionBuilder files = new ZipCollectionBuilder(); ZipCollectionBuilder files = new ZipCollectionBuilder();
@ -214,6 +202,30 @@ public class TerminologyLoaderSvcIntegrationDstu3Test extends BaseJpaDstu3Test {
} }
@Test
public void testValidateCodeFound() throws Exception {
ZipCollectionBuilder files = new ZipCollectionBuilder();
TerminologyLoaderSvcLoincTest.addLoincMandatoryFilesToZip(files);
myLoader.loadLoinc(files.getFiles(), mySrd);
IFhirResourceDaoValueSet.ValidateCodeResult result = myValueSetDao.validateCode(null, null, new StringType("10013-1"), new StringType(IHapiTerminologyLoaderSvc.LOINC_URI), null, null, null, mySrd);
assertTrue(result.isResult());
assertEquals("Found code", result.getMessage());
}
@Test
public void testValidateCodeNotFound() throws Exception {
ZipCollectionBuilder files = new ZipCollectionBuilder();
TerminologyLoaderSvcLoincTest.addLoincMandatoryFilesToZip(files);
myLoader.loadLoinc(files.getFiles(), mySrd);
IFhirResourceDaoValueSet.ValidateCodeResult result = myValueSetDao.validateCode(null, null, new StringType("10013-1-9999999999"), new StringType(IHapiTerminologyLoaderSvc.LOINC_URI), null, null, null, mySrd);
assertFalse(result.isResult());
assertEquals("Code not found", result.getMessage());
}
private Set<String> toExpandedCodes(ValueSet theExpanded) { private Set<String> toExpandedCodes(ValueSet theExpanded) {
return theExpanded return theExpanded
.getExpansion() .getExpansion()

View File

@ -26,11 +26,20 @@ import ca.uhn.fhir.jpa.dao.*;
@Configuration @Configuration
public abstract class BaseJavaConfig${versionCapitalized} extends ca.uhn.fhir.jpa.config${package_suffix}.Base${versionCapitalized}Config { public abstract class BaseJavaConfig${versionCapitalized} extends ca.uhn.fhir.jpa.config${package_suffix}.Base${versionCapitalized}Config {
/**
* Subclasses may override
*/
protected boolean isSupported(String theResourceType) {
return true;
}
@Bean(name="myResourceProviders${versionCapitalized}") @Bean(name="myResourceProviders${versionCapitalized}")
public List<IResourceProvider> resourceProviders${versionCapitalized}() { public List<IResourceProvider> resourceProviders${versionCapitalized}() {
List<IResourceProvider> retVal = new ArrayList<IResourceProvider>(); List<IResourceProvider> retVal = new ArrayList<IResourceProvider>();
#foreach ( $res in $resources ) #foreach ( $res in $resources )
if (isSupported("${res.name}")) {
retVal.add(rp${res.declaringClassNameComplete}${versionCapitalized}()); retVal.add(rp${res.declaringClassNameComplete}${versionCapitalized}());
}
#end #end
return retVal; return retVal;
} }
@ -39,7 +48,9 @@ public abstract class BaseJavaConfig${versionCapitalized} extends ca.uhn.fhir.jp
public List<IFhirResourceDao<?>> resourceDaos${versionCapitalized}() { public List<IFhirResourceDao<?>> resourceDaos${versionCapitalized}() {
List<IFhirResourceDao<?>> retVal = new ArrayList<IFhirResourceDao<?>>(); List<IFhirResourceDao<?>> retVal = new ArrayList<IFhirResourceDao<?>>();
#foreach ( $res in $resources ) #foreach ( $res in $resources )
if (isSupported("${res.name}")) {
retVal.add(dao${res.declaringClassNameComplete}${versionCapitalized}()); retVal.add(dao${res.declaringClassNameComplete}${versionCapitalized}());
}
#end #end
return retVal; return retVal;
} }