This commit is contained in:
lmds1 2015-02-23 20:02:30 -05:00
commit 424e6bebe4
1569 changed files with 232446 additions and 187457 deletions

View File

@ -20,8 +20,15 @@ public class ClientExamples {
public void createProxy() {
// START SNIPPET: proxy
FhirContext ctx = new FhirContext();
// Set connections to access the network via the HTTP proxy at
// example.com : 8888
ctx.getRestfulClientFactory().setProxy("example.com", 8888);
// If the proxy requires authentication, use the following as well
ctx.getRestfulClientFactory().setProxyCredentials("theUsername", "thePassword");
// Create the client
IGenericClient genericClient = ctx.newRestfulGenericClient("http://localhost:9999/fhir");
// END SNIPPET: proxy
}

View File

@ -5,8 +5,8 @@ import java.io.IOException;
import java.util.List;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.dstu.composite.ResourceReferenceDt;
import ca.uhn.fhir.model.dstu2.composite.IdentifierDt;
import ca.uhn.fhir.model.dstu2.composite.ResourceReferenceDt;
import ca.uhn.fhir.model.dstu2.resource.Organization;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.rest.annotation.RequiredParam;

View File

@ -8,6 +8,7 @@ import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.rest.annotation.RequiredParam;
import ca.uhn.fhir.rest.annotation.Search;
import ca.uhn.fhir.rest.server.HardcodedServerAddressStrategy;
import ca.uhn.fhir.rest.server.IResourceProvider;
import ca.uhn.fhir.rest.server.RestfulServer;
@ -23,7 +24,7 @@ public class PlainProvider {
* determine the resource type so it must be explicitly stated.
*/
@Search(type=Patient.class)
public Bundle searchForPatients(@RequiredParam(name="name") StringDt theName) {
public Bundle searchForPatients(@RequiredParam(name=Patient.SP_NAME) StringDt theName) {
Bundle retVal = new Bundle();
// perform search
return retVal;
@ -36,6 +37,7 @@ public class PlainProvider {
//START SNIPPET: plainProviderServer
public class ExampleServlet extends RestfulServer {
/** Constructor */
public ExampleServlet() {
/*
* Plain providers are passed to the server in the same way
@ -54,5 +56,23 @@ public class ExampleServlet extends RestfulServer {
}
//END SNIPPET: plainProviderServer
//START SNIPPET: addressStrategy
public class MyServlet extends RestfulServer {
/** Constructor */
public MyServlet() {
String serverBaseUrl = "http://foo.com/fhir";
setServerAddressStrategy(new HardcodedServerAddressStrategy(serverBaseUrl));
// ...add some resource providers, etc...
List<IResourceProvider> resourceProviders = new ArrayList<IResourceProvider>();
setResourceProviders(resourceProviders);
}
}
//END SNIPPET: addressStrategy
}

View File

@ -10,6 +10,7 @@ import ca.uhn.fhir.model.base.resource.BaseConformance;
import ca.uhn.fhir.model.base.resource.BaseOperationOutcome;
import ca.uhn.fhir.model.dstu2.valueset.AdministrativeGenderEnum;
import ca.uhn.fhir.model.dstu2.resource.Observation;
import ca.uhn.fhir.model.dstu2.resource.OperationOutcome;
import ca.uhn.fhir.model.dstu2.resource.Organization;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.model.primitive.IdDt;
@ -68,6 +69,30 @@ public class GenericClientExample {
System.out.println("Got ID: " + id.getValue());
// END SNIPPET: create
}
{
Patient patient = new Patient();
// START SNIPPET: createConditional
// One form
MethodOutcome outcome = client.create()
.resource(patient)
.conditionalByUrl("Patient?identifier=system%7C00001")
.execute();
// Another form
MethodOutcome outcome2 = client.create()
.resource(patient)
.conditional()
.where(Patient.IDENTIFIER.exactly().systemAndIdentifier("system", "00001"))
.execute();
// This will return true if the server responded with an HTTP 201 created,
// otherwise it will return null.
Boolean created = outcome.getCreated();
// The ID of the created, or the pre-existing resource
IdDt id = outcome.getId();
// END SNIPPET: createConditional
}
{
// START SNIPPET: update
Patient patient = new Patient();
@ -95,6 +120,21 @@ public class GenericClientExample {
System.out.println("Got ID: " + id.getValue());
// END SNIPPET: update
}
{
Patient patient = new Patient();
// START SNIPPET: updateConditional
client.update()
.resource(patient)
.conditionalByUrl("Patient?identifier=system%7C00001")
.execute();
client.update()
.resource(patient)
.conditional()
.where(Patient.IDENTIFIER.exactly().systemAndIdentifier("system", "00001"))
.execute();
// END SNIPPET: updateConditional
}
{
// START SNIPPET: etagupdate
// First, let's retrive the latest version of a resource
@ -132,16 +172,27 @@ public class GenericClientExample {
}
{
// START SNIPPET: delete
// Retrieve the server's conformance statement and print its
// description
BaseOperationOutcome outcome = client.delete().resourceById(new IdDt("Patient", "1234")).execute();
BaseOperationOutcome resp = client.delete().resourceById(new IdDt("Patient", "1234")).execute();
// outcome may be null if the server didn't return one
if (outcome != null) {
if (resp != null) {
OperationOutcome outcome = (OperationOutcome) resp;
System.out.println(outcome.getIssueFirstRep().getDetailsElement().getValue());
}
// END SNIPPET: delete
}
{
// START SNIPPET: deleteConditional
client.delete()
.resourceConditionalByUrl("Patient?identifier=system%7C00001")
.execute();
client.delete()
.resourceConditionalByType("Patient")
.where(Patient.IDENTIFIER.exactly().systemAndIdentifier("system", "00001"))
.execute();
// END SNIPPET: deleteConditional
}
{
// START SNIPPET: search
Bundle response = client.search()

View File

@ -0,0 +1,52 @@
package example;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.AuthenticationStrategy;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.rest.client.IGenericClient;
public class HttpProxy {
public static void main(String[] args) {
/*
* This is out ot date - Just keeping
* it in case it's helpful...
*/
final String authUser = "username";
final String authPassword = "password";
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope("10.10.10.10", 8080),
new UsernamePasswordCredentials(authUser, authPassword));
HttpHost myProxy = new HttpHost("10.10.10.10", 8080);
HttpClientBuilder clientBuilder = HttpClientBuilder.create();
clientBuilder
.setProxy(myProxy)
.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy())
.setDefaultCredentialsProvider(credsProvider)
.disableCookieManagement();
CloseableHttpClient httpClient = clientBuilder.build();
FhirContext ctx = new FhirContext();
String serverBase = "http://spark.furore.com/fhir/";
ctx.getRestfulClientFactory().setHttpClient(httpClient);
IGenericClient client = ctx.newRestfulGenericClient(serverBase);
IdDt id = new IdDt("Patient", "123");
client.read(Patient.class, id);
}
}

View File

@ -3,8 +3,8 @@ package example;
import java.io.IOException;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.dstu.valueset.NarrativeStatusEnum;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.model.dstu2.valueset.NarrativeStatusEnum;
import ca.uhn.fhir.narrative.DefaultThymeleafNarrativeGenerator;
import ca.uhn.fhir.parser.DataFormatException;

View File

@ -12,6 +12,7 @@ import ca.uhn.fhir.rest.server.IBundleProvider;
import ca.uhn.fhir.rest.server.IResourceProvider;
@SuppressWarnings("null")
//START SNIPPET: provider
public class PagingPatientProvider implements IResourceProvider {
@ -21,11 +22,22 @@ public class PagingPatientProvider implements IResourceProvider {
@Search
public IBundleProvider search(@RequiredParam(name = Patient.SP_FAMILY) StringParam theFamily) {
final InstantDt searchTime = InstantDt.withCurrentTime();
final List<String> matchingResourceIds = findIdsByFamily(theFamily);
/*
* First, we'll search the database for a set of database row IDs that
* match the given search criteria. That way we can keep just the
* row IDs around, and load the actual resources on demand later
* as the client pages through them.
*/
final List<Long> matchingResourceIds = null; // <-- implement this
/*
* Return a bundle provider which can page through the IDs and
* return the resources that go with them.
*/
return new IBundleProvider() {
@Override
@Override
public int size() {
return matchingResourceIds.size();
}
@ -33,7 +45,7 @@ public class PagingPatientProvider implements IResourceProvider {
@Override
public List<IResource> getResources(int theFromIndex, int theToIndex) {
int end = Math.max(theToIndex, matchingResourceIds.size() - 1);
List<String> idsToReturn = matchingResourceIds.subList(theFromIndex, end);
List<Long> idsToReturn = matchingResourceIds.subList(theFromIndex, end);
return loadResourcesByIds(idsToReturn);
}
@ -44,18 +56,10 @@ public class PagingPatientProvider implements IResourceProvider {
};
}
/**
* Get a list of resource IDs which match a given family name
*/
private List<String> findIdsByFamily(StringParam theFamily) {
// .. implement this search against the database ..
return null;
}
/**
* Load a list of patient resources given their IDs
*/
private List<IResource> loadResourcesByIds(List<String> theFamily) {
private List<IResource> loadResourcesByIds(List<Long> theIdsToReturn) {
// .. implement this search against the database ..
return null;
}

View File

@ -4,7 +4,6 @@ import java.io.IOException;
import java.util.List;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.dstu.valueset.AdministrativeGenderCodesEnum;
import ca.uhn.fhir.model.dstu2.composite.IdentifierDt;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.model.dstu2.valueset.AdministrativeGenderEnum;

View File

@ -34,6 +34,7 @@ import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.InstantDt;
import ca.uhn.fhir.parser.DataFormatException;
import ca.uhn.fhir.rest.annotation.AddTags;
import ca.uhn.fhir.rest.annotation.ConditionalOperationParam;
import ca.uhn.fhir.rest.annotation.Count;
import ca.uhn.fhir.rest.annotation.Create;
import ca.uhn.fhir.rest.annotation.DeleteTags;
@ -324,6 +325,23 @@ public void deletePatient(@IdParam IdDt theId) {
//END SNIPPET: delete
//START SNIPPET: deleteConditional
@Read()
public void deletePatientConditional(@IdParam IdDt theId, @ConditionalOperationParam String theConditionalUrl) {
// Only one of theId or theConditionalUrl will have a value depending
// on whether the URL receieved was a logical ID, or a conditional
// search string
if (theId != null) {
// do a normal delete
} else {
// do a conditional delete
}
// otherwise, delete was successful
return; // can also return MethodOutcome
}
//END SNIPPET: deleteConditional
//START SNIPPET: history
@History()
public List<Patient> getPatientHistory(@IdParam IdDt theId) {
@ -681,6 +699,25 @@ public MethodOutcome createPatient(@ResourceParam Patient thePatient) {
public abstract MethodOutcome createNewPatient(@ResourceParam Patient thePatient);
//END SNIPPET: createClient
//START SNIPPET: updateConditional
@Update
public MethodOutcome updatePatientConditional(
@ResourceParam Patient thePatient,
@IdParam IdDt theId,
@ConditionalOperationParam String theConditional) {
// Only one of theId or theConditional will have a value and the other will be null,
// depending on the URL passed into the server.
if (theConditional != null) {
// Do a conditional update. theConditional will have a value like "Patient?identifier=system%7C00001"
} else {
// Do a normal update. theId will have the identity of the resource to update
}
return new MethodOutcome(); // populate this
}
//END SNIPPET: updateConditional
//START SNIPPET: update
@Update
public MethodOutcome updatePatient(@IdParam IdDt theId, @ResourceParam Patient thePatient) {

View File

@ -12,6 +12,7 @@
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry including="**/*.java" kind="src" path="src/main/resources"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6">
<attributes>
<attribute name="maven.pomderived" value="true"/>

3
hapi-fhir-android/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
/target
/bin
/target/

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>hapi-fhir-android</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

210
hapi-fhir-android/pom.xml Normal file
View File

@ -0,0 +1,210 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>ca.uhn.hapi.fhir</groupId>
<artifactId>hapi-fhir</artifactId>
<version>0.9-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>hapi-fhir-android</artifactId>
<packaging>jar</packaging>
<name>HAPI FHIR - Android</name>
<dependencies>
<dependency>
<groupId>ca.uhn.hapi.fhir</groupId>
<artifactId>hapi-fhir-base</artifactId>
<version>0.9-SNAPSHOT</version>
<exclusions>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>ca.uhn.hapi.fhir</groupId>
<artifactId>hapi-fhir-structures-dstu</artifactId>
<version>0.9-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>ca.uhn.hapi.fhir</groupId>
<artifactId>hapi-fhir-structures-dstu2</artifactId>
<version>0.9-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.phloc</groupId>
<artifactId>phloc-schematron</artifactId>
<version>${phloc_schematron_version}</version>
</dependency>
<dependency>
<groupId>com.phloc</groupId>
<artifactId>phloc-commons</artifactId>
<version>${phloc_commons_version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient-android</artifactId>
<version>4.3.5.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-android</artifactId>
<version>${slf4j_version}</version>
</dependency>
<!-- <dependency> <groupId>org.codehaus.woodstox</groupId> <artifactId>stax2-api</artifactId>
<version>3.1.4</version> </dependency> -->
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons_codec_version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons_io_version}</version>
</dependency>
<!-- Testing -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit_version}</version>
<scope>test</scope>
</dependency>
<!-- <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId>
<version>${commons_io_version}</version> <scope>test</scope> </dependency> -->
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-deploy-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${maven_failsafe_plugin_version}</version>
<configuration>
<classpathDependencyScopeExclude>compile+runtime</classpathDependencyScopeExclude>
<additionalClasspathElements>
<additionalClasspathElement>target/hapi-fhir-android-0.9-SNAPSHOT-shaded.jar</additionalClasspathElement>
</additionalClasspathElements>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>true</shadedArtifactAttached>
<createDependencyReducedPom>true</createDependencyReducedPom>
<!--<minimizeJar>true</minimizeJar>-->
<artifactSet>
<includes>
<include>commons-codec:commons-codec</include>
<include>commons-io:commons-io</include>
<include>ca.uhn.hapi.fhir:hapi-fhir-base</include>
<include>ca.uhn.hapi.fhir:hapi-fhir-structures-dstu</include>
<include>ca.uhn.hapi.fhir:hapi-fhir-structures-dstu2</include>
<include>org.glassfish:javax.json</include>
<include>org.codehaus.woodstox:woodstox-core-asl</include>
<include>javax.xml.stream:stax-api</include>
<include>org.codehaus.woodstox:stax2-api</include>
<include>org.slf4j:slf4j*</include>
<include>org.apache.commons:*</include>
<include>org.apache.httpcomponents:*</include>
<include>org.glassfish:javax.json</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>javax.xml.stream</pattern>
<shadedPattern>ca.uhn.fhir.repackage.javax.xml.stream</shadedPattern>
</relocation>
<relocation>
<pattern>javax.json</pattern>
<shadedPattern>ca.uhn.fhir.repackage.javax.json</shadedPattern>
</relocation>
</relocations>
<filters>
<filter>
<artifact>ca.uhn.hapi.fhir:hapi-fhir-base</artifact>
<!--
<includes>
<include>**/*.class</include>
<include>**/*.properties</include>
<include>**/*.html</include>
</includes>
-->
<excludes>
<exclude>ca/uhn/fhir/model/dstu/valueset/**</exclude>
<exclude>**/*.java</exclude>
</excludes>
</filter>
</filters>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<profiles>
<profile>
<id>DIST</id>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>${maven_assembly_plugin_version}</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<attach>false</attach>
<descriptors>
<descriptor>${project.basedir}/src/assembly/hapi-fhir-all.xml</descriptor>
<descriptor>${project.basedir}/src/assembly/hapi-fhir-jpaserver-example.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -0,0 +1 @@
com.ctc.wstx.stax.WstxInputFactory

View File

@ -0,0 +1 @@
com.ctc.wstx.stax.WstxOutputFactory

View File

@ -0,0 +1,25 @@
package android.util;
public class Log {
public static final int VERBOSE = 2;
public static final int DEBUG = 3;
public static final int INFO = 4;
public static final int WARN = 5;
public static final int ERROR = 6;
public static final int ASSERT = 7;
public static boolean isLoggable(String theName, int thePriority) {
return true;
}
public static boolean isLoggable(int thePriority) {
return true;
}
public static int println(int thePriority, String theName, String theMessage) {
System.out.println("[" + theName + "] " + theMessage);
return 0;
}
}

View File

@ -0,0 +1,87 @@
package ca.uhn.fhir.android;
import static org.junit.Assert.*;
import java.io.File;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.WildcardFileFilter;
import org.junit.Test;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.dstu2.resource.Patient;
import ca.uhn.fhir.rest.client.IGenericClient;
import ca.uhn.fhir.rest.client.exceptions.FhirClientConnectionException;
public class BuiltJarIT {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BuiltJarIT.class);
@Test
public void testParser() {
FhirContext ctx = FhirContext.forDstu2();
Patient p = new Patient();
p.addIdentifier().setSystem("system");
String str = ctx.newXmlParser().encodeResourceToString(p);
Patient p2 = ctx.newXmlParser().parseResource(Patient.class, str);
assertEquals("system", p2.getIdentifierFirstRep().getSystemElement().getValueAsString());
}
/**
* A simple client test - We try to connect to a server that doesn't exist, but
* if we at least get the right exception it means we made it up to the HTTP/network stack
*
* Disabled for now - TODO: add the old version of the apache client (the one that
* android uses) and see if this passes
*/
public void testClient() {
FhirContext ctx = FhirContext.forDstu2();
try {
IGenericClient client = ctx.newRestfulGenericClient("http://127.0.0.1:44442/SomeBase");
client.conformance();
} catch (FhirClientConnectionException e) {
// this is good
}
}
/**
* Android does not like duplicate entries in the JAR
*/
@Test
public void testJarForDuplicates() throws Exception {
Collection<File> files = FileUtils.listFiles(new File("target"), new WildcardFileFilter("*-shaded.jar"), null);
if (files.isEmpty()) {
throw new Exception("No files matching target/*-shaded.jar");
}
for (File file : files) {
ourLog.info("Testing file: {}", file);
ZipFile zip = new ZipFile(file);
try {
Set<String> names = new HashSet<String>();
for (Enumeration<? extends ZipEntry> iter = zip.entries(); iter.hasMoreElements();) {
ZipEntry next = iter.nextElement();
String nextName = next.getName();
if (!names.add(nextName)) {
throw new Exception("File " + file + " contains duplicate contents: " + nextName);
}
}
ourLog.info("File {} contains {} entries", file, names.size());
} finally {
zip.close();
}
}
}
}

View File

@ -195,69 +195,6 @@
</plugins>
</reporting>
</profile>
<profile>
<id>ANDROID</id>
<dependencies>
<dependency>
<groupId>ca.uhn.hapi.fhir</groupId>
<artifactId>hapi-fhir-structures-dstu</artifactId>
<version>0.9-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-android</artifactId>
<version>${slf4j_version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>1.4</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
<configuration>
<shadedArtifactAttached>false</shadedArtifactAttached>
<createDependencyReducedPom>true</createDependencyReducedPom>
<artifactSet>
<includes>
<!--
<include>javax.json:javax.json-api</include>
-->
<include>ca.uhn.hapi.fhir:hapi-fhir-structures-dstu</include>
<include>ca.uhn.hapi.fhir:hapi-fhir-structures-dstu</include>
<include>org.glassfish:javax.json</include>
<include>org.codehaus.woodstox:woodstox-core-asl</include>
<include>javax.xml.stream:stax-api</include>
<include>org.codehaus.woodstox:stax2-api</include>
<include>org.slf4j:slf4j*</include>
<include>org.apache.commons:*</include>
<include>org.apache.httpcomponents:*</include>
</includes>
</artifactSet>
<relocations>
<relocation>
<pattern>javax.xml.stream</pattern>
<shadedPattern>ca.uhn.fhir.repackage.javax.xml.stream</shadedPattern>
</relocation>
<relocation>
<pattern>javax.json</pattern>
<shadedPattern>ca.uhn.fhir.repackage.javax.json</shadedPattern>
</relocation>
</relocations>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>

View File

@ -21,6 +21,7 @@ package ca.uhn.fhir.context;
*/
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
@ -28,7 +29,6 @@ import java.util.Set;
import org.hl7.fhir.instance.model.IBase;
import ca.uhn.fhir.model.api.ICodeEnum;
import ca.uhn.fhir.model.api.IDatatype;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Description;
@ -41,23 +41,30 @@ public abstract class BaseRuntimeChildDatatypeDefinition extends BaseRuntimeDecl
public BaseRuntimeChildDatatypeDefinition(Field theField, String theElementName, Child theChildAnnotation, Description theDescriptionAnnotation, Class<? extends IBase> theDatatype) {
super(theField, theChildAnnotation, theDescriptionAnnotation, theElementName);
assert theDatatype != IDatatype.class; // should use RuntimeChildAny
assert Modifier.isInterface(theDatatype.getModifiers()) == false : "Type of " + theDatatype + " shouldn't be here"; // should use RuntimeChildAny
myDatatype = theDatatype;
}
@Override
public String getChildNameByDatatype(Class<? extends IBase> theDatatype) {
if (myDatatype.equals(theDatatype)) {
return getElementName();
Class<?> nextType = theDatatype;
while(nextType.equals(Object.class)==false) {
if (myDatatype.equals(nextType)) {
return getElementName();
}
nextType = nextType.getSuperclass();
}
return null;
}
@Override
public BaseRuntimeElementDefinition<?> getChildElementDefinitionByDatatype(Class<? extends IBase> theDatatype) {
Class<? extends IBase> datatype = theDatatype;
if (myDatatype.equals(datatype)) {
return myElementDefinition;
Class<?> nextType = theDatatype;
while(nextType.equals(Object.class)==false) {
if (myDatatype.equals(nextType)) {
return myElementDefinition;
}
nextType = nextType.getSuperclass();
}
return null;
}
@ -84,7 +91,7 @@ public abstract class BaseRuntimeChildDatatypeDefinition extends BaseRuntimeDecl
}
@Override
void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
myElementDefinition = theClassToElementDefinitions.get(getDatatype());
assert myElementDefinition != null : "Unknown type: " + getDatatype();
}

View File

@ -45,10 +45,10 @@ public abstract class BaseRuntimeChildDefinition {
public abstract Set<String> getValidChildNames();
abstract void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions);
abstract void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions);
public interface IAccessor {
List<? extends IBase> getValues(Object theTarget);
List<IBase> getValues(Object theTarget);
}
public abstract String getElementName();

View File

@ -32,7 +32,6 @@ import java.util.List;
import org.apache.commons.lang3.text.WordUtils;
import org.hl7.fhir.instance.model.IBase;
import ca.uhn.fhir.model.api.IElement;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.util.BeanUtils;
@ -199,13 +198,13 @@ public abstract class BaseRuntimeDeclaredChildDefinition extends BaseRuntimeChil
private final class FieldPlainAccessor implements IAccessor {
@Override
public List<? extends IElement> getValues(Object theTarget) {
public List<IBase> getValues(Object theTarget) {
try {
Object values = myField.get(theTarget);
if (values == null) {
return Collections.emptyList();
}
List<? extends IElement> retVal = (List<? extends IElement>) Collections.singletonList((IElement)values);
List<IBase> retVal = Collections.singletonList((IBase)values);
return retVal;
} catch (IllegalArgumentException e) {
throw new ConfigurationException("Failed to get value", e);
@ -237,10 +236,10 @@ public abstract class BaseRuntimeDeclaredChildDefinition extends BaseRuntimeChil
private final class FieldListAccessor implements IAccessor {
@SuppressWarnings("unchecked")
@Override
public List<? extends IElement> getValues(Object theTarget) {
List<? extends IElement> retVal;
public List<IBase> getValues(Object theTarget) {
List<IBase> retVal;
try {
retVal = (List<? extends IElement>) myField.get(theTarget);
retVal = (List<IBase>) myField.get(theTarget);
} catch (IllegalArgumentException e) {
throw new ConfigurationException("Failed to get value", e);
} catch (IllegalAccessException e) {
@ -262,9 +261,9 @@ public abstract class BaseRuntimeDeclaredChildDefinition extends BaseRuntimeChil
@SuppressWarnings("unchecked")
@Override
public List<IElement> getValues(Object theTarget) {
public List<IBase> getValues(Object theTarget) {
try {
return (List<IElement>) myAccessorMethod.invoke(theTarget);
return (List<IBase>) myAccessorMethod.invoke(theTarget);
} catch (IllegalAccessException e) {
throw new ConfigurationException("Failed to get value", e);
} catch (IllegalArgumentException e) {
@ -284,8 +283,7 @@ public abstract class BaseRuntimeDeclaredChildDefinition extends BaseRuntimeChil
@Override
public void addValue(Object theTarget, IBase theValue) {
@SuppressWarnings("unchecked")
List<IBase> existingList = (List<IBase>) myAccessor.getValues(theTarget);
List<IBase> existingList = myAccessor.getValues(theTarget);
if (existingList == null) {
existingList = new ArrayList<IBase>();
try {
@ -310,9 +308,9 @@ public abstract class BaseRuntimeDeclaredChildDefinition extends BaseRuntimeChil
}
@Override
public List<IElement> getValues(Object theTarget) {
public List<IBase> getValues(Object theTarget) {
try {
return Collections.singletonList((IElement) myAccessorMethod.invoke(theTarget));
return Collections.singletonList((IBase)myAccessorMethod.invoke(theTarget));
} catch (IllegalAccessException e) {
throw new ConfigurationException("Failed to get value", e);
} catch (IllegalArgumentException e) {

View File

@ -45,9 +45,6 @@ public abstract class BaseRuntimeElementCompositeDefinition<T extends IBase> ext
if (theNext == null) {
throw new NullPointerException();
}
// if (theNext.getValidChildNames().contains("performetPractitioner")) {
// throw new NullPointerException();
// }
if (theNext.getExtensionUrl() != null) {
throw new IllegalArgumentException("Shouldn't haven an extension URL, use addExtension instead");
}
@ -76,11 +73,11 @@ public abstract class BaseRuntimeElementCompositeDefinition<T extends IBase> ext
}
@Override
public void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
super.sealAndInitialize(theClassToElementDefinitions);
public void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
super.sealAndInitialize(theContext, theClassToElementDefinitions);
for (BaseRuntimeChildDefinition next : myChildren) {
next.sealAndInitialize(theClassToElementDefinitions);
next.sealAndInitialize(theContext, theClassToElementDefinitions);
}
myNameToChild = new HashMap<String, BaseRuntimeChildDefinition>();

View File

@ -29,6 +29,7 @@ import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.hl7.fhir.instance.model.IBase;
import org.hl7.fhir.instance.model.api.IBaseEnumFactory;
import ca.uhn.fhir.model.api.IValueSetEnumBinder;
@ -51,7 +52,6 @@ public abstract class BaseRuntimeElementDefinition<T extends IBase> {
if (myName.endsWith("Dt")) {
myName = myName.substring(0, myName.length() - 2);
}
myImplementingClass = theImplementingClass;
}
@ -103,8 +103,10 @@ public abstract class BaseRuntimeElementDefinition<T extends IBase> {
try {
if (theArgument == null) {
return getImplementingClass().newInstance();
} else {
} else if (theArgument instanceof IValueSetEnumBinder) {
return getImplementingClass().getConstructor(IValueSetEnumBinder.class).newInstance(theArgument);
}else {
return getImplementingClass().getConstructor(IBaseEnumFactory.class).newInstance(theArgument);
}
} catch (InstantiationException e) {
throw new ConfigurationException("Failed to instantiate type:" + getImplementingClass().getName(), e);
@ -128,10 +130,11 @@ public abstract class BaseRuntimeElementDefinition<T extends IBase> {
/**
* Invoked prior to use to perform any initialization and make object
* mutable
* @param theContext TODO
*/
void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
for (BaseRuntimeChildDefinition next : myExtensions) {
next.sealAndInitialize(theClassToElementDefinitions);
next.sealAndInitialize(theContext, theClassToElementDefinitions);
}
for (RuntimeChildDeclaredExtensionDefinition next : myExtensions) {

View File

@ -37,7 +37,6 @@ 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.dstu.resource.Binary;
import ca.uhn.fhir.model.view.ViewGenerator;
import ca.uhn.fhir.narrative.INarrativeGenerator;
import ca.uhn.fhir.parser.DataFormatException;
@ -73,16 +72,19 @@ import ca.uhn.fhir.validation.FhirValidator;
public class FhirContext {
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 volatile Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> myClassToElementDefinition = Collections.emptyMap();
private volatile Map<String, RuntimeResourceDefinition> myIdToResourceDefinition = Collections.emptyMap();
private HapiLocalizer myLocalizer = new HapiLocalizer();
private volatile Map<String, RuntimeResourceDefinition> myNameToElementDefinition = Collections.emptyMap();
private Map<String, String> myNameToResourceType;
private Map<String, Class<? extends IBaseResource>> myNameToResourceType;
private volatile INarrativeGenerator myNarrativeGenerator;
private volatile IRestfulClientFactory myRestfulClientFactory;
private volatile RuntimeChildUndeclaredExtensionDefinition myRuntimeChildUndeclaredExtensionDefinition;
private final IFhirVersion myVersion;
private Map<FhirVersionEnum, Map<String, Class<? extends IBaseResource>>> myVersionToNameToResourceType = Collections.emptyMap();
/**
* Default constructor. In most cases this is the right constructor to use.
*/
@ -116,25 +118,21 @@ public class FhirContext {
myVersion = FhirVersionEnum.DSTU1.getVersionImplementation();
} else if (FhirVersionEnum.DSTU2.isPresentOnClasspath()) {
myVersion = FhirVersionEnum.DSTU2.getVersionImplementation();
} else if (FhirVersionEnum.DSTU2_HL7ORG.isPresentOnClasspath()) {
myVersion = FhirVersionEnum.DSTU2_HL7ORG.getVersionImplementation();
} else if (FhirVersionEnum.DEV.isPresentOnClasspath()) {
myVersion = FhirVersionEnum.DEV.getVersionImplementation();
} else {
throw new IllegalStateException(getLocalizer().getMessage(FhirContext.class, "noStructures"));
}
ourLog.info("Creating new FHIR context for FHIR version [{}]", myVersion.getVersion().name());
scanResourceTypes(toElementList(theResourceTypes));
}
@SuppressWarnings("unchecked")
private List<Class<? extends IElement>> toElementList(Collection<Class<? extends IBaseResource>> theResourceTypes) {
if (theResourceTypes == null) {
return null;
}
List<Class<? extends IElement>> resTypes = new ArrayList<Class<? extends IElement>>();
for (Class<? extends IBaseResource> next : theResourceTypes) {
resTypes.add((Class<? extends IElement>) next);
}
return resTypes;
private String createUnknownResourceNameError(String theResourceName, FhirVersionEnum theVersion) {
return getLocalizer().getMessage(FhirContext.class, "unknownResourceName", theResourceName, theVersion);
}
/**
@ -182,7 +180,7 @@ public class FhirContext {
if (Modifier.isAbstract(theResourceType.getModifiers())) {
throw new IllegalArgumentException("Can not scan abstract or interface class (resource definitions must be concrete classes): " + theResourceType.getName());
}
RuntimeResourceDefinition retVal = (RuntimeResourceDefinition) myClassToElementDefinition.get(theResourceType);
if (retVal == null) {
retVal = scanResourceType((Class<? extends IResource>) theResourceType);
@ -190,6 +188,32 @@ public class FhirContext {
return retVal;
}
public RuntimeResourceDefinition getResourceDefinition(FhirVersionEnum theVersion, String theResourceName) {
Validate.notNull(theVersion, "theVersion can not be null");
if (theVersion.equals(myVersion.getVersion())) {
return getResourceDefinition(theResourceName);
}
Map<String, Class<? extends IBaseResource>> nameToType = myVersionToNameToResourceType.get(theVersion);
if (nameToType == null) {
nameToType = new HashMap<String, Class<? extends IBaseResource>>();
ModelScanner.scanVersionPropertyFile(null, nameToType, theVersion);
Map<FhirVersionEnum, Map<String, Class<? extends IBaseResource>>> newVersionToNameToResourceType = new HashMap<FhirVersionEnum, Map<String, Class<? extends IBaseResource>>>();
newVersionToNameToResourceType.putAll(myVersionToNameToResourceType);
newVersionToNameToResourceType.put(theVersion, nameToType);
myVersionToNameToResourceType = newVersionToNameToResourceType;
}
Class<? extends IBaseResource> resourceType = nameToType.get(theResourceName.toLowerCase());
if (resourceType == null) {
throw new DataFormatException(createUnknownResourceNameError(theResourceName, theVersion));
}
return getResourceDefinition(resourceType);
}
/**
* Returns the scanned runtime model for the given type. This is an advanced feature which is generally only needed
* for extending the core library.
@ -219,22 +243,12 @@ public class FhirContext {
RuntimeResourceDefinition retVal = myNameToElementDefinition.get(resourceName);
if (retVal == null) {
try {
String className = myNameToResourceType.get(resourceName.toLowerCase());
if (className == null) {
if ("binary".equals(resourceName.toLowerCase())) {
// Binary is not generated so it's not in the list of potential resources
className = Binary.class.getName();
} else {
throw new DataFormatException("Unknown resource name[" + resourceName + "]");
}
}
Class<?> clazz = Class.forName(className);
if (IResource.class.isAssignableFrom(clazz)) {
retVal = scanResourceType((Class<? extends IResource>) clazz);
}
} catch (ClassNotFoundException e) {
throw new DataFormatException("Unknown resource name[" + resourceName + "]");
Class<? extends IBaseResource> clazz = myNameToResourceType.get(resourceName.toLowerCase());
if (clazz == null) {
throw new DataFormatException(createUnknownResourceNameError(resourceName, myVersion.getVersion()));
}
if (IBaseResource.class.isAssignableFrom(clazz)) {
retVal = scanResourceType((Class<? extends IResource>) clazz);
}
}
@ -358,13 +372,6 @@ public class FhirContext {
return new XmlParser(this);
}
private RuntimeResourceDefinition scanResourceType(Class<? extends IResource> theResourceType) {
ArrayList<Class<? extends IElement>> resourceTypes = new ArrayList<Class<? extends IElement>>();
resourceTypes.add(theResourceType);
Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> defs = scanResourceTypes(resourceTypes);
return (RuntimeResourceDefinition) defs.get(theResourceType);
}
private BaseRuntimeElementDefinition<?> scanDatatype(Class<? extends IElement> theResourceType) {
ArrayList<Class<? extends IElement>> resourceTypes = new ArrayList<Class<? extends IElement>>();
resourceTypes.add(theResourceType);
@ -372,8 +379,15 @@ public class FhirContext {
return defs.get(theResourceType);
}
private RuntimeResourceDefinition scanResourceType(Class<? extends IResource> theResourceType) {
ArrayList<Class<? extends IElement>> resourceTypes = new ArrayList<Class<? extends IElement>>();
resourceTypes.add(theResourceType);
Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> defs = scanResourceTypes(resourceTypes);
return (RuntimeResourceDefinition) defs.get(theResourceType);
}
private Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> scanResourceTypes(Collection<Class<? extends IElement>> theResourceTypes) {
ModelScanner scanner = new ModelScanner(this, myClassToElementDefinition, theResourceTypes);
ModelScanner scanner = new ModelScanner(this, myVersion.getVersion(), myClassToElementDefinition, theResourceTypes);
if (myRuntimeChildUndeclaredExtensionDefinition == null) {
myRuntimeChildUndeclaredExtensionDefinition = scanner.getRuntimeChildUndeclaredExtensionDefinition();
}
@ -414,6 +428,43 @@ public class FhirContext {
myNarrativeGenerator = theNarrativeGenerator;
}
@SuppressWarnings("unchecked")
private List<Class<? extends IElement>> toElementList(Collection<Class<? extends IBaseResource>> theResourceTypes) {
if (theResourceTypes == null) {
return null;
}
List<Class<? extends IElement>> resTypes = new ArrayList<Class<? extends IElement>>();
for (Class<? extends IBaseResource> next : theResourceTypes) {
resTypes.add((Class<? extends IElement>) next);
}
return resTypes;
}
/**
* Creates and returns a new FhirContext with version {@link FhirVersionEnum#DEV}
*/
public static FhirContext forDev() {
return new FhirContext(FhirVersionEnum.DEV);
}
/**
* Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU1}
*/
public static FhirContext forDstu1() {
return new FhirContext(FhirVersionEnum.DSTU1);
}
/**
* Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU2}
*/
public static FhirContext forDstu2() {
return new FhirContext(FhirVersionEnum.DSTU2);
}
public static FhirContext forDstu2Hl7Org() {
return new FhirContext(FhirVersionEnum.DSTU2_HL7ORG);
}
private static Collection<Class<? extends IBaseResource>> toCollection(Class<? extends IBaseResource> theResourceType) {
ArrayList<Class<? extends IBaseResource>> retVal = new ArrayList<Class<? extends IBaseResource>>(1);
retVal.add(theResourceType);
@ -432,25 +483,4 @@ public class FhirContext {
return retVal;
}
/**
* Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU1}
*/
public static FhirContext forDstu1() {
return new FhirContext(FhirVersionEnum.DSTU1);
}
/**
* Creates and returns a new FhirContext with version {@link FhirVersionEnum#DEV}
*/
public static FhirContext forDev() {
return new FhirContext(FhirVersionEnum.DEV);
}
/**
* Creates and returns a new FhirContext with version {@link FhirVersionEnum#DSTU2}
*/
public static FhirContext forDstu2() {
return new FhirContext(FhirVersionEnum.DSTU2);
}
}

View File

@ -38,7 +38,9 @@ public enum FhirVersionEnum {
DSTU2("ca.uhn.fhir.model.dstu2.FhirDstu2", null),
DEV("ca.uhn.fhir.model.dev.FhirDev", null);
DEV("ca.uhn.fhir.model.dev.FhirDev", null),
DSTU2_HL7ORG("org.hl7.fhir.instance.FhirDstu2Hl7Org", null);
private final String myVersionClass;

View File

@ -20,7 +20,7 @@ package ca.uhn.fhir.context;
* #L%
*/
import static org.apache.commons.lang3.StringUtils.*;
import static org.apache.commons.lang3.StringUtils.isBlank;
import java.io.IOException;
import java.io.InputStream;
@ -48,20 +48,24 @@ import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.hl7.fhir.instance.model.BackboneElement;
import org.hl7.fhir.instance.model.DomainResource;
import org.hl7.fhir.instance.model.IBase;
import org.hl7.fhir.instance.model.IBaseResource;
import org.hl7.fhir.instance.model.ICompositeType;
import org.hl7.fhir.instance.model.IPrimitiveType;
import org.hl7.fhir.instance.model.Narrative;
import org.hl7.fhir.instance.model.Reference;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBackboneElement;
import org.hl7.fhir.instance.model.api.IBaseDatatype;
import org.hl7.fhir.instance.model.api.IBaseEnumFactory;
import org.hl7.fhir.instance.model.api.IBaseExtension;
import org.hl7.fhir.instance.model.api.IDatatypeElement;
import org.hl7.fhir.instance.model.api.IDomainResource;
import org.hl7.fhir.instance.model.api.INarrative;
import org.hl7.fhir.instance.model.api.IReference;
import ca.uhn.fhir.model.api.CodeableConceptElement;
import ca.uhn.fhir.model.api.ExtensionDt;
import ca.uhn.fhir.model.api.IBoundCodeableConcept;
import ca.uhn.fhir.model.api.ICodeEnum;
import ca.uhn.fhir.model.api.ICompositeElement;
import ca.uhn.fhir.model.api.IDatatype;
import ca.uhn.fhir.model.api.IElement;
import ca.uhn.fhir.model.api.IPrimitiveDatatype;
@ -75,9 +79,9 @@ import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.api.annotation.Extension;
import ca.uhn.fhir.model.api.annotation.ResourceDef;
import ca.uhn.fhir.model.api.annotation.SearchParamDefinition;
import ca.uhn.fhir.model.base.composite.BaseContainedDt;
import ca.uhn.fhir.model.base.composite.BaseNarrativeDt;
import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt;
import ca.uhn.fhir.model.dstu.composite.ContainedDt;
import ca.uhn.fhir.model.dstu.composite.NarrativeDt;
import ca.uhn.fhir.model.dstu.valueset.SearchParamTypeEnum;
import ca.uhn.fhir.model.primitive.BoundCodeDt;
import ca.uhn.fhir.model.primitive.ICodedDatatype;
@ -88,37 +92,18 @@ class ModelScanner {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(ModelScanner.class);
private Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> myClassToElementDefinitions = new HashMap<Class<? extends IBase>, BaseRuntimeElementDefinition<?>>();
private FhirContext myContext;
private Map<String, RuntimeResourceDefinition> myIdToResourceDefinition = new HashMap<String, RuntimeResourceDefinition>();
private Map<String, RuntimeResourceDefinition> myNameToResourceDefinitions = new HashMap<String, RuntimeResourceDefinition>();
// private Map<String, RuntimeResourceDefinition>
// myNameToDatatypeDefinitions = new HashMap<String,
// RuntimeDatatypeDefinition>();
private Map<String, String> myNameToResourceType = new HashMap<String, String>();
private Map<String, Class<? extends IBaseResource>> myNameToResourceType = new HashMap<String, Class<? extends IBaseResource>>();
private RuntimeChildUndeclaredExtensionDefinition myRuntimeChildUndeclaredExtensionDefinition;
private Set<Class<? extends IBase>> myScanAlso = new HashSet<Class<? extends IBase>>();
private Set<Class<? extends ICodeEnum>> myScanAlsoCodeTable = new HashSet<Class<? extends ICodeEnum>>();
private FhirVersionEnum myVersion;
private FhirContext myContext;
ModelScanner(FhirContext theContext, Class<? extends IBaseResource> theResourceTypes) throws ConfigurationException {
myContext = theContext;
Set<Class<? extends IBase>> singleton = new HashSet<Class<? extends IBase>>();
singleton.add(theResourceTypes);
init(null, singleton);
}
ModelScanner(FhirContext theContext, Collection<Class<? extends IBaseResource>> theResourceTypes) throws ConfigurationException {
myContext = theContext;
init(null, new HashSet<Class<? extends IBase>>(theResourceTypes));
}
ModelScanner(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theExistingDefinitions, Collection<Class<? extends IElement>> theResourceTypes) throws ConfigurationException {
ModelScanner(FhirContext theContext, FhirVersionEnum theVersion, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theExistingDefinitions, Collection<Class<? extends IElement>> theResourceTypes) throws ConfigurationException {
myContext = theContext;
myVersion = theVersion;
Set<Class<? extends IBase>> toScan;
if (theResourceTypes != null) {
toScan = new HashSet<Class<? extends IBase>>(theResourceTypes);
@ -128,28 +113,8 @@ class ModelScanner {
init(theExistingDefinitions, toScan);
}
public Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> getClassToElementDefinitions() {
return myClassToElementDefinitions;
}
public Map<String, RuntimeResourceDefinition> getIdToResourceDefinition() {
return myIdToResourceDefinition;
}
public Map<String, RuntimeResourceDefinition> getNameToResourceDefinitions() {
return (myNameToResourceDefinitions);
}
public Map<String, String> getNameToResourceType() {
return myNameToResourceType;
}
public RuntimeChildUndeclaredExtensionDefinition getRuntimeChildUndeclaredExtensionDefinition() {
return myRuntimeChildUndeclaredExtensionDefinition;
}
private void addScanAlso(Class<? extends IBase> theType) {
if (theType.isInterface()) {
if (theType.isInterface() || Modifier.isAbstract(theType.getModifiers())) {
return;
}
myScanAlso.add(theType);
@ -186,46 +151,36 @@ class ModelScanner {
}
}
private void init(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theExistingDefinitions, Set<Class<? extends IBase>> toScan) {
public Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> getClassToElementDefinitions() {
return myClassToElementDefinitions;
}
public Map<String, RuntimeResourceDefinition> getIdToResourceDefinition() {
return myIdToResourceDefinition;
}
public Map<String, RuntimeResourceDefinition> getNameToResourceDefinitions() {
return (myNameToResourceDefinitions);
}
public Map<String, Class<? extends IBaseResource>> getNameToResourceType() {
return myNameToResourceType;
}
public RuntimeChildUndeclaredExtensionDefinition getRuntimeChildUndeclaredExtensionDefinition() {
return myRuntimeChildUndeclaredExtensionDefinition;
}
private void init(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theExistingDefinitions, Set<Class<? extends IBase>> theDatatypes) {
if (theExistingDefinitions != null) {
myClassToElementDefinitions.putAll(theExistingDefinitions);
}
int startSize = myClassToElementDefinitions.size();
long start = System.currentTimeMillis();
Map<String, Class<? extends IBaseResource>> resourceTypes = myNameToResourceType;
InputStream str = myContext.getVersion().getFhirVersionPropertiesFile();
Properties prop = new Properties();
try {
prop.load(str);
for (Entry<Object, Object> nextEntry : prop.entrySet()) {
String nextKey = nextEntry.getKey().toString();
String nextValue = nextEntry.getValue().toString();
if (!nextKey.startsWith("datatype.")) {
if (nextKey.startsWith("resource.")) {
String resName = nextKey.substring("resource.".length()).toLowerCase();
myNameToResourceType.put(resName, nextValue);
}
continue;
}
try {
@SuppressWarnings("unchecked")
Class<? extends IElement> nextClass = (Class<? extends IElement>) Class.forName((String) nextValue);
if (!IElement.class.isAssignableFrom(nextClass)) {
ourLog.warn("Class is not assignable from " + IElement.class.getSimpleName() + ": " + nextValue);
continue;
}
toScan.add(nextClass);
} catch (ClassNotFoundException e) {
ourLog.warn("Unknown class exception: " + nextValue, e);
}
}
} catch (IOException e) {
throw new ConfigurationException("Failed to load model property file from classpath: " + "/ca/uhn/fhir/model/dstu/model.properties");
}
scanVersionPropertyFile(theDatatypes, resourceTypes, myVersion);
// toScan.add(DateDt.class);
// toScan.add(CodeDt.class);
@ -235,7 +190,7 @@ class ModelScanner {
// toScan.add(QuantityDt.class);
do {
for (Class<? extends IBase> nextClass : toScan) {
for (Class<? extends IBase> nextClass : theDatatypes) {
scan(nextClass);
}
for (Iterator<Class<? extends IBase>> iter = myScanAlso.iterator(); iter.hasNext();) {
@ -243,25 +198,66 @@ class ModelScanner {
iter.remove();
}
}
toScan.clear();
toScan.addAll(myScanAlso);
theDatatypes.clear();
theDatatypes.addAll(myScanAlso);
myScanAlso.clear();
} while (!toScan.isEmpty());
} while (!theDatatypes.isEmpty());
for (Entry<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> nextEntry : myClassToElementDefinitions.entrySet()) {
if (theExistingDefinitions != null && theExistingDefinitions.containsKey(nextEntry.getKey())) {
continue;
}
BaseRuntimeElementDefinition<?> next = nextEntry.getValue();
next.sealAndInitialize(myClassToElementDefinitions);
next.sealAndInitialize(myContext, myClassToElementDefinitions);
}
myRuntimeChildUndeclaredExtensionDefinition = new RuntimeChildUndeclaredExtensionDefinition();
myRuntimeChildUndeclaredExtensionDefinition.sealAndInitialize(myClassToElementDefinitions);
myRuntimeChildUndeclaredExtensionDefinition.sealAndInitialize(myContext, myClassToElementDefinitions);
long time = System.currentTimeMillis() - start;
int size = myClassToElementDefinitions.size() - startSize;
ourLog.info("Done scanning FHIR library, found {} model entries in {}ms", size, time);
ourLog.debug("Done scanning FHIR library, found {} model entries in {}ms", size, time);
}
/**
* There are two implementations of all of the annotations (e.g. {@link Child} and
* {@link org.hl7.fhir.instance.model.annotations.Child}) since the HL7.org ones will eventually replace the HAPI
* ones. Annotations can't extend each other or implement interfaces or anything like that, so rather than duplicate
* all of the annotation processing code this method just creates an interface Proxy to simulate the HAPI
* annotations if the HL7.org ones are found instead.
*/
@SuppressWarnings("unchecked")
private <T extends Annotation> T pullAnnotation(AnnotatedElement theTarget, Class<T> theAnnotationType) {
T retVal = theTarget.getAnnotation(theAnnotationType);
if (retVal == null) {
String sourceClassName = theAnnotationType.getName();
String candidateAltClassName = sourceClassName.replace("ca.uhn.fhir.model.api.annotation", "org.hl7.fhir.instance.model.annotations");
if (!sourceClassName.equals(candidateAltClassName)) {
try {
final Class<? extends Annotation> altAnnotationClass = (Class<? extends Annotation>) Class.forName(candidateAltClassName);
final Annotation altAnnotation = theTarget.getAnnotation(altAnnotationClass);
if (altAnnotation == null) {
return null;
}
ourLog.debug("Forwarding annotation request for [{}] to class [{}]", sourceClassName, candidateAltClassName);
InvocationHandler h = new InvocationHandler() {
@Override
public Object invoke(Object theProxy, Method theMethod, Object[] theArgs) throws Throwable {
Method altMethod = altAnnotationClass.getMethod(theMethod.getName(), theMethod.getParameterTypes());
return altMethod.invoke(altAnnotation, theArgs);
}
};
retVal = (T) Proxy.newProxyInstance(theAnnotationType.getClassLoader(), new Class<?>[] { theAnnotationType }, h);
} catch (ClassNotFoundException e) {
return null;
}
}
}
return retVal;
}
private void scan(Class<? extends IBase> theClass) throws ConfigurationException {
@ -272,7 +268,7 @@ class ModelScanner {
ResourceDef resourceDefinition = pullAnnotation(theClass, ResourceDef.class);
if (resourceDefinition != null) {
if (!IResource.class.isAssignableFrom(theClass)) {
if (!IBaseResource.class.isAssignableFrom(theClass)) {
throw new ConfigurationException("Resource type contains a @" + ResourceDef.class.getSimpleName() + " annotation but does not implement " + IResource.class.getCanonicalName() + ": " + theClass.getCanonicalName());
}
@SuppressWarnings("unchecked")
@ -296,11 +292,10 @@ class ModelScanner {
}
Block blockDefinition = pullAnnotation(theClass, Block.class);
if (blockDefinition != null) {
if (IResourceBlock.class.isAssignableFrom(theClass)) {
@SuppressWarnings("unchecked")
Class<? extends IResourceBlock> blockClass = (Class<? extends IResourceBlock>) theClass;
scanBlock(blockClass, blockDefinition);
if (IResourceBlock.class.isAssignableFrom(theClass) || IBackboneElement.class.isAssignableFrom(theClass) || IDatatypeElement.class.isAssignableFrom(theClass)) {
scanBlock(theClass);
} else {
throw new ConfigurationException("Type contains a @" + Block.class.getSimpleName() + " annotation but does not implement " + IResourceBlock.class.getCanonicalName() + ": " + theClass.getCanonicalName());
}
@ -311,7 +306,7 @@ class ModelScanner {
}
}
private void scanBlock(Class<? extends IResourceBlock> theClass, Block theBlockDefinition) {
private void scanBlock(Class<? extends IBase> theClass) {
ourLog.debug("Scanning resource block class: {}", theClass.getName());
String resourceName = theClass.getCanonicalName();
@ -326,7 +321,7 @@ class ModelScanner {
}
private void scanCompositeDatatype(Class<? extends ICompositeType> theClass, DatatypeDef theDatatypeDefinition) {
ourLog.debug("Scanning resource class: {}", theClass.getName());
ourLog.debug("Scanning datatype class: {}", theClass.getName());
RuntimeCompositeDatatypeDefinition resourceDef;
if (theClass.equals(ExtensionDt.class)) {
@ -352,7 +347,7 @@ class ModelScanner {
Class<? extends IBase> current = theClass;
do {
classes.push(current);
if (ICompositeElement.class.isAssignableFrom(current.getSuperclass())) {
if (IBase.class.isAssignableFrom(current.getSuperclass())) {
current = (Class<? extends IBase>) current.getSuperclass();
} else {
current = null;
@ -464,8 +459,8 @@ class ModelScanner {
if (order != Child.ORDER_UNKNOWN) {
order = order + baseElementOrder;
}
int min = childAnnotation.min();
int max = childAnnotation.max();
// int min = childAnnotation.min();
// int max = childAnnotation.max();
/*
* Anything that's marked as unknown is given a new ID that is <0 so that it doesn't conflict with any given
@ -493,14 +488,21 @@ class ModelScanner {
Class<?> nextElementType = determineElementType(next);
if (nextElementType.equals(ContainedDt.class) || (childAnnotation.name().equals("contained") && DomainResource.class.isAssignableFrom(theClass))) {
if (IAnyResource.class.isAssignableFrom(nextElementType) || IResource.class.equals(nextElementType)) {
/*
* Child is a resource as a direct child, as in Bundle.entry.resource
*/
RuntimeChildDirectResource def = new RuntimeChildDirectResource(next, childAnnotation, descriptionAnnotation, elementName);
orderMap.put(order, def);
} else if (BaseContainedDt.class.isAssignableFrom(nextElementType) || (childAnnotation.name().equals("contained") && IDomainResource.class.isAssignableFrom(theClass))) {
/*
* Child is contained resources
*/
RuntimeChildContainedResources def = new RuntimeChildContainedResources(next, childAnnotation, descriptionAnnotation, elementName);
orderMap.put(order, def);
} else if (choiceTypes.size() > 1 && !BaseResourceReferenceDt.class.isAssignableFrom(nextElementType) && !Reference.class.isAssignableFrom(nextElementType)) {
} else if (choiceTypes.size() > 1 && !BaseResourceReferenceDt.class.isAssignableFrom(nextElementType) && !IReference.class.isAssignableFrom(nextElementType)) {
/*
* Child is a choice element
*/
@ -528,7 +530,7 @@ class ModelScanner {
if (IElement.class.isAssignableFrom(nextElementType)) {
addScanAlso((Class<? extends IElement>) nextElementType);
}
} else if (BaseResourceReferenceDt.class.isAssignableFrom(nextElementType) || Reference.class.isAssignableFrom(nextElementType)) {
} else if (BaseResourceReferenceDt.class.isAssignableFrom(nextElementType) || IReference.class.isAssignableFrom(nextElementType)) {
/*
* Child is a resource reference
*/
@ -543,7 +545,7 @@ class ModelScanner {
RuntimeChildResourceDefinition def = new RuntimeChildResourceDefinition(next, elementName, childAnnotation, descriptionAnnotation, refTypesList);
orderMap.put(order, def);
} else if (IResourceBlock.class.isAssignableFrom(nextElementType) || BackboneElement.class.isAssignableFrom(nextElementType)) {
} else if (IResourceBlock.class.isAssignableFrom(nextElementType) || IBackboneElement.class.isAssignableFrom(nextElementType) || IDatatypeElement.class.isAssignableFrom(nextElementType)) {
/*
* Child is a resource block (i.e. a sub-tag within a resource) TODO: do these have a better name
* according to HL7?
@ -554,20 +556,23 @@ class ModelScanner {
RuntimeChildResourceBlockDefinition def = new RuntimeChildResourceBlockDefinition(next, childAnnotation, descriptionAnnotation, elementName, blockDef);
orderMap.put(order, def);
} else if (IDatatype.class.equals(nextElementType) || IElement.class.equals(nextElementType)) {
} else if (IDatatype.class.equals(nextElementType) || IElement.class.equals(nextElementType) || "org.hl7.fhir.instance.model.Type".equals(nextElementType.getName()) || IBaseDatatype.class.equals(nextElementType)) {
RuntimeChildAny def = new RuntimeChildAny(next, elementName, childAnnotation, descriptionAnnotation);
orderMap.put(order, def);
} else if (IDatatype.class.isAssignableFrom(nextElementType) || IPrimitiveType.class.isAssignableFrom(nextElementType) || ICompositeType.class.isAssignableFrom(nextElementType)) {
} else if (IDatatype.class.isAssignableFrom(nextElementType) || IPrimitiveType.class.isAssignableFrom(nextElementType) || ICompositeType.class.isAssignableFrom(nextElementType) || IBaseDatatype.class.isAssignableFrom(nextElementType) || IBaseExtension.class.isAssignableFrom(nextElementType)) {
Class<? extends IBase> nextDatatype = (Class<? extends IBase>) nextElementType;
addScanAlso(nextDatatype);
BaseRuntimeChildDatatypeDefinition def;
if (IPrimitiveDatatype.class.isAssignableFrom(nextElementType)) {
if (IPrimitiveType.class.isAssignableFrom(nextElementType)) {
if (nextElementType.equals(BoundCodeDt.class)) {
IValueSetEnumBinder<Enum<?>> binder = getBoundCodeBinder(next);
def = new RuntimeChildPrimitiveBoundCodeDatatypeDefinition(next, elementName, childAnnotation, descriptionAnnotation, nextDatatype, binder);
} else if (childAnnotation.enumFactory().getSimpleName().equals("NoEnumFactory") == false) {
Class<? extends IBaseEnumFactory<?>> enumFactory = childAnnotation.enumFactory();
def = new RuntimeChildEnumerationDatatypeDefinition(next, elementName, childAnnotation, descriptionAnnotation, nextDatatype, enumFactory);
} else {
def = new RuntimeChildPrimitiveDatatypeDefinition(next, elementName, descriptionAnnotation, childAnnotation, nextDatatype);
}
@ -575,7 +580,7 @@ class ModelScanner {
if (IBoundCodeableConcept.class.isAssignableFrom(nextElementType)) {
IValueSetEnumBinder<Enum<?>> binder = getBoundCodeBinder(next);
def = new RuntimeChildCompositeBoundDatatypeDefinition(next, elementName, childAnnotation, descriptionAnnotation, nextDatatype, binder);
} else if (NarrativeDt.class.getSimpleName().equals(nextElementType.getSimpleName()) || Narrative.class.getName().equals(nextElementType.getClass().getName())) {
} else if (BaseNarrativeDt.class.isAssignableFrom(nextElementType) || INarrative.class.getName().equals(nextElementType.getClass().getName())) {
def = new RuntimeChildNarrativeDefinition(next, elementName, childAnnotation, descriptionAnnotation, nextDatatype);
} else {
def = new RuntimeChildCompositeDatatypeDefinition(next, elementName, childAnnotation, descriptionAnnotation, nextDatatype);
@ -603,48 +608,7 @@ class ModelScanner {
}
}
/**
* There are two implementations of all of the annotations (e.g. {@link Child} and
* {@link org.hl7.fhir.instance.model.annotations.Child}) since the HL7.org ones will eventually replace the HAPI
* ones. Annotations can't extend each other or implement interfaces or anything like that, so rather than duplicate
* all of the annotation processing code this method just creates an interface Proxy to simulate the HAPI
* annotations if the HL7.org ones are found instead.
*/
@SuppressWarnings("unchecked")
private <T extends Annotation> T pullAnnotation(AnnotatedElement theTarget, Class<T> theAnnotationType) {
T retVal = theTarget.getAnnotation(theAnnotationType);
if (retVal == null) {
String sourceClassName = theAnnotationType.getName();
String candidateAltClassName = sourceClassName.replace("ca.uhn.fhir.model.api.annotation", "org.hl7.fhir.instance.model.annotations");
if (!sourceClassName.equals(candidateAltClassName)) {
try {
final Class<? extends Annotation> altAnnotationClass = (Class<? extends Annotation>) Class.forName(candidateAltClassName);
final Annotation altAnnotation = theTarget.getAnnotation(altAnnotationClass);
if (altAnnotation == null) {
return null;
}
ourLog.debug("Forwarding annotation request for [{}] to class [{}]", sourceClassName, candidateAltClassName);
InvocationHandler h = new InvocationHandler() {
@Override
public Object invoke(Object theProxy, Method theMethod, Object[] theArgs) throws Throwable {
Method altMethod = altAnnotationClass.getMethod(theMethod.getName(), theMethod.getParameterTypes());
return altMethod.invoke(altAnnotation, theArgs);
}
};
retVal = (T) Proxy.newProxyInstance(theAnnotationType.getClassLoader(), new Class<?>[] { theAnnotationType }, h);
} catch (ClassNotFoundException e) {
return null;
}
}
}
return retVal;
}
private String scanPrimitiveDatatype(Class<? extends IPrimitiveType> theClass, DatatypeDef theDatatypeDefinition) {
private String scanPrimitiveDatatype(Class<? extends IPrimitiveType<?>> theClass, DatatypeDef theDatatypeDefinition) {
ourLog.debug("Scanning resource class: {}", theClass.getName());
String resourceName = theDatatypeDefinition.name();
@ -685,27 +649,8 @@ class ModelScanner {
}
}
// if (myNameToResourceDefinitions.containsKey(resourceName)) {
// if (!myNameToResourceDefinitions.get(resourceName).getImplementingClass().equals(theClass)) {
// // throw new
// // ConfigurationException("Detected duplicate element name '" +
// // resourceName + "' in types '" + theClass.getCanonicalName() +
// // "' and '"
// // +
// // myNameToResourceDefinitions.get(resourceName).getImplementingClass()
// // + "'");
// } else {
// return resourceName;
// }
// }
String resourceId = resourceDefinition.id();
if (isBlank(resourceId)) {
// throw new ConfigurationException("Resource type @" +
// ResourceDef.class.getSimpleName() +
// " annotation contains no resource ID: " +
// theClass.getCanonicalName());
} else {
if (!isBlank(resourceId)) {
if (myIdToResourceDefinition.containsKey(resourceId)) {
throw new ConfigurationException("The following resource types have the same ID of '" + resourceId + "' - " + theClass.getCanonicalName() + " and " + myIdToResourceDefinition.get(resourceId).getImplementingClass().getCanonicalName());
}
@ -714,7 +659,7 @@ class ModelScanner {
RuntimeResourceDefinition resourceDef = new RuntimeResourceDefinition(myContext, resourceName, theClass, resourceDefinition);
myClassToElementDefinitions.put(theClass, resourceDef);
if (primaryNameProvider) {
if (resourceDef.getStructureVersion() == myContext.getVersion().getVersion()) {
if (resourceDef.getStructureVersion() == myVersion) {
myNameToResourceDefinitions.put(resourceName, resourceDef);
}
}
@ -737,7 +682,7 @@ class ModelScanner {
if (searchParam != null) {
SearchParamTypeEnum paramType = SearchParamTypeEnum.valueOf(searchParam.type().toUpperCase());
if (paramType == null) {
throw new ConfigurationException("Searc param " + searchParam.name() + " has an invalid type: " + searchParam.type());
throw new ConfigurationException("Search param " + searchParam.name() + " has an invalid type: " + searchParam.type());
}
if (paramType == SearchParamTypeEnum.COMPOSITE) {
compositeFields.put(nextField, searchParam);
@ -781,4 +726,59 @@ class ModelScanner {
return type;
}
static void scanVersionPropertyFile(Set<Class<? extends IBase>> theDatatypes, Map<String, Class<? extends IBaseResource>> theResourceTypes, FhirVersionEnum version) {
InputStream str = version.getVersionImplementation().getFhirVersionPropertiesFile();
Properties prop = new Properties();
try {
prop.load(str);
for (Entry<Object, Object> nextEntry : prop.entrySet()) {
String nextKey = nextEntry.getKey().toString();
String nextValue = nextEntry.getValue().toString();
if (nextKey.startsWith("datatype.")) {
if (theDatatypes != null) {
try {
// Datatypes
Class<?> dtType = Class.forName(nextValue);
if (IElement.class.isAssignableFrom(dtType)) {
@SuppressWarnings("unchecked")
Class<? extends IElement> nextClass = (Class<? extends IElement>) dtType;
theDatatypes.add(nextClass);
} else if (IBaseDatatype.class.isAssignableFrom(dtType)) {
@SuppressWarnings("unchecked")
Class<? extends IBaseDatatype> nextClass = (Class<? extends IBaseDatatype>) dtType;
theDatatypes.add(nextClass);
} else {
ourLog.warn("Class is not assignable from " + IElement.class.getSimpleName() + " or " + IBaseDatatype.class.getSimpleName() + ": " + nextValue);
continue;
}
} catch (ClassNotFoundException e) {
ourLog.error("Unknown class[" + nextValue + "] for data type definition: " + nextKey.substring("datatype.".length()), e);
}
}
} else if (nextKey.startsWith("resource.")) {
// Resources
String resName = nextKey.substring("resource.".length()).toLowerCase();
try {
@SuppressWarnings("unchecked")
Class<? extends IBaseResource> nextClass = (Class<? extends IBaseResource>) Class.forName(nextValue);
if (!IBaseResource.class.isAssignableFrom(nextClass)) {
ourLog.warn("Class is not assignable from " + IBaseResource.class.getSimpleName() + ": " + nextValue);
continue;
}
theResourceTypes.put(resName, nextClass);
} catch (ClassNotFoundException e) {
ourLog.error("Unknown class[" + nextValue + "] for resource definition: " + nextKey.substring("resource.".length()), e);
}
} else {
ourLog.warn("Unexpected property in version property file: {}={}", nextKey, nextValue);
}
}
} catch (IOException e) {
throw new ConfigurationException("Failed to load model property file from classpath: " + "/ca/uhn/fhir/model/dstu/model.properties");
}
}
}

View File

@ -28,6 +28,7 @@ import java.util.List;
import java.util.Map;
import org.hl7.fhir.instance.model.IBase;
import org.hl7.fhir.instance.model.api.IBaseDatatype;
import ca.uhn.fhir.model.api.IDatatype;
import ca.uhn.fhir.model.api.IResource;
@ -42,7 +43,7 @@ public class RuntimeChildAny extends RuntimeChildChoiceDefinition {
}
@Override
void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
List<Class<? extends IBase>> choiceTypes = new ArrayList<Class<? extends IBase>>();
for (Class<? extends IBase> next : theClassToElementDefinitions.keySet()) {
@ -61,7 +62,7 @@ public class RuntimeChildAny extends RuntimeChildChoiceDefinition {
}
}
if (IResource.class.isAssignableFrom(next) || IDatatype.class.isAssignableFrom(next)) {
if (IResource.class.isAssignableFrom(next) || IDatatype.class.isAssignableFrom(next) || IBaseDatatype.class.isAssignableFrom(next)) {
choiceTypes.add(next);
}
}
@ -83,7 +84,7 @@ public class RuntimeChildAny extends RuntimeChildChoiceDefinition {
setChoiceTypes(choiceTypes);
super.sealAndInitialize(theClassToElementDefinitions);
super.sealAndInitialize(theContext, theClassToElementDefinitions);
}

View File

@ -34,7 +34,6 @@ import org.hl7.fhir.instance.model.IBaseResource;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.dstu.composite.ResourceReferenceDt;
public class RuntimeChildChoiceDefinition extends BaseRuntimeDeclaredChildDefinition {
@ -78,7 +77,7 @@ public class RuntimeChildChoiceDefinition extends BaseRuntimeDeclaredChildDefini
@SuppressWarnings("unchecked")
@Override
void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
myNameToChildDefinition = new HashMap<String, BaseRuntimeElementDefinition<?>>();
myDatatypeToElementName = new HashMap<Class<? extends IBase>, String>();
myDatatypeToElementDefinition = new HashMap<Class<? extends IBase>, BaseRuntimeElementDefinition<?>>();
@ -94,7 +93,7 @@ public class RuntimeChildChoiceDefinition extends BaseRuntimeDeclaredChildDefini
List<Class<? extends IBaseResource>> types = new ArrayList<Class<? extends IBaseResource>>();
types.add((Class<? extends IBaseResource>) next);
nextDef = new RuntimeResourceReferenceDefinition(elementName, types);
nextDef.sealAndInitialize(theClassToElementDefinitions);
nextDef.sealAndInitialize(theContext, theClassToElementDefinitions);
} else {
nextDef = theClassToElementDefinitions.get(next);
elementName = getElementName() + StringUtils.capitalize(nextDef.getName());
@ -106,9 +105,10 @@ public class RuntimeChildChoiceDefinition extends BaseRuntimeDeclaredChildDefini
}
if (IBaseResource.class.isAssignableFrom(next)) {
myDatatypeToElementDefinition.put(ResourceReferenceDt.class, nextDef);
Class<? extends IBase> refType = theContext.getVersion().getResourceReferenceType();
myDatatypeToElementDefinition.put(refType, nextDef);
alternateElementName = getElementName() + "Resource";
myDatatypeToElementName.put(ResourceReferenceDt.class, alternateElementName);
myDatatypeToElementName.put(refType, alternateElementName);
}
myDatatypeToElementDefinition.put(next, nextDef);

View File

@ -21,6 +21,7 @@ package ca.uhn.fhir.context;
*/
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
@ -29,7 +30,7 @@ import org.hl7.fhir.instance.model.IBase;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.dstu.composite.ContainedDt;
import ca.uhn.fhir.model.base.composite.BaseContainedDt;
public class RuntimeChildContainedResources extends BaseRuntimeDeclaredChildDefinition {
@ -47,13 +48,13 @@ public class RuntimeChildContainedResources extends BaseRuntimeDeclaredChildDefi
@Override
public BaseRuntimeElementDefinition<?> getChildElementDefinitionByDatatype(Class<? extends IBase> theType) {
assert theType.equals(ContainedDt.class);
return myElem;
assert BaseContainedDt.class.isAssignableFrom(theType);
return myElem;
}
@Override
public String getChildNameByDatatype(Class<? extends IBase> theDatatype) {
assert theDatatype.equals(ContainedDt.class);
assert BaseContainedDt.class.isAssignableFrom(theDatatype);
return getElementName();
}
@ -63,8 +64,17 @@ public class RuntimeChildContainedResources extends BaseRuntimeDeclaredChildDefi
}
@Override
void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
myElem = new RuntimeElemContainedResources();
void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
Class<?> actualType = theContext.getVersion().getContainedType();
if (BaseContainedDt.class.isAssignableFrom(actualType)) {
@SuppressWarnings("unchecked")
Class<? extends BaseContainedDt> type = (Class<? extends BaseContainedDt>) actualType;
myElem = new RuntimeElemContainedResources(type);
} else if (ArrayList.class.isAssignableFrom(actualType)) {
myElem = null;
} else {
throw new ConfigurationException("Fhir Version definition returned invalid contained type: " + actualType);
}
}
}

View File

@ -132,7 +132,7 @@ public class RuntimeChildDeclaredExtensionDefinition extends BaseRuntimeDeclared
}
@Override
void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
myUrlToChildExtension = new HashMap<String, RuntimeChildDeclaredExtensionDefinition>();
BaseRuntimeElementDefinition<?> elementDef = theClassToElementDefinitions.get(myChildType);

View File

@ -0,0 +1,70 @@
package ca.uhn.fhir.context;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.hl7.fhir.instance.model.IBase;
import org.hl7.fhir.instance.model.IBaseResource;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.base.composite.BaseContainedDt;
public class RuntimeChildDirectResource extends BaseRuntimeDeclaredChildDefinition {
private RuntimeElemContainedResources myElem;
private FhirContext myContext;
RuntimeChildDirectResource(Field theField, Child theChildAnnotation, Description theDescriptionAnnotation, String theElementName) throws ConfigurationException {
super(theField, theChildAnnotation, theDescriptionAnnotation, theElementName);
}
@Override
public BaseRuntimeElementDefinition<?> getChildByName(String theName) {
return new RuntimeElementDirectResource();
}
@SuppressWarnings("unchecked")
@Override
public BaseRuntimeElementDefinition<?> getChildElementDefinitionByDatatype(Class<? extends IBase> theType) {
return myContext.getResourceDefinition((Class<? extends IBaseResource>) theType);
}
@Override
public String getChildNameByDatatype(Class<? extends IBase> theDatatype) {
return getElementName();
}
@Override
public Set<String> getValidChildNames() {
return Collections.singleton(getElementName());
}
@Override
void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
myContext = theContext;
}
}

View File

@ -0,0 +1,58 @@
package ca.uhn.fhir.context;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.lang.reflect.Field;
import org.hl7.fhir.instance.model.IBase;
import org.hl7.fhir.instance.model.api.IBaseEnumFactory;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Description;
public class RuntimeChildEnumerationDatatypeDefinition extends RuntimeChildPrimitiveDatatypeDefinition {
private Class<? extends IBaseEnumFactory<?>> myBinderType;
private volatile IBaseEnumFactory<?> myBinder;
public RuntimeChildEnumerationDatatypeDefinition(Field theField, String theElementName, Child theChildAnnotation, Description theDescriptionAnnotation, Class<? extends IBase> theDatatype, Class<? extends IBaseEnumFactory<?>> theBinderType) {
super(theField, theElementName, theDescriptionAnnotation, theChildAnnotation, theDatatype);
myBinderType = theBinderType;
}
@Override
public IBaseEnumFactory<?> getInstanceConstructorArguments() {
IBaseEnumFactory<?> retVal = myBinder;
if (retVal == null) {
try {
retVal = myBinderType.newInstance();
} catch (InstantiationException e) {
throw new IllegalStateException("Failed to instantiate " + myBinderType, e);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Failed to instantiate " + myBinderType, e);
}
myBinder = retVal;
}
return retVal;
}
}

View File

@ -32,5 +32,7 @@ public class RuntimeChildPrimitiveDatatypeDefinition extends BaseRuntimeChildDat
public RuntimeChildPrimitiveDatatypeDefinition(Field theField, String theElementName, Description theDescriptionAnnotation, Child theChildAnnotation, Class<? extends IBase> theDatatype) {
super(theField, theElementName, theChildAnnotation, theDescriptionAnnotation, theDatatype);
}
}

View File

@ -71,7 +71,7 @@ public class RuntimeChildResourceBlockDefinition extends BaseRuntimeDeclaredChil
}
@Override
void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
myElementDef = (RuntimeResourceBlockDefinition) theClassToElementDefinitions.get(myResourceBlockType);
}

View File

@ -21,6 +21,7 @@ package ca.uhn.fhir.context;
*/
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
@ -47,7 +48,9 @@ public class RuntimeChildResourceDefinition extends BaseRuntimeDeclaredChildDefi
myResourceTypes = theResourceTypes;
if (theResourceTypes == null || theResourceTypes.isEmpty()) {
throw new ConfigurationException("Field '" + theField.getName() + "' on type '" + theField.getDeclaringClass().getCanonicalName() + "' has no resource types noted");
myResourceTypes = new ArrayList<Class<? extends IBaseResource>>();
myResourceTypes.add(IBaseResource.class);
// throw new ConfigurationException("Field '" + theField.getName() + "' on type '" + theField.getDeclaringClass().getCanonicalName() + "' has no resource types noted");
}
}
@ -78,9 +81,9 @@ public class RuntimeChildResourceDefinition extends BaseRuntimeDeclaredChildDefi
}
@Override
void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
myRuntimeDef = new RuntimeResourceReferenceDefinition(getElementName(), myResourceTypes);
myRuntimeDef.sealAndInitialize(theClassToElementDefinitions);
myRuntimeDef.sealAndInitialize(theContext, theClassToElementDefinitions);
myValidChildNames = new HashSet<String>();
myValidChildNames.add(getElementName());

View File

@ -35,7 +35,6 @@ import org.hl7.fhir.instance.model.IBaseResource;
import ca.uhn.fhir.model.api.ExtensionDt;
import ca.uhn.fhir.model.api.IDatatype;
import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt;
import ca.uhn.fhir.model.dstu.composite.ResourceReferenceDt;
public class RuntimeChildUndeclaredExtensionDefinition extends BaseRuntimeChildDefinition {
@ -51,12 +50,13 @@ public class RuntimeChildUndeclaredExtensionDefinition extends BaseRuntimeChildD
public IAccessor getAccessor() {
return new IAccessor() {
@Override
public List<? extends IBase> getValues(Object theTarget) {
public List<IBase> getValues(Object theTarget) {
ExtensionDt target = (ExtensionDt) theTarget;
if (target.getValue() != null) {
return Collections.singletonList(target.getValue());
return Collections.singletonList((IBase)target.getValue());
}
return target.getUndeclaredExtensions();
ArrayList<IBase> retVal = new ArrayList<IBase>(target.getUndeclaredExtensions());
return retVal;
}
};
}
@ -112,7 +112,7 @@ public class RuntimeChildUndeclaredExtensionDefinition extends BaseRuntimeChildD
}
@Override
void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
Map<String, BaseRuntimeElementDefinition<?>> datatypeAttributeNameToDefinition = new HashMap<String, BaseRuntimeElementDefinition<?>>();
myDatatypeToAttributeName = new HashMap<Class<? extends IBase>, String>();
@ -142,14 +142,14 @@ public class RuntimeChildUndeclaredExtensionDefinition extends BaseRuntimeChildD
}
// Resource Reference
myDatatypeToAttributeName.put(ResourceReferenceDt.class, "valueResource");
myDatatypeToAttributeName.put(theContext.getVersion().getResourceReferenceType(), "valueResource");
List<Class<? extends IBaseResource>> types = new ArrayList<Class<? extends IBaseResource>>();
types.add(IBaseResource.class);
RuntimeResourceReferenceDefinition def = new RuntimeResourceReferenceDefinition("valueResource", types);
def.sealAndInitialize(theClassToElementDefinitions);
def.sealAndInitialize(theContext, theClassToElementDefinitions);
myAttributeNameToDefinition.put("valueResource", def);
myDatatypeToDefinition.put(BaseResourceReferenceDt.class, def);
myDatatypeToDefinition.put(ResourceReferenceDt.class, def);
myDatatypeToDefinition.put(theContext.getVersion().getResourceReferenceType(), def);
}
public static String createExtensionChildName(BaseRuntimeElementDefinition<?> next) {

View File

@ -20,12 +20,13 @@ package ca.uhn.fhir.context;
* #L%
*/
import ca.uhn.fhir.model.dstu.composite.ContainedDt;
import ca.uhn.fhir.model.base.composite.BaseContainedDt;
public class RuntimeElemContainedResources extends BaseRuntimeElementDefinition<ContainedDt> {
public class RuntimeElemContainedResources extends BaseRuntimeElementDefinition<BaseContainedDt> {
public RuntimeElemContainedResources() {
super("contained", ContainedDt.class);
public RuntimeElemContainedResources(Class<? extends BaseContainedDt> theClass) {
super("contained", theClass);
assert BaseContainedDt.class.isAssignableFrom(theClass);
}
@Override

View File

@ -0,0 +1,36 @@
package ca.uhn.fhir.context;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.hl7.fhir.instance.model.IBaseResource;
public class RuntimeElementDirectResource extends BaseRuntimeElementDefinition<IBaseResource> {
public RuntimeElementDirectResource() {
super("DirectChildResource", IBaseResource.class);
}
@Override
public ca.uhn.fhir.context.BaseRuntimeElementDefinition.ChildTypeEnum getChildType() {
return ChildTypeEnum.RESOURCE;
}
}

View File

@ -44,8 +44,8 @@ public class RuntimeExtensionDtDefinition extends RuntimeCompositeDatatypeDefini
}
@Override
public void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
super.sealAndInitialize(theClassToElementDefinitions);
public void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
super.sealAndInitialize(theContext, theClassToElementDefinitions);
/*
* The "url" child is a weird child because it is not parsed and encoded in the normal way,

View File

@ -51,7 +51,7 @@ public class RuntimePrimitiveDatatypeDefinition extends BaseRuntimeElementDefini
}
@Override
void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
// nothing
}

View File

@ -38,7 +38,7 @@ public class RuntimePrimitiveDatatypeNarrativeDefinition extends BaseRuntimeEle
}
@Override
void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
// nothing
}

View File

@ -20,11 +20,11 @@ package ca.uhn.fhir.context;
* #L%
*/
import ca.uhn.fhir.model.api.IResourceBlock;
import org.hl7.fhir.instance.model.IBase;
public class RuntimeResourceBlockDefinition extends BaseRuntimeElementCompositeDefinition<IResourceBlock> {
public class RuntimeResourceBlockDefinition extends BaseRuntimeElementCompositeDefinition<IBase> {
public RuntimeResourceBlockDefinition(String theName, Class<? extends IResourceBlock> theImplementingClass) {
public RuntimeResourceBlockDefinition(String theName, Class<? extends IBase> theImplementingClass) {
super(theName, theImplementingClass);
}

View File

@ -29,6 +29,7 @@ import java.util.Map;
import org.hl7.fhir.instance.model.IBase;
import org.hl7.fhir.instance.model.IBaseResource;
import org.hl7.fhir.instance.model.api.IAnyResource;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.api.annotation.ResourceDef;
@ -38,7 +39,7 @@ public class RuntimeResourceDefinition extends BaseRuntimeElementCompositeDefini
private RuntimeResourceDefinition myBaseDefinition;
private Map<String, RuntimeSearchParam> myNameToSearchParam = new LinkedHashMap<String, RuntimeSearchParam>();
private IResource myProfileDef;
private IBaseResource myProfileDef;
private String myResourceProfile;
private List<RuntimeSearchParam> mySearchParams;
private FhirContext myContext;
@ -57,7 +58,11 @@ public class RuntimeResourceDefinition extends BaseRuntimeElementCompositeDefini
try {
IBaseResource instance = theClass.newInstance();
myStructureVersion = ((IResource)instance).getStructureFhirVersionEnum();
if (instance instanceof IAnyResource) {
myStructureVersion = FhirVersionEnum.DSTU2_HL7ORG;
} else {
myStructureVersion = ((IResource)instance).getStructureFhirVersionEnum();
}
} catch (Exception e) {
throw new ConfigurationException(myContext.getLocalizer().getMessage(getClass(), "nonInstantiableType", theClass.getName(), e.toString()), e);
}
@ -127,8 +132,8 @@ public class RuntimeResourceDefinition extends BaseRuntimeElementCompositeDefini
}
@Override
public void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
super.sealAndInitialize(theClassToElementDefinitions);
public void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
super.sealAndInitialize(theContext, theClassToElementDefinitions);
myNameToSearchParam = Collections.unmodifiableMap(myNameToSearchParam);
@ -152,25 +157,29 @@ public class RuntimeResourceDefinition extends BaseRuntimeElementCompositeDefini
}
@Deprecated
public synchronized IResource toProfile() {
public synchronized IBaseResource toProfile() {
if (myProfileDef != null) {
return myProfileDef;
}
IResource retVal = myContext.getVersion().generateProfile(this, null);
IBaseResource retVal = myContext.getVersion().generateProfile(this, null);
myProfileDef = retVal;
return retVal;
}
public synchronized IResource toProfile(String theServerBase) {
public synchronized IBaseResource toProfile(String theServerBase) {
if (myProfileDef != null) {
return myProfileDef;
}
IResource retVal = myContext.getVersion().generateProfile(this, theServerBase);
IBaseResource retVal = myContext.getVersion().generateProfile(this, theServerBase);
myProfileDef = retVal;
return retVal;
}
public boolean isBundle() {
return "Bundle".equals(getName());
}
}

View File

@ -26,7 +26,7 @@ import java.util.Map;
import org.hl7.fhir.instance.model.IBase;
import org.hl7.fhir.instance.model.IBaseResource;
import org.hl7.fhir.instance.model.Resource;
import org.hl7.fhir.instance.model.api.IAnyResource;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt;
@ -49,10 +49,10 @@ public class RuntimeResourceReferenceDefinition extends BaseRuntimeElementDefini
}
@Override
void sealAndInitialize(Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
void sealAndInitialize(FhirContext theContext, Map<Class<? extends IBase>, BaseRuntimeElementDefinition<?>> theClassToElementDefinitions) {
myResourceTypeToDefinition = new HashMap<Class<? extends IBaseResource>, RuntimeResourceDefinition>();
for (Class<? extends IBaseResource> next : myResourceTypes) {
if (next.equals(IResource.class) || next.equals(Resource.class) || next.equals(IBaseResource.class)) {
if (next.equals(IResource.class) || next.equals(IAnyResource.class) || next.equals(IBaseResource.class)) {
continue;
}
RuntimeResourceDefinition definition = (RuntimeResourceDefinition) theClassToElementDefinitions.get(next);

View File

@ -25,6 +25,7 @@ import java.util.Collections;
import java.util.List;
import org.apache.commons.lang3.Validate;
import org.hl7.fhir.instance.model.api.IBaseDatatype;
public abstract class BaseElement implements IElement, ISupportsUndeclaredExtensions {
@ -32,7 +33,7 @@ public abstract class BaseElement implements IElement, ISupportsUndeclaredExtens
private List<ExtensionDt> myUndeclaredModifierExtensions;
@Override
public ExtensionDt addUndeclaredExtension(boolean theIsModifier, String theUrl, IDatatype theValue) {
public ExtensionDt addUndeclaredExtension(boolean theIsModifier, String theUrl, IBaseDatatype theValue) {
Validate.notEmpty(theUrl, "URL must be populated");
Validate.notNull(theValue, "Value must not be null");
ExtensionDt retVal = new ExtensionDt(theIsModifier, theUrl, theValue);

View File

@ -24,13 +24,15 @@ import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.Validate;
import org.hl7.fhir.instance.model.api.IBaseDatatype;
import org.hl7.fhir.instance.model.api.IBaseExtension;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.DatatypeDef;
import ca.uhn.fhir.model.primitive.StringDt;
@DatatypeDef(name="Extension")
public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDatatype {
public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDatatype, IBaseExtension<ExtensionDt> {
private boolean myModifier;
@ -38,7 +40,7 @@ public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDa
private StringDt myUrl;
@Child(name="value", type=IDatatype.class, order=1, min=0, max=1)
private IElement myValue;
private IBaseDatatype myValue;
public ExtensionDt() {
}
@ -54,7 +56,7 @@ public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDa
myUrl = new StringDt(theUrl);
}
public ExtensionDt(boolean theIsModifier, String theUrl, IDatatype theValue) {
public ExtensionDt(boolean theIsModifier, String theUrl, IBaseDatatype theValue) {
Validate.notEmpty(theUrl, "URL must be populated");
Validate.notNull(theValue, "Value must not be null");
@ -63,15 +65,25 @@ public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDa
myValue=theValue;
}
public StringDt getUrl() {
if (myUrl==null) {
myUrl=new StringDt();
}
return myUrl;
/**
* Returns the URL for this extension.
* <p>
* Note that before HAPI 0.9 this method returned a {@link StringDt} but as of
* HAPI 0.9 this method returns a plain string. This was changed because it does not make sense to use a StringDt here
* since the URL itself can not contain extensions and it was therefore misleading.
* </p>
*/
public String getUrl() {
return myUrl != null ? myUrl.getValue() : null;
}
/**
* Retained for backward compatibility
*
* @see ExtensionDt#getUrl()
*/
public String getUrlAsString() {
return getUrl().getValue();
return getUrl();
}
/**
@ -81,7 +93,7 @@ public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDa
* {@link #getUndeclaredModifierExtensions()} to retrieve the child extensions.
* </p>
*/
public IElement getValue() {
public IBaseDatatype getValue() {
return myValue;
}
@ -117,7 +129,7 @@ public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDa
}
public ExtensionDt setUrl(String theUrl) {
myUrl = new StringDt(theUrl);
myUrl = theUrl != null ? new StringDt(theUrl) : myUrl;
return this;
}
@ -126,8 +138,9 @@ public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDa
return this;
}
public void setValue(IElement theValue) {
public ExtensionDt setValue(IBaseDatatype theValue) {
myValue = theValue;
return this;
}
@Override
@ -135,4 +148,9 @@ public class ExtensionDt extends BaseIdentifiableElement implements ICompositeDa
return new ArrayList<T>();
}
@Override
public List<ExtensionDt> getExtension() {
return getAllUndeclaredExtensions();
}
}

View File

@ -1,5 +1,7 @@
package ca.uhn.fhir.model.api;
import org.hl7.fhir.instance.model.api.IBaseDatatype;
/*
* #%L
* HAPI FHIR - Core Library
@ -20,6 +22,6 @@ package ca.uhn.fhir.model.api;
* #L%
*/
public interface IDatatype extends IElement {
public interface IDatatype extends IElement, IBaseDatatype {
}

View File

@ -22,6 +22,7 @@ package ca.uhn.fhir.model.api;
import java.io.InputStream;
import org.hl7.fhir.instance.model.IBase;
import org.hl7.fhir.instance.model.IBaseResource;
import ca.uhn.fhir.context.FhirVersionEnum;
@ -38,10 +39,14 @@ public interface IFhirVersion {
InputStream getFhirVersionPropertiesFile();
IResource generateProfile(RuntimeResourceDefinition theRuntimeResourceDefinition, String theServerBase);
IBaseResource generateProfile(RuntimeResourceDefinition theRuntimeResourceDefinition, String theServerBase);
IServerConformanceProvider<? extends IBaseResource> createServerConformanceProvider(RestfulServer theRestfulServer);
String getPathToSchemaDefinitions();
Class<? extends IBase> getResourceReferenceType();
Class<?> getContainedType();
}

View File

@ -21,9 +21,9 @@ package ca.uhn.fhir.model.api;
*/
import ca.uhn.fhir.model.api.annotation.ResourceDef;
import ca.uhn.fhir.model.base.composite.BaseContainedDt;
import ca.uhn.fhir.model.base.composite.BaseNarrativeDt;
import ca.uhn.fhir.model.base.resource.ResourceMetadataMap;
import ca.uhn.fhir.model.dstu.composite.ContainedDt;
import ca.uhn.fhir.model.dstu.composite.NarrativeDt;
import ca.uhn.fhir.model.primitive.CodeDt;
import ca.uhn.fhir.model.primitive.IdDt;
@ -54,7 +54,7 @@ public interface IResource extends ICompositeElement, org.hl7.fhir.instance.mode
* </p>
* TODO: document contained resources and link there
*/
ContainedDt getContained();
BaseContainedDt getContained();
/**
* Returns the ID of this resource. Note that this identifier is the URL (or a portion
@ -92,7 +92,7 @@ public interface IResource extends ICompositeElement, org.hl7.fhir.instance.mode
/**
* Returns the narrative block for this resource
*/
NarrativeDt getText();
BaseNarrativeDt getText();
/**
* Sets the ID of this resource. Note that this identifier is the URL (or a portion

View File

@ -22,6 +22,8 @@ package ca.uhn.fhir.model.api;
import java.util.List;
import org.hl7.fhir.instance.model.api.IBaseDatatype;
public interface ISupportsUndeclaredExtensions extends IElement {
/**
@ -52,7 +54,7 @@ public interface ISupportsUndeclaredExtensions extends IElement {
* <li>{@link ExtensionDt#setUrl(String) URL}</li>
* <li>And one of:
* <ul>
* <li>{@link ExtensionDt#setValue(IElement) A datatype value}</li>
* <li>{@link ExtensionDt#setValue(IBaseDatatype) A datatype value}</li>
* <li>{@link #addUndeclaredExtension(ExtensionDt) Further sub-extensions}</li>
* </ul>
* </ul>
@ -64,7 +66,7 @@ public interface ISupportsUndeclaredExtensions extends IElement {
/**
* Adds an extension to this object
*/
ExtensionDt addUndeclaredExtension(boolean theIsModifier, String theUrl, IDatatype theValue);
ExtensionDt addUndeclaredExtension(boolean theIsModifier, String theUrl, IBaseDatatype theValue);
/**
* Adds an extension to this object. This method is intended for use when

View File

@ -28,6 +28,8 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.hl7.fhir.instance.model.IBase;
/**
* A collection of tags present on a single resource. TagList is backed by a {@link LinkedHashSet}, so the order of added tags will be consistent, but duplicates will not be preserved.
*
@ -35,7 +37,7 @@ import java.util.Set;
* <b>Thread safety:</b> This class is not thread safe
* </p>
*/
public class TagList implements Set<Tag>, Serializable {
public class TagList implements Set<Tag>, Serializable, IBase {
public static final String ATTR_CATEGORY = "category";
public static final String ELEMENT_NAME = "TagList";

View File

@ -24,6 +24,9 @@ import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Enumeration;
import org.hl7.fhir.instance.model.api.IBaseEnumFactory;
import ca.uhn.fhir.model.api.IElement;
@ -97,4 +100,28 @@ public @interface Child {
// */
// String replaces() default "";
/**
* For children which accept an {@link Enumeration} as the type, this
* field indicates the type to use for the enum factory
*/
Class<? extends IBaseEnumFactory<?>> enumFactory() default NoEnumFactory.class;
public static class NoEnumFactory implements IBaseEnumFactory<Enum<?>> {
private NoEnumFactory() {
// non instantiable
}
@Override
public Enum<?> fromCode(String theCodeString) throws IllegalArgumentException {
return null;
}
@Override
public String toCode(Enum<?> theCode) {
return null;
}
}
}

View File

@ -25,6 +25,8 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.hl7.fhir.instance.model.IBaseResource;
@Target(value=ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SearchParamDefinition {
@ -58,4 +60,10 @@ public @interface SearchParamDefinition {
*/
String[] compositeOf() default {};
/**
* For search params of type "reference", this can optionally be used to
* specify the resource type(s) that this parameter applies to.
*/
Class<? extends IBaseResource>[] target() default {};
}

View File

@ -26,6 +26,7 @@ import ca.uhn.fhir.model.api.BaseIdentifiableElement;
import ca.uhn.fhir.model.api.ICompositeDatatype;
import ca.uhn.fhir.model.api.IQueryParameterType;
import ca.uhn.fhir.model.primitive.CodeDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.model.primitive.UriDt;
import ca.uhn.fhir.rest.param.ParameterUtil;
@ -54,6 +55,20 @@ public abstract class BaseCodingDt extends BaseIdentifiableElement implements IC
*/
public abstract UriDt getSystemElement();
/**
* Gets the value(s) for <b>display</b> (Representation defined by the system).
* creating it if it does
* not exist. Will not return <code>null</code>.
*
* <p>
* <b>Definition:</b>
* A representation of the meaning of the code in the system, following the rules of the system.
* </p>
*/
public abstract StringDt getDisplayElement();
public abstract BaseCodingDt setDisplay( String theString);
/**
* {@inheritDoc}
*/

View File

@ -1,5 +1,10 @@
package ca.uhn.fhir.model.base.composite;
import java.util.List;
import ca.uhn.fhir.model.api.IDatatype;
import ca.uhn.fhir.model.api.IResource;
/*
* #%L
* HAPI FHIR - Core Library
@ -20,6 +25,8 @@ package ca.uhn.fhir.model.base.composite;
* #L%
*/
public class BaseContainedDt {
public abstract class BaseContainedDt implements IDatatype {
public abstract List<? extends IResource> getContainedResources();
}

View File

@ -1,4 +1,9 @@
package org.hl7.fhir.instance.model.annotations;
package ca.uhn.fhir.model.base.composite;
import ca.uhn.fhir.model.api.BaseIdentifiableElement;
import ca.uhn.fhir.model.api.ICompositeDatatype;
import ca.uhn.fhir.model.primitive.BoundCodeDt;
import ca.uhn.fhir.model.primitive.XhtmlDt;
/*
* #%L
@ -20,27 +25,13 @@ package org.hl7.fhir.instance.model.annotations;
* #L%
*/
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Class annotation used to indicate a class which is a "block"/"component" type. A block
* is a nested group of fields within a resource definition and can contain other blocks as
* well as data types.
* <p>
* An example of a block would be Patient.contact
* </p>
* @param <T> The narrative status enum type
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value= {ElementType.TYPE})
public @interface Block {
public abstract class BaseNarrativeDt<T extends Enum<?>> extends BaseIdentifiableElement implements ICompositeDatatype {
/**
* @deprecated Do not use, will be removed
*/
@Deprecated
String name() default "";
public abstract BoundCodeDt<T> getStatus();
public abstract XhtmlDt getDiv();
}

View File

@ -27,16 +27,18 @@ import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.hl7.fhir.instance.model.api.IBaseDatatype;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.BaseIdentifiableElement;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.parser.IParser;
import ca.uhn.fhir.rest.client.BaseClient;
import ca.uhn.fhir.rest.client.api.IRestfulClient;
public abstract class BaseResourceReferenceDt extends BaseIdentifiableElement {
public abstract class BaseResourceReferenceDt extends BaseIdentifiableElement implements IBaseDatatype {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BaseResourceReferenceDt.class);
private IResource myResource;
@ -59,14 +61,15 @@ public abstract class BaseResourceReferenceDt extends BaseIdentifiableElement {
setReference(theResource.getId());
}
public abstract StringDt getDisplayElement();
public abstract IdDt getReference();
/**
* Gets the actual loaded and parsed resource instance, <b>if it is already present</b>. This method will return the resource instance only if it has previously been loaded using
* {@link #loadResource(IRestfulClient)} or it was contained within the resource containing this resource.
*
* See the FHIR specification section on <a href="http://www.hl7.org/implement/standards/fhir/references.html#id">contained resources</a>
* for more information.
* See the FHIR specification section on <a href="http://www.hl7.org/implement/standards/fhir/references.html#id">contained resources</a> for more information.
*
* @see #loadResource(IRestfulClient)
*/

View File

@ -0,0 +1,38 @@
package ca.uhn.fhir.model.base.resource;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 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 ca.uhn.fhir.model.api.IResource;
public interface BaseBinary extends IResource {
byte[] getContent();
String getContentAsBase64();
String getContentType();
void setContent(byte[] theContent);
void setContentAsBase64(String theContent);
void setContentType(String theContentType);
}

View File

@ -20,13 +20,12 @@ package ca.uhn.fhir.model.base.resource;
* #L%
*/
import ca.uhn.fhir.model.api.BaseResource;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.StringDt;
//@ResourceDef(name="Conformance")
public abstract class BaseConformance extends BaseResource implements IResource {
public interface BaseConformance extends IResource {
public abstract StringDt getDescriptionElement();

View File

@ -23,14 +23,13 @@ package ca.uhn.fhir.model.base.resource;
import java.util.List;
import ca.uhn.fhir.model.api.BaseIdentifiableElement;
import ca.uhn.fhir.model.api.BaseResource;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.api.IResourceBlock;
import ca.uhn.fhir.model.base.composite.BaseCodingDt;
import ca.uhn.fhir.model.primitive.CodeDt;
import ca.uhn.fhir.model.primitive.StringDt;
public abstract class BaseOperationOutcome extends BaseResource implements IResource {
public interface BaseOperationOutcome extends IResource {
public abstract BaseIssue addIssue();

View File

@ -20,9 +20,8 @@ package ca.uhn.fhir.model.base.resource;
* #L%
*/
import ca.uhn.fhir.model.api.BaseResource;
import ca.uhn.fhir.model.api.IResource;
public abstract class BaseSecurityEvent extends BaseResource implements IResource {
public interface BaseSecurityEvent extends IResource {
}

View File

@ -1,143 +0,0 @@
package ca.uhn.fhir.model.dstu.valueset;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import ca.uhn.fhir.model.api.IValueSetEnumBinder;
public enum AdministrativeGenderCodesEnum {
/**
* Code Value: <b>F</b>
*/
F("F", "http://hl7.org/fhir/v3/AdministrativeGender"),
/**
* Code Value: <b>M</b>
*/
M("M", "http://hl7.org/fhir/v3/AdministrativeGender"),
/**
* Code Value: <b>UN</b>
*/
UN("UN", "http://hl7.org/fhir/v3/AdministrativeGender"),
/**
* Code Value: <b>UNK</b>
*/
UNK("UNK", "http://hl7.org/fhir/v3/NullFlavor"),
;
/**
* Identifier for this Value Set:
* http://hl7.org/fhir/vs/administrative-gender
*/
public static final String VALUESET_IDENTIFIER = "http://hl7.org/fhir/vs/administrative-gender";
/**
* Name for this Value Set:
* Administrative Gender Codes
*/
public static final String VALUESET_NAME = "Administrative Gender Codes";
private static Map<String, AdministrativeGenderCodesEnum> CODE_TO_ENUM = new HashMap<String, AdministrativeGenderCodesEnum>();
private static Map<String, Map<String, AdministrativeGenderCodesEnum>> SYSTEM_TO_CODE_TO_ENUM = new HashMap<String, Map<String, AdministrativeGenderCodesEnum>>();
private final String myCode;
private final String mySystem;
static {
for (AdministrativeGenderCodesEnum next : AdministrativeGenderCodesEnum.values()) {
CODE_TO_ENUM.put(next.getCode(), next);
if (!SYSTEM_TO_CODE_TO_ENUM.containsKey(next.getSystem())) {
SYSTEM_TO_CODE_TO_ENUM.put(next.getSystem(), new HashMap<String, AdministrativeGenderCodesEnum>());
}
SYSTEM_TO_CODE_TO_ENUM.get(next.getSystem()).put(next.getCode(), next);
}
}
/**
* Returns the code associated with this enumerated value
*/
public String getCode() {
return myCode;
}
/**
* Returns the code system associated with this enumerated value
*/
public String getSystem() {
return mySystem;
}
/**
* Returns the enumerated value associated with this code
*/
public AdministrativeGenderCodesEnum forCode(String theCode) {
AdministrativeGenderCodesEnum retVal = CODE_TO_ENUM.get(theCode);
return retVal;
}
/**
* Converts codes to their respective enumerated values
*/
public static final IValueSetEnumBinder<AdministrativeGenderCodesEnum> VALUESET_BINDER = new IValueSetEnumBinder<AdministrativeGenderCodesEnum>() {
@Override
public String toCodeString(AdministrativeGenderCodesEnum theEnum) {
return theEnum.getCode();
}
@Override
public String toSystemString(AdministrativeGenderCodesEnum theEnum) {
return theEnum.getSystem();
}
@Override
public AdministrativeGenderCodesEnum fromCodeString(String theCodeString) {
return CODE_TO_ENUM.get(theCodeString);
}
@Override
public AdministrativeGenderCodesEnum fromCodeString(String theCodeString, String theSystemString) {
Map<String, AdministrativeGenderCodesEnum> map = SYSTEM_TO_CODE_TO_ENUM.get(theSystemString);
if (map == null) {
return null;
}
return map.get(theCodeString);
}
};
/**
* Constructor
*/
AdministrativeGenderCodesEnum(String theCode, String theSystem) {
myCode = theCode;
mySystem = theSystem;
}
}

View File

@ -1,151 +0,0 @@
package ca.uhn.fhir.model.dstu.valueset;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import ca.uhn.fhir.model.api.IValueSetEnumBinder;
public enum CausalityExpectationEnum {
/**
* Code Value: <b>likely</b>
*
* Likely that this specific exposure caused the reaction.
*/
LIKELY("likely", "http://hl7.org/fhir/causalityExpectation"),
/**
* Code Value: <b>unlikely</b>
*
* Unlikely that this specific exposure caused the reaction - the exposure is being linked to for information purposes.
*/
UNLIKELY("unlikely", "http://hl7.org/fhir/causalityExpectation"),
/**
* Code Value: <b>confirmed</b>
*
* It has been confirmed that this exposure was one of the causes of the reaction.
*/
CONFIRMED("confirmed", "http://hl7.org/fhir/causalityExpectation"),
/**
* Code Value: <b>unknown</b>
*
* It is unknown whether this exposure had anything to do with the reaction.
*/
UNKNOWN("unknown", "http://hl7.org/fhir/causalityExpectation"),
;
/**
* Identifier for this Value Set:
* http://hl7.org/fhir/vs/causalityExpectation
*/
public static final String VALUESET_IDENTIFIER = "http://hl7.org/fhir/vs/causalityExpectation";
/**
* Name for this Value Set:
* CausalityExpectation
*/
public static final String VALUESET_NAME = "CausalityExpectation";
private static Map<String, CausalityExpectationEnum> CODE_TO_ENUM = new HashMap<String, CausalityExpectationEnum>();
private static Map<String, Map<String, CausalityExpectationEnum>> SYSTEM_TO_CODE_TO_ENUM = new HashMap<String, Map<String, CausalityExpectationEnum>>();
private final String myCode;
private final String mySystem;
static {
for (CausalityExpectationEnum next : CausalityExpectationEnum.values()) {
CODE_TO_ENUM.put(next.getCode(), next);
if (!SYSTEM_TO_CODE_TO_ENUM.containsKey(next.getSystem())) {
SYSTEM_TO_CODE_TO_ENUM.put(next.getSystem(), new HashMap<String, CausalityExpectationEnum>());
}
SYSTEM_TO_CODE_TO_ENUM.get(next.getSystem()).put(next.getCode(), next);
}
}
/**
* Returns the code associated with this enumerated value
*/
public String getCode() {
return myCode;
}
/**
* Returns the code system associated with this enumerated value
*/
public String getSystem() {
return mySystem;
}
/**
* Returns the enumerated value associated with this code
*/
public CausalityExpectationEnum forCode(String theCode) {
CausalityExpectationEnum retVal = CODE_TO_ENUM.get(theCode);
return retVal;
}
/**
* Converts codes to their respective enumerated values
*/
public static final IValueSetEnumBinder<CausalityExpectationEnum> VALUESET_BINDER = new IValueSetEnumBinder<CausalityExpectationEnum>() {
@Override
public String toCodeString(CausalityExpectationEnum theEnum) {
return theEnum.getCode();
}
@Override
public String toSystemString(CausalityExpectationEnum theEnum) {
return theEnum.getSystem();
}
@Override
public CausalityExpectationEnum fromCodeString(String theCodeString) {
return CODE_TO_ENUM.get(theCodeString);
}
@Override
public CausalityExpectationEnum fromCodeString(String theCodeString, String theSystemString) {
Map<String, CausalityExpectationEnum> map = SYSTEM_TO_CODE_TO_ENUM.get(theSystemString);
if (map == null) {
return null;
}
return map.get(theCodeString);
}
};
/**
* Constructor
*/
CausalityExpectationEnum(String theCode, String theSystem) {
myCode = theCode;
mySystem = theSystem;
}
}

View File

@ -1,137 +0,0 @@
package ca.uhn.fhir.model.dstu.valueset;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import ca.uhn.fhir.model.api.IValueSetEnumBinder;
public enum ConditionRelationshipTypeEnum {
/**
* Code Value: <b>due-to</b>
*
* this condition follows the identified condition/procedure/substance and is a consequence of it.
*/
DUE_TO("due-to", "http://hl7.org/fhir/condition-relationship-type"),
/**
* Code Value: <b>following</b>
*
* this condition follows the identified condition/procedure/substance, but it is not known whether they are causually linked.
*/
FOLLOWING("following", "http://hl7.org/fhir/condition-relationship-type"),
;
/**
* Identifier for this Value Set:
* http://hl7.org/fhir/vs/condition-relationship-type
*/
public static final String VALUESET_IDENTIFIER = "http://hl7.org/fhir/vs/condition-relationship-type";
/**
* Name for this Value Set:
* ConditionRelationshipType
*/
public static final String VALUESET_NAME = "ConditionRelationshipType";
private static Map<String, ConditionRelationshipTypeEnum> CODE_TO_ENUM = new HashMap<String, ConditionRelationshipTypeEnum>();
private static Map<String, Map<String, ConditionRelationshipTypeEnum>> SYSTEM_TO_CODE_TO_ENUM = new HashMap<String, Map<String, ConditionRelationshipTypeEnum>>();
private final String myCode;
private final String mySystem;
static {
for (ConditionRelationshipTypeEnum next : ConditionRelationshipTypeEnum.values()) {
CODE_TO_ENUM.put(next.getCode(), next);
if (!SYSTEM_TO_CODE_TO_ENUM.containsKey(next.getSystem())) {
SYSTEM_TO_CODE_TO_ENUM.put(next.getSystem(), new HashMap<String, ConditionRelationshipTypeEnum>());
}
SYSTEM_TO_CODE_TO_ENUM.get(next.getSystem()).put(next.getCode(), next);
}
}
/**
* Returns the code associated with this enumerated value
*/
public String getCode() {
return myCode;
}
/**
* Returns the code system associated with this enumerated value
*/
public String getSystem() {
return mySystem;
}
/**
* Returns the enumerated value associated with this code
*/
public ConditionRelationshipTypeEnum forCode(String theCode) {
ConditionRelationshipTypeEnum retVal = CODE_TO_ENUM.get(theCode);
return retVal;
}
/**
* Converts codes to their respective enumerated values
*/
public static final IValueSetEnumBinder<ConditionRelationshipTypeEnum> VALUESET_BINDER = new IValueSetEnumBinder<ConditionRelationshipTypeEnum>() {
@Override
public String toCodeString(ConditionRelationshipTypeEnum theEnum) {
return theEnum.getCode();
}
@Override
public String toSystemString(ConditionRelationshipTypeEnum theEnum) {
return theEnum.getSystem();
}
@Override
public ConditionRelationshipTypeEnum fromCodeString(String theCodeString) {
return CODE_TO_ENUM.get(theCodeString);
}
@Override
public ConditionRelationshipTypeEnum fromCodeString(String theCodeString, String theSystemString) {
Map<String, ConditionRelationshipTypeEnum> map = SYSTEM_TO_CODE_TO_ENUM.get(theSystemString);
if (map == null) {
return null;
}
return map.get(theCodeString);
}
};
/**
* Constructor
*/
ConditionRelationshipTypeEnum(String theCode, String theSystem) {
myCode = theCode;
mySystem = theSystem;
}
}

View File

@ -1,151 +0,0 @@
package ca.uhn.fhir.model.dstu.valueset;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import ca.uhn.fhir.model.api.IValueSetEnumBinder;
public enum ContactSystemEnum {
/**
* Code Value: <b>phone</b>
*
* The value is a telephone number used for voice calls. Use of full international numbers starting with + is recommended to enable automatic dialing support but not required.
*/
PHONE("phone", "http://hl7.org/fhir/contact-system"),
/**
* Code Value: <b>fax</b>
*
* The value is a fax machine. Use of full international numbers starting with + is recommended to enable automatic dialing support but not required.
*/
FAX("fax", "http://hl7.org/fhir/contact-system"),
/**
* Code Value: <b>email</b>
*
* The value is an email address.
*/
EMAIL("email", "http://hl7.org/fhir/contact-system"),
/**
* Code Value: <b>url</b>
*
* The value is a url. This is intended for various personal contacts including blogs, Twitter, Facebook, etc. Do not use for email addresses.
*/
URL("url", "http://hl7.org/fhir/contact-system"),
;
/**
* Identifier for this Value Set:
* http://hl7.org/fhir/vs/contact-system
*/
public static final String VALUESET_IDENTIFIER = "http://hl7.org/fhir/vs/contact-system";
/**
* Name for this Value Set:
* ContactSystem
*/
public static final String VALUESET_NAME = "ContactSystem";
private static Map<String, ContactSystemEnum> CODE_TO_ENUM = new HashMap<String, ContactSystemEnum>();
private static Map<String, Map<String, ContactSystemEnum>> SYSTEM_TO_CODE_TO_ENUM = new HashMap<String, Map<String, ContactSystemEnum>>();
private final String myCode;
private final String mySystem;
static {
for (ContactSystemEnum next : ContactSystemEnum.values()) {
CODE_TO_ENUM.put(next.getCode(), next);
if (!SYSTEM_TO_CODE_TO_ENUM.containsKey(next.getSystem())) {
SYSTEM_TO_CODE_TO_ENUM.put(next.getSystem(), new HashMap<String, ContactSystemEnum>());
}
SYSTEM_TO_CODE_TO_ENUM.get(next.getSystem()).put(next.getCode(), next);
}
}
/**
* Returns the code associated with this enumerated value
*/
public String getCode() {
return myCode;
}
/**
* Returns the code system associated with this enumerated value
*/
public String getSystem() {
return mySystem;
}
/**
* Returns the enumerated value associated with this code
*/
public ContactSystemEnum forCode(String theCode) {
ContactSystemEnum retVal = CODE_TO_ENUM.get(theCode);
return retVal;
}
/**
* Converts codes to their respective enumerated values
*/
public static final IValueSetEnumBinder<ContactSystemEnum> VALUESET_BINDER = new IValueSetEnumBinder<ContactSystemEnum>() {
@Override
public String toCodeString(ContactSystemEnum theEnum) {
return theEnum.getCode();
}
@Override
public String toSystemString(ContactSystemEnum theEnum) {
return theEnum.getSystem();
}
@Override
public ContactSystemEnum fromCodeString(String theCodeString) {
return CODE_TO_ENUM.get(theCodeString);
}
@Override
public ContactSystemEnum fromCodeString(String theCodeString, String theSystemString) {
Map<String, ContactSystemEnum> map = SYSTEM_TO_CODE_TO_ENUM.get(theSystemString);
if (map == null) {
return null;
}
return map.get(theCodeString);
}
};
/**
* Constructor
*/
ContactSystemEnum(String theCode, String theSystem) {
myCode = theCode;
mySystem = theSystem;
}
}

View File

@ -1,158 +0,0 @@
package ca.uhn.fhir.model.dstu.valueset;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import ca.uhn.fhir.model.api.IValueSetEnumBinder;
public enum ContactUseEnum {
/**
* Code Value: <b>home</b>
*
* A communication contact at a home; attempted contacts for business purposes might intrude privacy and chances are one will contact family or other household members instead of the person one wishes to call. Typically used with urgent cases, or if no other contacts are available.
*/
HOME("home", "http://hl7.org/fhir/contact-use"),
/**
* Code Value: <b>work</b>
*
* An office contact. First choice for business related contacts during business hours.
*/
WORK("work", "http://hl7.org/fhir/contact-use"),
/**
* Code Value: <b>temp</b>
*
* A temporary contact. The period can provide more detailed information.
*/
TEMP("temp", "http://hl7.org/fhir/contact-use"),
/**
* Code Value: <b>old</b>
*
* This contact is no longer in use (or was never correct, but retained for records).
*/
OLD("old", "http://hl7.org/fhir/contact-use"),
/**
* Code Value: <b>mobile</b>
*
* A telecommunication device that moves and stays with its owner. May have characteristics of all other use codes, suitable for urgent matters, not the first choice for routine business.
*/
MOBILE("mobile", "http://hl7.org/fhir/contact-use"),
;
/**
* Identifier for this Value Set:
* http://hl7.org/fhir/vs/contact-use
*/
public static final String VALUESET_IDENTIFIER = "http://hl7.org/fhir/vs/contact-use";
/**
* Name for this Value Set:
* ContactUse
*/
public static final String VALUESET_NAME = "ContactUse";
private static Map<String, ContactUseEnum> CODE_TO_ENUM = new HashMap<String, ContactUseEnum>();
private static Map<String, Map<String, ContactUseEnum>> SYSTEM_TO_CODE_TO_ENUM = new HashMap<String, Map<String, ContactUseEnum>>();
private final String myCode;
private final String mySystem;
static {
for (ContactUseEnum next : ContactUseEnum.values()) {
CODE_TO_ENUM.put(next.getCode(), next);
if (!SYSTEM_TO_CODE_TO_ENUM.containsKey(next.getSystem())) {
SYSTEM_TO_CODE_TO_ENUM.put(next.getSystem(), new HashMap<String, ContactUseEnum>());
}
SYSTEM_TO_CODE_TO_ENUM.get(next.getSystem()).put(next.getCode(), next);
}
}
/**
* Returns the code associated with this enumerated value
*/
public String getCode() {
return myCode;
}
/**
* Returns the code system associated with this enumerated value
*/
public String getSystem() {
return mySystem;
}
/**
* Returns the enumerated value associated with this code
*/
public ContactUseEnum forCode(String theCode) {
ContactUseEnum retVal = CODE_TO_ENUM.get(theCode);
return retVal;
}
/**
* Converts codes to their respective enumerated values
*/
public static final IValueSetEnumBinder<ContactUseEnum> VALUESET_BINDER = new IValueSetEnumBinder<ContactUseEnum>() {
@Override
public String toCodeString(ContactUseEnum theEnum) {
return theEnum.getCode();
}
@Override
public String toSystemString(ContactUseEnum theEnum) {
return theEnum.getSystem();
}
@Override
public ContactUseEnum fromCodeString(String theCodeString) {
return CODE_TO_ENUM.get(theCodeString);
}
@Override
public ContactUseEnum fromCodeString(String theCodeString, String theSystemString) {
Map<String, ContactUseEnum> map = SYSTEM_TO_CODE_TO_ENUM.get(theSystemString);
if (map == null) {
return null;
}
return map.get(theCodeString);
}
};
/**
* Constructor
*/
ContactUseEnum(String theCode, String theSystem) {
myCode = theCode;
mySystem = theSystem;
}
}

View File

@ -1,151 +0,0 @@
package ca.uhn.fhir.model.dstu.valueset;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import ca.uhn.fhir.model.api.IValueSetEnumBinder;
public enum CriticalityEnum {
/**
* Code Value: <b>fatal</b>
*
* Likely to result in death if re-exposed.
*/
FATAL("fatal", "http://hl7.org/fhir/criticality"),
/**
* Code Value: <b>high</b>
*
* Likely to result in reactions that will need to be treated if re-exposed.
*/
HIGH("high", "http://hl7.org/fhir/criticality"),
/**
* Code Value: <b>medium</b>
*
* Likely to result in reactions that will inconvenience the subject.
*/
MEDIUM("medium", "http://hl7.org/fhir/criticality"),
/**
* Code Value: <b>low</b>
*
* Not likely to result in any inconveniences for the subject.
*/
LOW("low", "http://hl7.org/fhir/criticality"),
;
/**
* Identifier for this Value Set:
* http://hl7.org/fhir/vs/criticality
*/
public static final String VALUESET_IDENTIFIER = "http://hl7.org/fhir/vs/criticality";
/**
* Name for this Value Set:
* Criticality
*/
public static final String VALUESET_NAME = "Criticality";
private static Map<String, CriticalityEnum> CODE_TO_ENUM = new HashMap<String, CriticalityEnum>();
private static Map<String, Map<String, CriticalityEnum>> SYSTEM_TO_CODE_TO_ENUM = new HashMap<String, Map<String, CriticalityEnum>>();
private final String myCode;
private final String mySystem;
static {
for (CriticalityEnum next : CriticalityEnum.values()) {
CODE_TO_ENUM.put(next.getCode(), next);
if (!SYSTEM_TO_CODE_TO_ENUM.containsKey(next.getSystem())) {
SYSTEM_TO_CODE_TO_ENUM.put(next.getSystem(), new HashMap<String, CriticalityEnum>());
}
SYSTEM_TO_CODE_TO_ENUM.get(next.getSystem()).put(next.getCode(), next);
}
}
/**
* Returns the code associated with this enumerated value
*/
public String getCode() {
return myCode;
}
/**
* Returns the code system associated with this enumerated value
*/
public String getSystem() {
return mySystem;
}
/**
* Returns the enumerated value associated with this code
*/
public CriticalityEnum forCode(String theCode) {
CriticalityEnum retVal = CODE_TO_ENUM.get(theCode);
return retVal;
}
/**
* Converts codes to their respective enumerated values
*/
public static final IValueSetEnumBinder<CriticalityEnum> VALUESET_BINDER = new IValueSetEnumBinder<CriticalityEnum>() {
@Override
public String toCodeString(CriticalityEnum theEnum) {
return theEnum.getCode();
}
@Override
public String toSystemString(CriticalityEnum theEnum) {
return theEnum.getSystem();
}
@Override
public CriticalityEnum fromCodeString(String theCodeString) {
return CODE_TO_ENUM.get(theCodeString);
}
@Override
public CriticalityEnum fromCodeString(String theCodeString, String theSystemString) {
Map<String, CriticalityEnum> map = SYSTEM_TO_CODE_TO_ENUM.get(theSystemString);
if (map == null) {
return null;
}
return map.get(theCodeString);
}
};
/**
* Constructor
*/
CriticalityEnum(String theCode, String theSystem) {
myCode = theCode;
mySystem = theSystem;
}
}

View File

@ -1,144 +0,0 @@
package ca.uhn.fhir.model.dstu.valueset;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import ca.uhn.fhir.model.api.IValueSetEnumBinder;
public enum ExposureTypeEnum {
/**
* Code Value: <b>drugadmin</b>
*
* Drug Administration.
*/
DRUGADMIN("drugadmin", "http://hl7.org/fhir/exposureType"),
/**
* Code Value: <b>immuniz</b>
*
* Immunization.
*/
IMMUNIZ("immuniz", "http://hl7.org/fhir/exposureType"),
/**
* Code Value: <b>coincidental</b>
*
* In the same area as the substance.
*/
COINCIDENTAL("coincidental", "http://hl7.org/fhir/exposureType"),
;
/**
* Identifier for this Value Set:
* http://hl7.org/fhir/vs/exposureType
*/
public static final String VALUESET_IDENTIFIER = "http://hl7.org/fhir/vs/exposureType";
/**
* Name for this Value Set:
* ExposureType
*/
public static final String VALUESET_NAME = "ExposureType";
private static Map<String, ExposureTypeEnum> CODE_TO_ENUM = new HashMap<String, ExposureTypeEnum>();
private static Map<String, Map<String, ExposureTypeEnum>> SYSTEM_TO_CODE_TO_ENUM = new HashMap<String, Map<String, ExposureTypeEnum>>();
private final String myCode;
private final String mySystem;
static {
for (ExposureTypeEnum next : ExposureTypeEnum.values()) {
CODE_TO_ENUM.put(next.getCode(), next);
if (!SYSTEM_TO_CODE_TO_ENUM.containsKey(next.getSystem())) {
SYSTEM_TO_CODE_TO_ENUM.put(next.getSystem(), new HashMap<String, ExposureTypeEnum>());
}
SYSTEM_TO_CODE_TO_ENUM.get(next.getSystem()).put(next.getCode(), next);
}
}
/**
* Returns the code associated with this enumerated value
*/
public String getCode() {
return myCode;
}
/**
* Returns the code system associated with this enumerated value
*/
public String getSystem() {
return mySystem;
}
/**
* Returns the enumerated value associated with this code
*/
public ExposureTypeEnum forCode(String theCode) {
ExposureTypeEnum retVal = CODE_TO_ENUM.get(theCode);
return retVal;
}
/**
* Converts codes to their respective enumerated values
*/
public static final IValueSetEnumBinder<ExposureTypeEnum> VALUESET_BINDER = new IValueSetEnumBinder<ExposureTypeEnum>() {
@Override
public String toCodeString(ExposureTypeEnum theEnum) {
return theEnum.getCode();
}
@Override
public String toSystemString(ExposureTypeEnum theEnum) {
return theEnum.getSystem();
}
@Override
public ExposureTypeEnum fromCodeString(String theCodeString) {
return CODE_TO_ENUM.get(theCodeString);
}
@Override
public ExposureTypeEnum fromCodeString(String theCodeString, String theSystemString) {
Map<String, ExposureTypeEnum> map = SYSTEM_TO_CODE_TO_ENUM.get(theSystemString);
if (map == null) {
return null;
}
return map.get(theCodeString);
}
};
/**
* Constructor
*/
ExposureTypeEnum(String theCode, String theSystem) {
myCode = theCode;
mySystem = theSystem;
}
}

View File

@ -1,151 +0,0 @@
package ca.uhn.fhir.model.dstu.valueset;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import ca.uhn.fhir.model.api.IValueSetEnumBinder;
public enum QueryOutcomeEnum {
/**
* Code Value: <b>ok</b>
*
* The query was processed successfully.
*/
OK("ok", "http://hl7.org/fhir/query-outcome"),
/**
* Code Value: <b>limited</b>
*
* The query was processed successfully, but some additional limitations were added.
*/
LIMITED("limited", "http://hl7.org/fhir/query-outcome"),
/**
* Code Value: <b>refused</b>
*
* The server refused to process the query.
*/
REFUSED("refused", "http://hl7.org/fhir/query-outcome"),
/**
* Code Value: <b>error</b>
*
* The server tried to process the query, but some error occurred.
*/
ERROR("error", "http://hl7.org/fhir/query-outcome"),
;
/**
* Identifier for this Value Set:
* http://hl7.org/fhir/vs/query-outcome
*/
public static final String VALUESET_IDENTIFIER = "http://hl7.org/fhir/vs/query-outcome";
/**
* Name for this Value Set:
* QueryOutcome
*/
public static final String VALUESET_NAME = "QueryOutcome";
private static Map<String, QueryOutcomeEnum> CODE_TO_ENUM = new HashMap<String, QueryOutcomeEnum>();
private static Map<String, Map<String, QueryOutcomeEnum>> SYSTEM_TO_CODE_TO_ENUM = new HashMap<String, Map<String, QueryOutcomeEnum>>();
private final String myCode;
private final String mySystem;
static {
for (QueryOutcomeEnum next : QueryOutcomeEnum.values()) {
CODE_TO_ENUM.put(next.getCode(), next);
if (!SYSTEM_TO_CODE_TO_ENUM.containsKey(next.getSystem())) {
SYSTEM_TO_CODE_TO_ENUM.put(next.getSystem(), new HashMap<String, QueryOutcomeEnum>());
}
SYSTEM_TO_CODE_TO_ENUM.get(next.getSystem()).put(next.getCode(), next);
}
}
/**
* Returns the code associated with this enumerated value
*/
public String getCode() {
return myCode;
}
/**
* Returns the code system associated with this enumerated value
*/
public String getSystem() {
return mySystem;
}
/**
* Returns the enumerated value associated with this code
*/
public QueryOutcomeEnum forCode(String theCode) {
QueryOutcomeEnum retVal = CODE_TO_ENUM.get(theCode);
return retVal;
}
/**
* Converts codes to their respective enumerated values
*/
public static final IValueSetEnumBinder<QueryOutcomeEnum> VALUESET_BINDER = new IValueSetEnumBinder<QueryOutcomeEnum>() {
@Override
public String toCodeString(QueryOutcomeEnum theEnum) {
return theEnum.getCode();
}
@Override
public String toSystemString(QueryOutcomeEnum theEnum) {
return theEnum.getSystem();
}
@Override
public QueryOutcomeEnum fromCodeString(String theCodeString) {
return CODE_TO_ENUM.get(theCodeString);
}
@Override
public QueryOutcomeEnum fromCodeString(String theCodeString, String theSystemString) {
Map<String, QueryOutcomeEnum> map = SYSTEM_TO_CODE_TO_ENUM.get(theSystemString);
if (map == null) {
return null;
}
return map.get(theCodeString);
}
};
/**
* Constructor
*/
QueryOutcomeEnum(String theCode, String theSystem) {
myCode = theCode;
mySystem = theSystem;
}
}

View File

@ -1,153 +0,0 @@
package ca.uhn.fhir.model.dstu.valueset;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import ca.uhn.fhir.model.api.IValueSetEnumBinder;
public enum QuestionnaireGroupNameEnum {
/**
* Display: <b>Hair Color</b><br>
* Code Value: <b>B.001</b>
*/
HAIR_COLOR("B.001", "http://hl7.org/fhir/questionnaire-group-name"),
/**
* Display: <b>Vision</b><br>
* Code Value: <b>B.002</b>
*/
VISION("B.002", "http://hl7.org/fhir/questionnaire-group-name"),
/**
* Display: <b>Sleepwalker</b><br>
* Code Value: <b>B.003</b>
*/
SLEEPWALKER("B.003", "http://hl7.org/fhir/questionnaire-group-name"),
/**
* Display: <b>Tooth extraction</b><br>
* Code Value: <b>B.004</b>
*/
TOOTH_EXTRACTION("B.004", "http://hl7.org/fhir/questionnaire-group-name"),
/**
* Display: <b>Stutter</b><br>
* Code Value: <b>B.005</b>
*/
STUTTER("B.005", "http://hl7.org/fhir/questionnaire-group-name"),
;
/**
* Identifier for this Value Set:
* http://hl7.org/fhir/vs/questionnaire-group-name
*/
public static final String VALUESET_IDENTIFIER = "http://hl7.org/fhir/vs/questionnaire-group-name";
/**
* Name for this Value Set:
* QuestionnaireGroupName
*/
public static final String VALUESET_NAME = "QuestionnaireGroupName";
private static Map<String, QuestionnaireGroupNameEnum> CODE_TO_ENUM = new HashMap<String, QuestionnaireGroupNameEnum>();
private static Map<String, Map<String, QuestionnaireGroupNameEnum>> SYSTEM_TO_CODE_TO_ENUM = new HashMap<String, Map<String, QuestionnaireGroupNameEnum>>();
private final String myCode;
private final String mySystem;
static {
for (QuestionnaireGroupNameEnum next : QuestionnaireGroupNameEnum.values()) {
CODE_TO_ENUM.put(next.getCode(), next);
if (!SYSTEM_TO_CODE_TO_ENUM.containsKey(next.getSystem())) {
SYSTEM_TO_CODE_TO_ENUM.put(next.getSystem(), new HashMap<String, QuestionnaireGroupNameEnum>());
}
SYSTEM_TO_CODE_TO_ENUM.get(next.getSystem()).put(next.getCode(), next);
}
}
/**
* Returns the code associated with this enumerated value
*/
public String getCode() {
return myCode;
}
/**
* Returns the code system associated with this enumerated value
*/
public String getSystem() {
return mySystem;
}
/**
* Returns the enumerated value associated with this code
*/
public QuestionnaireGroupNameEnum forCode(String theCode) {
QuestionnaireGroupNameEnum retVal = CODE_TO_ENUM.get(theCode);
return retVal;
}
/**
* Converts codes to their respective enumerated values
*/
public static final IValueSetEnumBinder<QuestionnaireGroupNameEnum> VALUESET_BINDER = new IValueSetEnumBinder<QuestionnaireGroupNameEnum>() {
@Override
public String toCodeString(QuestionnaireGroupNameEnum theEnum) {
return theEnum.getCode();
}
@Override
public String toSystemString(QuestionnaireGroupNameEnum theEnum) {
return theEnum.getSystem();
}
@Override
public QuestionnaireGroupNameEnum fromCodeString(String theCodeString) {
return CODE_TO_ENUM.get(theCodeString);
}
@Override
public QuestionnaireGroupNameEnum fromCodeString(String theCodeString, String theSystemString) {
Map<String, QuestionnaireGroupNameEnum> map = SYSTEM_TO_CODE_TO_ENUM.get(theSystemString);
if (map == null) {
return null;
}
return map.get(theCodeString);
}
};
/**
* Constructor
*/
QuestionnaireGroupNameEnum(String theCode, String theSystem) {
myCode = theCode;
mySystem = theSystem;
}
}

View File

@ -1,141 +0,0 @@
package ca.uhn.fhir.model.dstu.valueset;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import ca.uhn.fhir.model.api.IValueSetEnumBinder;
public enum QuestionnaireNameEnum {
/**
* Display: <b>Cancer Treatment Quality Questionnaire 2012</b><br>
* Code Value: <b>CTQQ-2012</b>
*/
CANCER_TREATMENT_QUALITY_QUESTIONNAIRE_2012("CTQQ-2012", "http://hl7.org/fhir/questionnaire-name"),
/**
* Display: <b>Pre-admission standard Form A</b><br>
* Code Value: <b>PA.form.A</b>
*/
PRE_ADMISSION_STANDARD_FORM_A("PA.form.A", "http://hl7.org/fhir/questionnaire-name"),
/**
* Display: <b>Brazelton Neonatal Assessment Scale</b><br>
* Code Value: <b>BNAS</b>
*/
BRAZELTON_NEONATAL_ASSESSMENT_SCALE("BNAS", "http://hl7.org/fhir/questionnaire-name"),
;
/**
* Identifier for this Value Set:
* http://hl7.org/fhir/vs/questionnaire-name
*/
public static final String VALUESET_IDENTIFIER = "http://hl7.org/fhir/vs/questionnaire-name";
/**
* Name for this Value Set:
* QuestionnaireName
*/
public static final String VALUESET_NAME = "QuestionnaireName";
private static Map<String, QuestionnaireNameEnum> CODE_TO_ENUM = new HashMap<String, QuestionnaireNameEnum>();
private static Map<String, Map<String, QuestionnaireNameEnum>> SYSTEM_TO_CODE_TO_ENUM = new HashMap<String, Map<String, QuestionnaireNameEnum>>();
private final String myCode;
private final String mySystem;
static {
for (QuestionnaireNameEnum next : QuestionnaireNameEnum.values()) {
CODE_TO_ENUM.put(next.getCode(), next);
if (!SYSTEM_TO_CODE_TO_ENUM.containsKey(next.getSystem())) {
SYSTEM_TO_CODE_TO_ENUM.put(next.getSystem(), new HashMap<String, QuestionnaireNameEnum>());
}
SYSTEM_TO_CODE_TO_ENUM.get(next.getSystem()).put(next.getCode(), next);
}
}
/**
* Returns the code associated with this enumerated value
*/
public String getCode() {
return myCode;
}
/**
* Returns the code system associated with this enumerated value
*/
public String getSystem() {
return mySystem;
}
/**
* Returns the enumerated value associated with this code
*/
public QuestionnaireNameEnum forCode(String theCode) {
QuestionnaireNameEnum retVal = CODE_TO_ENUM.get(theCode);
return retVal;
}
/**
* Converts codes to their respective enumerated values
*/
public static final IValueSetEnumBinder<QuestionnaireNameEnum> VALUESET_BINDER = new IValueSetEnumBinder<QuestionnaireNameEnum>() {
@Override
public String toCodeString(QuestionnaireNameEnum theEnum) {
return theEnum.getCode();
}
@Override
public String toSystemString(QuestionnaireNameEnum theEnum) {
return theEnum.getSystem();
}
@Override
public QuestionnaireNameEnum fromCodeString(String theCodeString) {
return CODE_TO_ENUM.get(theCodeString);
}
@Override
public QuestionnaireNameEnum fromCodeString(String theCodeString, String theSystemString) {
Map<String, QuestionnaireNameEnum> map = SYSTEM_TO_CODE_TO_ENUM.get(theSystemString);
if (map == null) {
return null;
}
return map.get(theCodeString);
}
};
/**
* Constructor
*/
QuestionnaireNameEnum(String theCode, String theSystem) {
myCode = theCode;
mySystem = theSystem;
}
}

View File

@ -1,151 +0,0 @@
package ca.uhn.fhir.model.dstu.valueset;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import ca.uhn.fhir.model.api.IValueSetEnumBinder;
public enum ReactionSeverityEnum {
/**
* Code Value: <b>severe</b>
*
* Severe complications arose due to the reaction.
*/
SEVERE("severe", "http://hl7.org/fhir/reactionSeverity"),
/**
* Code Value: <b>serious</b>
*
* Serious inconvenience to the subject.
*/
SERIOUS("serious", "http://hl7.org/fhir/reactionSeverity"),
/**
* Code Value: <b>moderate</b>
*
* Moderate inconvenience to the subject.
*/
MODERATE("moderate", "http://hl7.org/fhir/reactionSeverity"),
/**
* Code Value: <b>minor</b>
*
* Minor inconvenience to the subject.
*/
MINOR("minor", "http://hl7.org/fhir/reactionSeverity"),
;
/**
* Identifier for this Value Set:
* http://hl7.org/fhir/vs/reactionSeverity
*/
public static final String VALUESET_IDENTIFIER = "http://hl7.org/fhir/vs/reactionSeverity";
/**
* Name for this Value Set:
* ReactionSeverity
*/
public static final String VALUESET_NAME = "ReactionSeverity";
private static Map<String, ReactionSeverityEnum> CODE_TO_ENUM = new HashMap<String, ReactionSeverityEnum>();
private static Map<String, Map<String, ReactionSeverityEnum>> SYSTEM_TO_CODE_TO_ENUM = new HashMap<String, Map<String, ReactionSeverityEnum>>();
private final String myCode;
private final String mySystem;
static {
for (ReactionSeverityEnum next : ReactionSeverityEnum.values()) {
CODE_TO_ENUM.put(next.getCode(), next);
if (!SYSTEM_TO_CODE_TO_ENUM.containsKey(next.getSystem())) {
SYSTEM_TO_CODE_TO_ENUM.put(next.getSystem(), new HashMap<String, ReactionSeverityEnum>());
}
SYSTEM_TO_CODE_TO_ENUM.get(next.getSystem()).put(next.getCode(), next);
}
}
/**
* Returns the code associated with this enumerated value
*/
public String getCode() {
return myCode;
}
/**
* Returns the code system associated with this enumerated value
*/
public String getSystem() {
return mySystem;
}
/**
* Returns the enumerated value associated with this code
*/
public ReactionSeverityEnum forCode(String theCode) {
ReactionSeverityEnum retVal = CODE_TO_ENUM.get(theCode);
return retVal;
}
/**
* Converts codes to their respective enumerated values
*/
public static final IValueSetEnumBinder<ReactionSeverityEnum> VALUESET_BINDER = new IValueSetEnumBinder<ReactionSeverityEnum>() {
@Override
public String toCodeString(ReactionSeverityEnum theEnum) {
return theEnum.getCode();
}
@Override
public String toSystemString(ReactionSeverityEnum theEnum) {
return theEnum.getSystem();
}
@Override
public ReactionSeverityEnum fromCodeString(String theCodeString) {
return CODE_TO_ENUM.get(theCodeString);
}
@Override
public ReactionSeverityEnum fromCodeString(String theCodeString, String theSystemString) {
Map<String, ReactionSeverityEnum> map = SYSTEM_TO_CODE_TO_ENUM.get(theSystemString);
if (map == null) {
return null;
}
return map.get(theCodeString);
}
};
/**
* Constructor
*/
ReactionSeverityEnum(String theCode, String theSystem) {
myCode = theCode;
mySystem = theSystem;
}
}

View File

@ -1,151 +0,0 @@
package ca.uhn.fhir.model.dstu.valueset;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import ca.uhn.fhir.model.api.IValueSetEnumBinder;
public enum SensitivityStatusEnum {
/**
* Code Value: <b>suspected</b>
*
* A suspected sensitivity to a substance.
*/
SUSPECTED("suspected", "http://hl7.org/fhir/sensitivitystatus"),
/**
* Code Value: <b>confirmed</b>
*
* The sensitivity has been confirmed and is active.
*/
CONFIRMED("confirmed", "http://hl7.org/fhir/sensitivitystatus"),
/**
* Code Value: <b>refuted</b>
*
* The sensitivity has been shown to never have existed.
*/
REFUTED("refuted", "http://hl7.org/fhir/sensitivitystatus"),
/**
* Code Value: <b>resolved</b>
*
* The sensitivity used to exist but no longer does.
*/
RESOLVED("resolved", "http://hl7.org/fhir/sensitivitystatus"),
;
/**
* Identifier for this Value Set:
* http://hl7.org/fhir/vs/sensitivitystatus
*/
public static final String VALUESET_IDENTIFIER = "http://hl7.org/fhir/vs/sensitivitystatus";
/**
* Name for this Value Set:
* SensitivityStatus
*/
public static final String VALUESET_NAME = "SensitivityStatus";
private static Map<String, SensitivityStatusEnum> CODE_TO_ENUM = new HashMap<String, SensitivityStatusEnum>();
private static Map<String, Map<String, SensitivityStatusEnum>> SYSTEM_TO_CODE_TO_ENUM = new HashMap<String, Map<String, SensitivityStatusEnum>>();
private final String myCode;
private final String mySystem;
static {
for (SensitivityStatusEnum next : SensitivityStatusEnum.values()) {
CODE_TO_ENUM.put(next.getCode(), next);
if (!SYSTEM_TO_CODE_TO_ENUM.containsKey(next.getSystem())) {
SYSTEM_TO_CODE_TO_ENUM.put(next.getSystem(), new HashMap<String, SensitivityStatusEnum>());
}
SYSTEM_TO_CODE_TO_ENUM.get(next.getSystem()).put(next.getCode(), next);
}
}
/**
* Returns the code associated with this enumerated value
*/
public String getCode() {
return myCode;
}
/**
* Returns the code system associated with this enumerated value
*/
public String getSystem() {
return mySystem;
}
/**
* Returns the enumerated value associated with this code
*/
public SensitivityStatusEnum forCode(String theCode) {
SensitivityStatusEnum retVal = CODE_TO_ENUM.get(theCode);
return retVal;
}
/**
* Converts codes to their respective enumerated values
*/
public static final IValueSetEnumBinder<SensitivityStatusEnum> VALUESET_BINDER = new IValueSetEnumBinder<SensitivityStatusEnum>() {
@Override
public String toCodeString(SensitivityStatusEnum theEnum) {
return theEnum.getCode();
}
@Override
public String toSystemString(SensitivityStatusEnum theEnum) {
return theEnum.getSystem();
}
@Override
public SensitivityStatusEnum fromCodeString(String theCodeString) {
return CODE_TO_ENUM.get(theCodeString);
}
@Override
public SensitivityStatusEnum fromCodeString(String theCodeString, String theSystemString) {
Map<String, SensitivityStatusEnum> map = SYSTEM_TO_CODE_TO_ENUM.get(theSystemString);
if (map == null) {
return null;
}
return map.get(theCodeString);
}
};
/**
* Constructor
*/
SensitivityStatusEnum(String theCode, String theSystem) {
myCode = theCode;
mySystem = theSystem;
}
}

View File

@ -1,144 +0,0 @@
package ca.uhn.fhir.model.dstu.valueset;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import ca.uhn.fhir.model.api.IValueSetEnumBinder;
public enum SensitivityTypeEnum {
/**
* Code Value: <b>allergy</b>
*
* Allergic Reaction.
*/
ALLERGY("allergy", "http://hl7.org/fhir/sensitivitytype"),
/**
* Code Value: <b>intolerance</b>
*
* Non-Allergic Reaction.
*/
INTOLERANCE("intolerance", "http://hl7.org/fhir/sensitivitytype"),
/**
* Code Value: <b>unknown</b>
*
* Unknown type.
*/
UNKNOWN("unknown", "http://hl7.org/fhir/sensitivitytype"),
;
/**
* Identifier for this Value Set:
* http://hl7.org/fhir/vs/sensitivitytype
*/
public static final String VALUESET_IDENTIFIER = "http://hl7.org/fhir/vs/sensitivitytype";
/**
* Name for this Value Set:
* SensitivityType
*/
public static final String VALUESET_NAME = "SensitivityType";
private static Map<String, SensitivityTypeEnum> CODE_TO_ENUM = new HashMap<String, SensitivityTypeEnum>();
private static Map<String, Map<String, SensitivityTypeEnum>> SYSTEM_TO_CODE_TO_ENUM = new HashMap<String, Map<String, SensitivityTypeEnum>>();
private final String myCode;
private final String mySystem;
static {
for (SensitivityTypeEnum next : SensitivityTypeEnum.values()) {
CODE_TO_ENUM.put(next.getCode(), next);
if (!SYSTEM_TO_CODE_TO_ENUM.containsKey(next.getSystem())) {
SYSTEM_TO_CODE_TO_ENUM.put(next.getSystem(), new HashMap<String, SensitivityTypeEnum>());
}
SYSTEM_TO_CODE_TO_ENUM.get(next.getSystem()).put(next.getCode(), next);
}
}
/**
* Returns the code associated with this enumerated value
*/
public String getCode() {
return myCode;
}
/**
* Returns the code system associated with this enumerated value
*/
public String getSystem() {
return mySystem;
}
/**
* Returns the enumerated value associated with this code
*/
public SensitivityTypeEnum forCode(String theCode) {
SensitivityTypeEnum retVal = CODE_TO_ENUM.get(theCode);
return retVal;
}
/**
* Converts codes to their respective enumerated values
*/
public static final IValueSetEnumBinder<SensitivityTypeEnum> VALUESET_BINDER = new IValueSetEnumBinder<SensitivityTypeEnum>() {
@Override
public String toCodeString(SensitivityTypeEnum theEnum) {
return theEnum.getCode();
}
@Override
public String toSystemString(SensitivityTypeEnum theEnum) {
return theEnum.getSystem();
}
@Override
public SensitivityTypeEnum fromCodeString(String theCodeString) {
return CODE_TO_ENUM.get(theCodeString);
}
@Override
public SensitivityTypeEnum fromCodeString(String theCodeString, String theSystemString) {
Map<String, SensitivityTypeEnum> map = SYSTEM_TO_CODE_TO_ENUM.get(theSystemString);
if (map == null) {
return null;
}
return map.get(theCodeString);
}
};
/**
* Constructor
*/
SensitivityTypeEnum(String theCode, String theSystem) {
myCode = theCode;
mySystem = theSystem;
}
}

View File

@ -1,139 +0,0 @@
package ca.uhn.fhir.model.dstu.valueset;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import ca.uhn.fhir.model.api.IValueSetEnumBinder;
public enum SupplyTypeEnum {
/**
* Display: <b>Central Supply</b><br>
* Code Value: <b>central</b>
*
* Supply is stored and requested from central supply
*/
CENTRAL_SUPPLY("central", "http://hl7.org/fhir/supply-type"),
/**
* Display: <b>Non-Stock</b><br>
* Code Value: <b>nonstock</b>
*
* Supply is not onsite and must be requested from an outside vendor using a non-stock requisition
*/
NON_STOCK("nonstock", "http://hl7.org/fhir/supply-type"),
;
/**
* Identifier for this Value Set:
* http://hl7.org/fhir/vs/supply-type
*/
public static final String VALUESET_IDENTIFIER = "http://hl7.org/fhir/vs/supply-type";
/**
* Name for this Value Set:
* Supply Type
*/
public static final String VALUESET_NAME = "Supply Type";
private static Map<String, SupplyTypeEnum> CODE_TO_ENUM = new HashMap<String, SupplyTypeEnum>();
private static Map<String, Map<String, SupplyTypeEnum>> SYSTEM_TO_CODE_TO_ENUM = new HashMap<String, Map<String, SupplyTypeEnum>>();
private final String myCode;
private final String mySystem;
static {
for (SupplyTypeEnum next : SupplyTypeEnum.values()) {
CODE_TO_ENUM.put(next.getCode(), next);
if (!SYSTEM_TO_CODE_TO_ENUM.containsKey(next.getSystem())) {
SYSTEM_TO_CODE_TO_ENUM.put(next.getSystem(), new HashMap<String, SupplyTypeEnum>());
}
SYSTEM_TO_CODE_TO_ENUM.get(next.getSystem()).put(next.getCode(), next);
}
}
/**
* Returns the code associated with this enumerated value
*/
public String getCode() {
return myCode;
}
/**
* Returns the code system associated with this enumerated value
*/
public String getSystem() {
return mySystem;
}
/**
* Returns the enumerated value associated with this code
*/
public SupplyTypeEnum forCode(String theCode) {
SupplyTypeEnum retVal = CODE_TO_ENUM.get(theCode);
return retVal;
}
/**
* Converts codes to their respective enumerated values
*/
public static final IValueSetEnumBinder<SupplyTypeEnum> VALUESET_BINDER = new IValueSetEnumBinder<SupplyTypeEnum>() {
@Override
public String toCodeString(SupplyTypeEnum theEnum) {
return theEnum.getCode();
}
@Override
public String toSystemString(SupplyTypeEnum theEnum) {
return theEnum.getSystem();
}
@Override
public SupplyTypeEnum fromCodeString(String theCodeString) {
return CODE_TO_ENUM.get(theCodeString);
}
@Override
public SupplyTypeEnum fromCodeString(String theCodeString, String theSystemString) {
Map<String, SupplyTypeEnum> map = SYSTEM_TO_CODE_TO_ENUM.get(theSystemString);
if (map == null) {
return null;
}
return map.get(theCodeString);
}
};
/**
* Constructor
*/
SupplyTypeEnum(String theCode, String theSystem) {
myCode = theCode;
mySystem = theSystem;
}
}

View File

@ -20,13 +20,15 @@ package ca.uhn.fhir.model.primitive;
* #L%
*/
import org.hl7.fhir.instance.model.api.IBaseBooleanDatatype;
import ca.uhn.fhir.model.api.BasePrimitive;
import ca.uhn.fhir.model.api.annotation.DatatypeDef;
import ca.uhn.fhir.model.api.annotation.SimpleSetter;
import ca.uhn.fhir.parser.DataFormatException;
@DatatypeDef(name = "boolean")
public class BooleanDt extends BasePrimitive<Boolean> {
public class BooleanDt extends BasePrimitive<Boolean> implements IBaseBooleanDatatype {
/**
* Constructor

View File

@ -24,12 +24,14 @@ import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;
import org.hl7.fhir.instance.model.api.IBaseDecimalDatatype;
import ca.uhn.fhir.model.api.BasePrimitive;
import ca.uhn.fhir.model.api.annotation.DatatypeDef;
import ca.uhn.fhir.model.api.annotation.SimpleSetter;
@DatatypeDef(name = "decimal")
public class DecimalDt extends BasePrimitive<BigDecimal> implements Comparable<DecimalDt> {
public class DecimalDt extends BasePrimitive<BigDecimal> implements Comparable<DecimalDt>, IBaseDecimalDatatype {
/**
* Constructor

View File

@ -29,7 +29,7 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.hl7.fhir.instance.model.IBaseResource;
import org.hl7.fhir.instance.model.Resource;
import org.hl7.fhir.instance.model.api.IAnyResource;
import ca.uhn.fhir.model.api.IPrimitiveDatatype;
import ca.uhn.fhir.model.api.IResource;
@ -51,7 +51,7 @@ import ca.uhn.fhir.util.UrlUtil;
* </p>
*/
@DatatypeDef(name = "id")
public class IdDt implements IPrimitiveDatatype<String> {
public class IdDt extends UriDt implements IPrimitiveDatatype<String> {
private String myBaseUrl;
private boolean myHaveComponentParts;
@ -113,6 +113,18 @@ public class IdDt implements IPrimitiveDatatype<String> {
this(theResourceType, toPlainStringWithNpeThrowIfNeeded(theIdPart));
}
/**
* Constructor
*
* @param theResourceType
* The resource type (e.g. "Patient")
* @param theIdPart
* The ID (e.g. "123")
*/
public IdDt(String theResourceType, Long theIdPart) {
this(theResourceType, toPlainStringWithNpeThrowIfNeeded(theIdPart));
}
/**
* Constructor
*
@ -515,6 +527,13 @@ public class IdDt implements IPrimitiveDatatype<String> {
return theIdPart.toPlainString();
}
private static String toPlainStringWithNpeThrowIfNeeded(Long theIdPart) {
if (theIdPart == null) {
throw new NullPointerException("Long ID can not be null");
}
return theIdPart.toString();
}
@Override
public boolean isEmpty() {
return isBlank(getValue());
@ -525,8 +544,8 @@ public class IdDt implements IPrimitiveDatatype<String> {
throw new NullPointerException("theResource can not be null");
} else if (theResouce instanceof IResource) {
((IResource) theResouce).setId(new IdDt(getValue()));
} else if (theResouce instanceof Resource) {
((Resource) theResouce).setId(getIdPart());
} else if (theResouce instanceof IAnyResource) {
((IAnyResource) theResouce).setId(getIdPart());
} else {
throw new IllegalArgumentException("Unknown resource class type, does not implement IResource or extend Resource");
}
@ -540,7 +559,7 @@ public class IdDt implements IPrimitiveDatatype<String> {
throw new NullPointerException("theResource can not be null");
} else if (theResouce instanceof IResource) {
return ((IResource) theResouce).getId();
} else if (theResouce instanceof Resource) {
} else if (theResouce instanceof IAnyResource) {
// TODO: implement
throw new UnsupportedOperationException();
} else {

View File

@ -20,13 +20,15 @@ package ca.uhn.fhir.model.primitive;
* #L%
*/
import org.hl7.fhir.instance.model.api.IBaseIntegerDatatype;
import ca.uhn.fhir.model.api.BasePrimitive;
import ca.uhn.fhir.model.api.annotation.DatatypeDef;
import ca.uhn.fhir.model.api.annotation.SimpleSetter;
import ca.uhn.fhir.parser.DataFormatException;
@DatatypeDef(name = "integer")
public class IntegerDt extends BasePrimitive<Integer> {
public class IntegerDt extends BasePrimitive<Integer> implements IBaseIntegerDatatype {
/**
* Constructor

View File

@ -28,10 +28,9 @@ import org.apache.commons.lang3.StringUtils;
import ca.uhn.fhir.model.api.BasePrimitive;
import ca.uhn.fhir.model.api.annotation.DatatypeDef;
import ca.uhn.fhir.model.api.annotation.SimpleSetter;
import ca.uhn.fhir.parser.DataFormatException;
@DatatypeDef(name = "uri")
public class UriDt extends BasePrimitive<URI> {
public class UriDt extends BasePrimitive<String> {
/**
* Creates a new UriDt instance which uses the given OID as the content (and prepends "urn:oid:" to the OID string
@ -67,8 +66,8 @@ public class UriDt extends BasePrimitive<URI> {
}
@Override
protected String encode(URI theValue) {
return getValue().toASCIIString();
protected String encode(String theValue) {
return theValue;
}
@Override
@ -88,8 +87,8 @@ public class UriDt extends BasePrimitive<URI> {
return false;
}
URI normalize = normalize(getValue());
URI normalize2 = normalize(other.getValue());
String normalize = normalize(getValue());
String normalize2 = normalize(other.getValue());
return normalize.equals(normalize2);
}
@ -107,17 +106,23 @@ public class UriDt extends BasePrimitive<URI> {
final int prime = 31;
int result = 1;
URI normalize = normalize(getValue());
String normalize = normalize(getValue());
result = prime * result + ((normalize == null) ? 0 : normalize.hashCode());
return result;
}
private URI normalize(URI theValue) {
private String normalize(String theValue) {
if (theValue == null) {
return null;
}
URI retVal = (theValue.normalize());
URI retVal;
try {
retVal = new URI(theValue).normalize();
} catch (URISyntaxException e1) {
ourLog.debug("Failed to normalize URL '{}', message was: {}", theValue, e1.toString());
return theValue;
}
String urlString = retVal.toString();
if (urlString.endsWith("/") && urlString.length() > 1) {
try {
@ -126,16 +131,12 @@ public class UriDt extends BasePrimitive<URI> {
ourLog.debug("Failed to normalize URL '{}', message was: {}", urlString, e.toString());
}
}
return retVal;
return retVal.toASCIIString();
}
@Override
protected URI parse(String theValue) {
try {
return new URI(theValue);
} catch (URISyntaxException e) {
throw new DataFormatException("Unable to parse URI value", e);
}
protected String parse(String theValue) {
return theValue;
}
}

View File

@ -20,7 +20,7 @@ package ca.uhn.fhir.narrative;
* #L%
*/
import static org.apache.commons.lang3.StringUtils.*;
import static org.apache.commons.lang3.StringUtils.isBlank;
import java.io.File;
import java.io.FileInputStream;
@ -63,9 +63,7 @@ import org.thymeleaf.templateresolver.TemplateResolver;
import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.api.IDatatype;
import ca.uhn.fhir.model.dstu.composite.NarrativeDt;
import ca.uhn.fhir.model.dstu.valueset.NarrativeStatusEnum;
import ca.uhn.fhir.model.primitive.XhtmlDt;
import ca.uhn.fhir.model.base.composite.BaseNarrativeDt;
import ca.uhn.fhir.parser.DataFormatException;
public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGenerator {
@ -94,8 +92,8 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener
}
@Override
public NarrativeDt generateNarrative(IBaseResource theResource) {
return generateNarrative( null, theResource);
public void generateNarrative(IBaseResource theResource, BaseNarrativeDt<?> theNarrative) {
generateNarrative(null, theResource, theNarrative);
}
@Override
@ -110,7 +108,7 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener
}
@Override
public NarrativeDt generateNarrative(String theProfile, IBaseResource theResource) {
public void generateNarrative(String theProfile, IBaseResource theResource, BaseNarrativeDt<?> theNarrative) {
if (!myInitialized) {
initialize();
}
@ -129,7 +127,9 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener
if (name == null) {
if (myIgnoreMissingTemplates) {
ourLog.debug("No narrative template available for profile: {}", theProfile);
return new NarrativeDt(new XhtmlDt("<div>No narrative template available for resource profile: " + theProfile + "</div>"), NarrativeStatusEnum.EMPTY);
theNarrative.getDiv().setValueAsString("<div>No narrative template available for resource profile: " + theProfile + "</div>");
theNarrative.getStatus().setValueAsString("empty");
return;
} else {
throw new DataFormatException("No narrative template for class " + theResource.getClass().getCanonicalName());
}
@ -147,12 +147,15 @@ public abstract class BaseThymeleafNarrativeGenerator implements INarrativeGener
ourLog.trace("Post-whitespace cleaning: ", result);
}
XhtmlDt div = new XhtmlDt(result);
return new NarrativeDt(div, NarrativeStatusEnum.GENERATED);
theNarrative.getDiv().setValueAsString(result);
theNarrative.getStatus().setValueAsString("generated");
return;
} catch (Exception e) {
if (myIgnoreFailures) {
ourLog.error("Failed to generate narrative", e);
return new NarrativeDt(new XhtmlDt("<div>No narrative available - Error: " + e.getMessage() + "</div>"), NarrativeStatusEnum.EMPTY);
theNarrative.getDiv().setValueAsString("<div>No narrative available - Error: " + e.getMessage() + "</div>");
theNarrative.getStatus().setValueAsString("empty");
return;
} else {
throw new DataFormatException(e);
}

View File

@ -23,14 +23,14 @@ package ca.uhn.fhir.narrative;
import org.hl7.fhir.instance.model.IBaseResource;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.model.dstu.composite.NarrativeDt;
import ca.uhn.fhir.model.base.composite.BaseNarrativeDt;
import ca.uhn.fhir.parser.DataFormatException;
public interface INarrativeGenerator {
NarrativeDt generateNarrative(String theProfile, IBaseResource theResource) throws DataFormatException;
void generateNarrative(String theProfile, IBaseResource theResource, BaseNarrativeDt<?> theNarrative) throws DataFormatException;
NarrativeDt generateNarrative(IBaseResource theResource);
void generateNarrative(IBaseResource theResource, BaseNarrativeDt<?> theNarrative);
String generateTitle(IBaseResource theResource);

View File

@ -20,7 +20,7 @@ package ca.uhn.fhir.parser;
* #L%
*/
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.*;
import java.io.IOException;
import java.io.Reader;
@ -36,22 +36,27 @@ import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.hl7.fhir.instance.model.DomainResource;
import org.hl7.fhir.instance.model.IBase;
import org.hl7.fhir.instance.model.IBaseResource;
import org.hl7.fhir.instance.model.Reference;
import org.hl7.fhir.instance.model.Resource;
import org.hl7.fhir.instance.model.IPrimitiveType;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IDomainResource;
import org.hl7.fhir.instance.model.api.IReference;
import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.context.BaseRuntimeDeclaredChildDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementDefinition;
import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.RuntimeChildChoiceDefinition;
import ca.uhn.fhir.context.RuntimeResourceDefinition;
import ca.uhn.fhir.model.api.Bundle;
import ca.uhn.fhir.model.api.BundleEntry;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
import ca.uhn.fhir.model.api.TagList;
import ca.uhn.fhir.model.dstu.composite.ResourceReferenceDt;
import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt;
import ca.uhn.fhir.model.primitive.IdDt;
public abstract class BaseParser implements IParser {
@ -64,28 +69,6 @@ public abstract class BaseParser implements IParser {
myContext = theContext;
}
protected String fixContainedResourceId(String theValue) {
if (StringUtils.isNotBlank(theValue) && theValue.charAt(0) == '#') {
return theValue.substring(1);
}
return theValue;
}
protected String determineResourceBaseUrl(String bundleBaseUrl, BundleEntry theEntry) {
IResource resource = theEntry.getResource();
if (resource == null) {
return null;
}
String resourceBaseUrl = null;
if (resource.getId() != null && resource.getId().hasBaseUrl()) {
if (!resource.getId().getBaseUrl().equals(bundleBaseUrl)) {
resourceBaseUrl = resource.getId().getBaseUrl();
}
}
return resourceBaseUrl;
}
private void containResourcesForEncoding(ContainedResources theContained, IBaseResource theResource, IBaseResource theTarget) {
Set<String> allIds = new HashSet<String>();
@ -103,9 +86,9 @@ public abstract class BaseParser implements IParser {
existingIdToContainedResource.put(nextId, next);
}
}
} else if (theTarget instanceof DomainResource) {
List<Resource> containedResources = ((DomainResource) theTarget).getContained();
for (Resource next : containedResources) {
} else if (theTarget instanceof IDomainResource) {
List<? extends IAnyResource> containedResources = ((IDomainResource) theTarget).getContained();
for (IAnyResource next : containedResources) {
String nextId = next.getId();
if (StringUtils.isNotBlank(nextId)) {
allIds.add(nextId);
@ -120,8 +103,8 @@ public abstract class BaseParser implements IParser {
}
{
List<ResourceReferenceDt> allElements = myContext.newTerser().getAllPopulatedChildElementsOfType(theResource, ResourceReferenceDt.class);
for (ResourceReferenceDt next : allElements) {
List<BaseResourceReferenceDt> allElements = myContext.newTerser().getAllPopulatedChildElementsOfType(theResource, BaseResourceReferenceDt.class);
for (BaseResourceReferenceDt next : allElements) {
IResource resource = next.getResource();
if (resource != null) {
if (resource.getId().isEmpty() || resource.getId().isLocal()) {
@ -144,9 +127,9 @@ public abstract class BaseParser implements IParser {
}
{
List<Reference> allElements = myContext.newTerser().getAllPopulatedChildElementsOfType(theResource, Reference.class);
for (Reference next : allElements) {
Resource resource = next.getResource();
List<IReference> allElements = myContext.newTerser().getAllPopulatedChildElementsOfType(theResource, IReference.class);
for (IReference next : allElements) {
IAnyResource resource = next.getResource();
if (resource != null) {
if (resource.getIdElement().isEmpty() || resource.getId().startsWith("#")) {
theContained.addContained(resource);
@ -175,6 +158,40 @@ public abstract class BaseParser implements IParser {
myContainedResources = contained;
}
protected String determineReferenceText(BaseResourceReferenceDt theRef) {
String reference = theRef.getReference().getValue();
if (isBlank(reference)) {
if (theRef.getResource() != null) {
IdDt containedId = getContainedResources().getResourceId(theRef.getResource());
if (containedId != null && !containedId.isEmpty()) {
if (containedId.isLocal()) {
reference = containedId.getValue();
} else {
reference = "#" + containedId.getValue();
}
} else if (theRef.getResource().getId() != null && theRef.getResource().getId().hasIdPart()) {
reference = theRef.getResource().getId().getValue();
}
}
}
return reference;
}
protected String determineResourceBaseUrl(String bundleBaseUrl, BundleEntry theEntry) {
IResource resource = theEntry.getResource();
if (resource == null) {
return null;
}
String resourceBaseUrl = null;
if (resource.getId() != null && resource.getId().hasBaseUrl()) {
if (!resource.getId().getBaseUrl().equals(bundleBaseUrl)) {
resourceBaseUrl = resource.getId().getBaseUrl();
}
}
return resourceBaseUrl;
}
@Override
public String encodeBundleToString(Bundle theBundle) throws DataFormatException {
if (theBundle == null) {
@ -212,6 +229,13 @@ public abstract class BaseParser implements IParser {
return stringWriter.toString();
}
protected String fixContainedResourceId(String theValue) {
if (StringUtils.isNotBlank(theValue) && theValue.charAt(0) == '#') {
return theValue.substring(1);
}
return theValue;
}
ContainedResources getContainedResources() {
return myContainedResources;
}
@ -247,6 +271,57 @@ public abstract class BaseParser implements IParser {
return parseResource(null, theReader);
}
protected abstract <T extends IBaseResource> T doParseResource(Class<T> theResourceType, Reader theReader) throws DataFormatException;
public <T extends IBaseResource> T parseResource(Class<T> theResourceType, Reader theReader) throws DataFormatException {
T retVal = doParseResource(theResourceType, theReader);
RuntimeResourceDefinition def = myContext.getResourceDefinition(retVal);
if ("Bundle".equals(def.getName())) {
List<IBase> base = def.getChildByName("base").getAccessor().getValues(retVal);
if (base != null && base.size() > 0) {
IPrimitiveType<?> baseType = (IPrimitiveType<?>) base.get(0);
IResource res = ((IResource)retVal);
res.setId(new IdDt(baseType.getValueAsString(), def.getName(), res.getId().getIdPart(), res.getId().getVersionIdPart()));
}
BaseRuntimeChildDefinition entryChild = def.getChildByName("entry");
BaseRuntimeElementCompositeDefinition<?> entryDef = (BaseRuntimeElementCompositeDefinition<?>) entryChild.getChildByName("entry");
List<IBase> entries = entryChild.getAccessor().getValues(retVal);
if (entries != null) {
for (IBase nextEntry : entries) {
List<IBase> entryBase = entryDef.getChildByName("base").getAccessor().getValues(nextEntry);
if (entryBase == null || entryBase.isEmpty()) {
entryBase = base;
}
if (entryBase != null && entryBase.size() > 0) {
IPrimitiveType<?> baseType = (IPrimitiveType<?>) entryBase.get(0);
List<IBase> entryResources = entryDef.getChildByName("resource").getAccessor().getValues(nextEntry);
if (entryResources != null && entryResources.size() > 0) {
IResource res = (IResource) entryResources.get(0);
RuntimeResourceDefinition resDef = myContext.getResourceDefinition(res);
String versionIdPart = res.getId().getVersionIdPart();
if (isBlank(versionIdPart)) {
versionIdPart = ResourceMetadataKeyEnum.VERSION.get(res);
}
res.setId(new IdDt(baseType.getValueAsString(), resDef.getName(), res.getId().getIdPart(), versionIdPart));
}
}
}
}
}
return retVal;
}
@Override
public IResource parseResource(String theMessageString) throws ConfigurationException, DataFormatException {
return parseResource(null, theMessageString);
@ -279,30 +354,11 @@ public abstract class BaseParser implements IParser {
throw new DataFormatException(nextChild + " has no child of type " + theType);
}
protected String determineReferenceText(ResourceReferenceDt theRef) {
String reference = theRef.getReference().getValue();
if (isBlank(reference)) {
if (theRef.getResource() != null) {
IdDt containedId = getContainedResources().getResourceId(theRef.getResource());
if (containedId != null && !containedId.isEmpty()) {
if (containedId.isLocal()) {
reference = containedId.getValue();
} else {
reference = "#" + containedId.getValue();
}
} else if (theRef.getResource().getId() != null && theRef.getResource().getId().hasIdPart()) {
reference = theRef.getResource().getId().getValue();
}
}
}
return reference;
}
static class ContainedResources {
private long myNextContainedId = 1;
private IdentityHashMap<IBaseResource, IdDt> myResourceToId = new IdentityHashMap<IBaseResource, IdDt>();
private List<IBaseResource> myResources = new ArrayList<IBaseResource>();
private IdentityHashMap<IBaseResource, IdDt> myResourceToId = new IdentityHashMap<IBaseResource, IdDt>();
public void addContained(IBaseResource theResource) {
if (myResourceToId.containsKey(theResource)) {
@ -312,8 +368,8 @@ public abstract class BaseParser implements IParser {
IdDt newId;
if (theResource instanceof IResource && ((IResource) theResource).getId().isLocal()) {
newId = ((IResource) theResource).getId();
} else if (theResource instanceof Resource && ((Resource)theResource).getId() != null && ((Resource)theResource).getId().startsWith("#")) {
newId = new IdDt(((Resource)theResource).getId());
} else if (theResource instanceof IAnyResource && ((IAnyResource)theResource).getId() != null && ((IAnyResource)theResource).getId().startsWith("#")) {
newId = new IdDt(((IAnyResource)theResource).getId());
} else {
// TODO: make this configurable between the two below (and something else?)
// newId = new IdDt(UUID.randomUUID().toString());

View File

@ -20,11 +20,12 @@ package ca.uhn.fhir.parser;
* #L%
*/
import static org.apache.commons.lang3.StringUtils.*;
import static org.apache.commons.lang3.StringUtils.defaultString;
import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collections;
@ -52,7 +53,15 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.hl7.fhir.instance.model.IBase;
import org.hl7.fhir.instance.model.IBaseResource;
import org.hl7.fhir.instance.model.Resource;
import org.hl7.fhir.instance.model.IPrimitiveType;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBaseBooleanDatatype;
import org.hl7.fhir.instance.model.api.IBaseDatatype;
import org.hl7.fhir.instance.model.api.IBaseDecimalDatatype;
import org.hl7.fhir.instance.model.api.IBaseExtension;
import org.hl7.fhir.instance.model.api.IBaseHasExtensions;
import org.hl7.fhir.instance.model.api.IBaseHasModifierExtensions;
import org.hl7.fhir.instance.model.api.IBaseIntegerDatatype;
import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition;
@ -78,11 +87,10 @@ import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
import ca.uhn.fhir.model.api.Tag;
import ca.uhn.fhir.model.api.TagList;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.dstu.composite.ContainedDt;
import ca.uhn.fhir.model.dstu.composite.NarrativeDt;
import ca.uhn.fhir.model.dstu.composite.ResourceReferenceDt;
import ca.uhn.fhir.model.dstu.resource.Binary;
import ca.uhn.fhir.model.primitive.BooleanDt;
import ca.uhn.fhir.model.base.composite.BaseContainedDt;
import ca.uhn.fhir.model.base.composite.BaseNarrativeDt;
import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt;
import ca.uhn.fhir.model.base.resource.BaseBinary;
import ca.uhn.fhir.model.primitive.DecimalDt;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.IntegerDt;
@ -124,7 +132,7 @@ public class JsonParser extends BaseParser implements IParser {
myContext = theContext;
}
private void addToHeldExtensions(int valueIdx, List<ExtensionDt> ext, ArrayList<ArrayList<HeldExtension>> list) {
private void addToHeldExtensions(int valueIdx, List<? extends IBaseExtension<?>> ext, ArrayList<ArrayList<HeldExtension>> list, boolean theIsModifier) {
if (ext.size() > 0) {
list.ensureCapacity(valueIdx);
while (list.size() <= valueIdx) {
@ -133,8 +141,8 @@ public class JsonParser extends BaseParser implements IParser {
if (list.get(valueIdx) == null) {
list.set(valueIdx, new ArrayList<JsonParser.HeldExtension>());
}
for (ExtensionDt next : ext) {
list.get(valueIdx).add(new HeldExtension(next));
for (IBaseExtension<?> next : ext) {
list.get(valueIdx).add(new HeldExtension(next, theIsModifier));
}
}
}
@ -274,6 +282,13 @@ public class JsonParser extends BaseParser implements IParser {
writeOptionalTagWithTextNode(theEventWriter, "base", determineResourceBaseUrl(theBundle.getLinkBase().getValue(), nextEntry));
boolean deleted = nextEntry.getDeletedAt() != null && nextEntry.getDeletedAt().isEmpty() == false;
IResource resource = nextEntry.getResource();
if (resource != null && !resource.isEmpty() && !deleted) {
RuntimeResourceDefinition resDef = myContext.getResourceDefinition(resource);
encodeResourceToJsonStreamWriter(resDef, resource, theEventWriter, "resource", false);
}
if (nextEntry.getSearchMode().isEmpty() == false || nextEntry.getScore().isEmpty() == false) {
theEventWriter.writeStartObject("search");
writeOptionalTagWithTextNode(theEventWriter, "mode", nextEntry.getSearchMode().getValueAsString());
@ -285,11 +300,10 @@ public class JsonParser extends BaseParser implements IParser {
if (nextEntry.getTransactionOperation().isEmpty() == false || nextEntry.getLinkSearch().isEmpty() == false) {
theEventWriter.writeStartObject("transaction");
writeOptionalTagWithTextNode(theEventWriter, "operation", nextEntry.getTransactionOperation().getValue());
writeOptionalTagWithTextNode(theEventWriter, "match", nextEntry.getLinkSearch().getValue());
writeOptionalTagWithTextNode(theEventWriter, "url", nextEntry.getLinkSearch().getValue());
theEventWriter.writeEnd();
}
boolean deleted = nextEntry.getDeletedAt() != null && nextEntry.getDeletedAt().isEmpty() == false;
if (deleted) {
theEventWriter.writeStartObject("deleted");
if (nextEntry.getResource() != null) {
@ -316,12 +330,6 @@ public class JsonParser extends BaseParser implements IParser {
//
// writeAuthor(nextEntry, theEventWriter);
IResource resource = nextEntry.getResource();
if (resource != null && !resource.isEmpty() && !deleted) {
RuntimeResourceDefinition resDef = myContext.getResourceDefinition(resource);
encodeResourceToJsonStreamWriter(resDef, resource, theEventWriter, "resource", false);
}
if (nextEntry.getSummary().isEmpty() == false) {
theEventWriter.write("summary", nextEntry.getSummary().getValueAsString());
}
@ -338,28 +346,28 @@ public class JsonParser extends BaseParser implements IParser {
switch (theChildDef.getChildType()) {
case PRIMITIVE_DATATYPE: {
IPrimitiveDatatype<?> value = (IPrimitiveDatatype<?>) theNextValue;
IPrimitiveType<?> value = (IPrimitiveType<?>) theNextValue;
if (isBlank(value.getValueAsString())) {
break;
}
if (value instanceof IntegerDt) {
if (value instanceof IBaseIntegerDatatype) {
if (theChildName != null) {
theWriter.write(theChildName, ((IntegerDt) value).getValue());
theWriter.write(theChildName, ((IBaseIntegerDatatype) value).getValue());
} else {
theWriter.write(((IntegerDt) value).getValue());
theWriter.write(((IBaseIntegerDatatype) value).getValue());
}
} else if (value instanceof DecimalDt) {
} else if (value instanceof IBaseDecimalDatatype) {
if (theChildName != null) {
theWriter.write(theChildName, ((DecimalDt) value).getValue());
theWriter.write(theChildName, ((IBaseDecimalDatatype) value).getValue());
} else {
theWriter.write(((DecimalDt) value).getValue());
theWriter.write(((IBaseDecimalDatatype) value).getValue());
}
} else if (value instanceof BooleanDt) {
} else if (value instanceof IBaseBooleanDatatype) {
if (theChildName != null) {
theWriter.write(theChildName, ((BooleanDt) value).getValue());
theWriter.write(theChildName, ((IBaseBooleanDatatype) value).getValue());
} else {
theWriter.write(((BooleanDt) value).getValue());
theWriter.write(((IBaseBooleanDatatype) value).getValue());
}
} else {
String valueStr = value.getValueAsString();
@ -387,7 +395,7 @@ public class JsonParser extends BaseParser implements IParser {
break;
}
case RESOURCE_REF: {
ResourceReferenceDt referenceDt = (ResourceReferenceDt) theNextValue;
BaseResourceReferenceDt referenceDt = (BaseResourceReferenceDt) theNextValue;
if (theChildName != null) {
theWriter.writeStartObject(theChildName);
} else {
@ -399,16 +407,15 @@ public class JsonParser extends BaseParser implements IParser {
if (StringUtils.isNotBlank(reference)) {
theWriter.write(XmlParser.RESREF_REFERENCE, reference);
}
if (referenceDt.getDisplay().isEmpty() == false) {
theWriter.write(XmlParser.RESREF_DISPLAY, referenceDt.getDisplay().getValueAsString());
if (referenceDt.getDisplayElement().isEmpty() == false) {
theWriter.write(XmlParser.RESREF_DISPLAY, referenceDt.getDisplayElement().getValueAsString());
}
theWriter.writeEnd();
break;
}
case CONTAINED_RESOURCES: {
/*
* Disabled per #103
* ContainedDt value = (ContainedDt) theNextValue; for (IResource next : value.getContainedResources()) { if (getContainedResources().getResourceId(next) != null) {
* Disabled per #103 ContainedDt value = (ContainedDt) theNextValue; for (IResource next : value.getContainedResources()) { if (getContainedResources().getResourceId(next) != null) {
* continue; } encodeResourceToJsonStreamWriter(theResDef, next, theWriter, null, true, fixContainedResourceId(next.getId().getValue())); }
*/
List<IBaseResource> containedResources = getContainedResources().getContainedResources();
@ -441,6 +448,11 @@ public class JsonParser extends BaseParser implements IParser {
}
break;
}
case RESOURCE:
IBaseResource resource = (IBaseResource) theNextValue;
RuntimeResourceDefinition def = myContext.getResourceDefinition(resource);
encodeResourceToJsonStreamWriter(def, resource, theWriter, theChildName, true);
break;
case UNDECL_EXT:
default:
throw new IllegalStateException("Should not have this state here: " + theChildDef.getChildType().name());
@ -451,11 +463,16 @@ public class JsonParser extends BaseParser implements IParser {
private void encodeCompositeElementChildrenToStreamWriter(RuntimeResourceDefinition theResDef, IBaseResource theResource, IBase theNextValue, JsonGenerator theEventWriter,
List<? extends BaseRuntimeChildDefinition> theChildren, boolean theIsSubElementWithinResource) throws IOException {
for (BaseRuntimeChildDefinition nextChild : theChildren) {
if (nextChild.getElementName().equals("extension") || nextChild.getElementName().equals("modifierExtension")) {
continue;
}
if (nextChild instanceof RuntimeChildNarrativeDefinition) {
INarrativeGenerator gen = myContext.getNarrativeGenerator();
if (gen != null) {
NarrativeDt narr = gen.generateNarrative(theResDef.getResourceProfile(), theResource);
BaseNarrativeDt<?> narr = ((IResource) theResource).getText();
gen.generateNarrative(theResDef.getResourceProfile(), theResource, narr);
if (narr != null) {
RuntimeChildNarrativeDefinition child = (RuntimeChildNarrativeDefinition) nextChild;
String childName = nextChild.getChildNameByDatatype(child.getDatatype());
@ -480,7 +497,7 @@ public class JsonParser extends BaseParser implements IParser {
int valueIdx = 0;
for (IBase nextValue : values) {
if (nextValue == null || nextValue.isEmpty()) {
if (nextValue instanceof ContainedDt) {
if (nextValue instanceof BaseContainedDt) {
if (theIsSubElementWithinResource || getContainedResources().isEmpty()) {
continue;
}
@ -530,12 +547,25 @@ public class JsonParser extends BaseParser implements IParser {
encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, nextValue, childDef, null, theIsSubElementWithinResource);
}
if (nextValue instanceof ISupportsUndeclaredExtensions && primitive) {
List<ExtensionDt> ext = ((ISupportsUndeclaredExtensions) nextValue).getUndeclaredExtensions();
addToHeldExtensions(valueIdx, ext, extensions);
if (primitive) {
if (nextValue instanceof ISupportsUndeclaredExtensions) {
List<ExtensionDt> ext = ((ISupportsUndeclaredExtensions) nextValue).getUndeclaredExtensions();
addToHeldExtensions(valueIdx, ext, extensions,false);
ext = ((ISupportsUndeclaredExtensions) nextValue).getUndeclaredModifierExtensions();
addToHeldExtensions(valueIdx, ext, modifierExtensions);
ext = ((ISupportsUndeclaredExtensions) nextValue).getUndeclaredModifierExtensions();
addToHeldExtensions(valueIdx, ext, modifierExtensions,true);
}else {
if (nextValue instanceof IBaseHasExtensions) {
IBaseHasExtensions element = (IBaseHasExtensions) nextValue;
List<? extends IBaseExtension<?>> ext = element.getExtension();
addToHeldExtensions(valueIdx, ext, extensions, false);
}
if (nextValue instanceof IBaseHasModifierExtensions) {
IBaseHasModifierExtensions element = (IBaseHasModifierExtensions) nextValue;
List<? extends IBaseExtension<?>> ext = element.getModifierExtension();
addToHeldExtensions(valueIdx, ext, extensions, true);
}
}
}
}
@ -607,8 +637,8 @@ public class JsonParser extends BaseParser implements IParser {
resourceId = res.getId().getIdPart();
}
}
} else if (theResource instanceof Resource) {
Resource res = (Resource) theResource;
} else if (theResource instanceof IAnyResource) {
IAnyResource res = (IAnyResource) theResource;
if (theIsSubElementWithinResource && StringUtils.isNotBlank(res.getId())) {
resourceId = res.getId();
}
@ -646,13 +676,14 @@ public class JsonParser extends BaseParser implements IParser {
}
}
if (theResource instanceof Binary) {
Binary bin = (Binary) theResource;
if (theResource instanceof BaseBinary) {
BaseBinary bin = (BaseBinary) theResource;
theEventWriter.write("contentType", bin.getContentType());
theEventWriter.write("content", bin.getContentAsBase64());
} else {
encodeCompositeElementToStreamWriter(theResDef, theResource, theResource, theEventWriter, resDef, theIsSubElementWithinResource);
}
theEventWriter.writeEnd();
}
@ -740,22 +771,44 @@ public class JsonParser extends BaseParser implements IParser {
}
}
private void extractUndeclaredExtensions(IBase theResource, List<HeldExtension> extensions, List<HeldExtension> modifierExtensions) {
if (theResource instanceof ISupportsUndeclaredExtensions) {
List<ExtensionDt> ext = ((ISupportsUndeclaredExtensions) theResource).getUndeclaredExtensions();
private void extractUndeclaredExtensions(IBase theElement, List<HeldExtension> extensions, List<HeldExtension> modifierExtensions) {
if (theElement instanceof ISupportsUndeclaredExtensions) {
ISupportsUndeclaredExtensions element = (ISupportsUndeclaredExtensions) theElement;
List<ExtensionDt> ext = element.getUndeclaredExtensions();
for (ExtensionDt next : ext) {
if (next == null || next.isEmpty()) {
continue;
}
extensions.add(new HeldExtension(next));
extensions.add(new HeldExtension(next, false));
}
ext = ((ISupportsUndeclaredExtensions) theResource).getUndeclaredModifierExtensions();
ext = element.getUndeclaredModifierExtensions();
for (ExtensionDt next : ext) {
if (next == null || next.isEmpty()) {
continue;
}
modifierExtensions.add(new HeldExtension(next));
modifierExtensions.add(new HeldExtension(next, true));
}
} else {
if (theElement instanceof IBaseHasExtensions) {
IBaseHasExtensions element = (IBaseHasExtensions) theElement;
List<? extends IBaseExtension<?>> ext = element.getExtension();
for (IBaseExtension<?> next : ext) {
if (next == null || next.isEmpty()) {
continue;
}
extensions.add(new HeldExtension(next, false));
}
}
if (theElement instanceof IBaseHasModifierExtensions) {
IBaseHasModifierExtensions element = (IBaseHasModifierExtensions) theElement;
List<? extends IBaseExtension<?>> ext = element.getModifierExtension();
for (IBaseExtension<?> next : ext) {
if (next == null || next.isEmpty()) {
continue;
}
modifierExtensions.add(new HeldExtension(next, true));
}
}
}
}
@ -777,16 +830,15 @@ public class JsonParser extends BaseParser implements IParser {
return;
}
boolean newerThanDstu1 = myContext.getVersion().getVersion().isNewerThan(FhirVersionEnum.DSTU1);
JsonObject alternate = (JsonObject) theAlternateVal;
for (Entry<String, JsonValue> nextEntry : alternate.entrySet()) {
String nextKey = nextEntry.getKey();
JsonValue nextVal = nextEntry.getValue();
if (!newerThanDstu1 && "extension".equals(nextKey)) {
if ("extension".equals(nextKey)) {
boolean isModifier = false;
JsonArray array = (JsonArray) nextEntry.getValue();
parseExtension(theState, array, isModifier);
} else if (!newerThanDstu1 && "modifierExtension".equals(nextKey)) {
} else if ("modifierExtension".equals(nextKey)) {
boolean isModifier = true;
JsonArray array = (JsonArray) nextEntry.getValue();
parseExtension(theState, array, isModifier);
@ -800,12 +852,6 @@ public class JsonParser extends BaseParser implements IParser {
default:
break;
}
} else if (newerThanDstu1) {
if (nextKey.indexOf(':') > -1 && newerThanDstu1) {
JsonArray array = (JsonArray) nextEntry.getValue();
parseExtensionInDstu2Style(false, theState, null, nextKey, array);
continue;
}
}
}
}
@ -924,7 +970,6 @@ public class JsonParser extends BaseParser implements IParser {
private void parseChildren(JsonObject theObject, ParserState<?> theState) {
String elementId = null;
boolean newerThanDstu1 = myContext.getVersion().getVersion().isNewerThan(FhirVersionEnum.DSTU1);
for (String nextName : theObject.keySet()) {
if ("resourceType".equals(nextName)) {
continue;
@ -937,29 +982,16 @@ public class JsonParser extends BaseParser implements IParser {
// _id is incorrect, but some early examples in the FHIR spec used it
elementId = theObject.getString(nextName);
continue;
} else if (!newerThanDstu1 && "extension".equals(nextName)) {
} else if ("extension".equals(nextName)) {
JsonArray array = theObject.getJsonArray(nextName);
parseExtension(theState, array, false);
continue;
} else if (!newerThanDstu1 && "modifierExtension".equals(nextName)) {
} else if ("modifierExtension".equals(nextName)) {
JsonArray array = theObject.getJsonArray(nextName);
parseExtension(theState, array, true);
continue;
} else if (newerThanDstu1 && "modifier".equals(nextName)) {
JsonObject obj = theObject.getJsonObject(nextName);
for (String nextUrl : obj.keySet()) {
JsonArray array = obj.getJsonArray(nextUrl);
parseExtensionInDstu2Style(true, theState, null, nextUrl, array);
}
continue;
} else if (nextName.charAt(0) == '_') {
continue;
} else {
if (newerThanDstu1 && nextName.indexOf(':') > -1) {
JsonArray array = theObject.getJsonArray(nextName);
parseExtensionInDstu2Style(false, theState, null, nextName, array);
continue;
}
}
JsonValue nextVal = theObject.get(nextName);
@ -1086,7 +1118,7 @@ public class JsonParser extends BaseParser implements IParser {
}
@Override
public <T extends IBaseResource> T parseResource(Class<T> theResourceType, Reader theReader) {
public <T extends IBaseResource> T doParseResource(Class<T> theResourceType, Reader theReader) {
JsonReader reader = Json.createReader(theReader);
JsonObject object = reader.readObject();
@ -1101,7 +1133,7 @@ public class JsonParser extends BaseParser implements IParser {
def = myContext.getResourceDefinition(resourceType);
}
ParserState<? extends IBaseResource> state = (ParserState<? extends IBaseResource>) ParserState.getPreResourceInstance(def.getImplementingClass(), myContext, true);
ParserState<? extends IBaseResource> state = ParserState.getPreResourceInstance(def.getImplementingClass(), myContext, true);
state.enteringNewElement(null, def.getName());
parseChildren(object, state);
@ -1114,11 +1146,6 @@ public class JsonParser extends BaseParser implements IParser {
return retVal;
}
@Override
public <T extends IBaseResource> T parseResource(Class<T> theResourceType, String theMessageString) {
return parseResource(theResourceType, new StringReader(theMessageString));
}
@Override
public TagList parseTagList(Reader theReader) {
JsonReader reader = Json.createReader(theReader);
@ -1204,42 +1231,18 @@ public class JsonParser extends BaseParser implements IParser {
private void writeExtensionsAsDirectChild(IBaseResource theResource, JsonGenerator theEventWriter, RuntimeResourceDefinition resDef, List<HeldExtension> extensions,
List<HeldExtension> modifierExtensions, String theParentExtensionUrl) throws IOException {
if (extensions.isEmpty() == false) {
if (myContext.getVersion().getVersion().isNewerThan(FhirVersionEnum.DSTU1)) {
Collections.sort(extensions);
String currentlyWritingExtensionUrl = null;
for (HeldExtension next : extensions) {
currentlyWritingExtensionUrl = next.writeExtensionInDstu2Format(resDef, theResource, theEventWriter, currentlyWritingExtensionUrl, theParentExtensionUrl);
}
if (currentlyWritingExtensionUrl != null) {
theEventWriter.writeEnd();
}
} else {
theEventWriter.writeStartArray("extension");
for (HeldExtension next : extensions) {
next.write(resDef, theResource, theEventWriter);
}
theEventWriter.writeEnd();
theEventWriter.writeStartArray("extension");
for (HeldExtension next : extensions) {
next.write(resDef, theResource, theEventWriter);
}
theEventWriter.writeEnd();
}
if (modifierExtensions.isEmpty() == false) {
if (myContext.getVersion().getVersion().isNewerThan(FhirVersionEnum.DSTU1)) {
Collections.sort(modifierExtensions);
theEventWriter.writeStartObject("modifier");
String currentlyWritingExtensionUrl = null;
for (HeldExtension next : modifierExtensions) {
currentlyWritingExtensionUrl = next.writeExtensionInDstu2Format(resDef, theResource, theEventWriter, currentlyWritingExtensionUrl, theParentExtensionUrl);
}
if (currentlyWritingExtensionUrl != null) {
theEventWriter.writeEnd();
}
theEventWriter.writeEnd();
} else {
theEventWriter.writeStartArray("modifierExtension");
for (HeldExtension next : modifierExtensions) {
next.write(resDef, theResource, theEventWriter);
}
theEventWriter.writeEnd();
theEventWriter.writeStartArray("modifierExtension");
for (HeldExtension next : modifierExtensions) {
next.write(resDef, theResource, theEventWriter);
}
theEventWriter.writeEnd();
}
}
@ -1277,14 +1280,6 @@ public class JsonParser extends BaseParser implements IParser {
}
}
private void writeTagWithTextNode(JsonGenerator theEventWriter, String theElementName, String theValue) {
if (theValue != null && !theValue.isEmpty()) {
theEventWriter.write(theElementName, theValue);
} else {
theEventWriter.writeNull(theElementName);
}
}
private void writeTagWithTextNode(JsonGenerator theEventWriter, String theElementName, StringDt theStringDt) {
if (StringUtils.isNotBlank(theStringDt.getValue())) {
theEventWriter.write(theElementName, theStringDt.getValue());
@ -1297,12 +1292,14 @@ public class JsonParser extends BaseParser implements IParser {
private class HeldExtension implements Comparable<HeldExtension> {
private RuntimeChildDeclaredExtensionDefinition myDef;
private ExtensionDt myUndeclaredExtension;
private IBaseExtension<?> myUndeclaredExtension;
private IBase myValue;
private boolean myModifier;
public HeldExtension(ExtensionDt theUndeclaredExtension) {
public HeldExtension(IBaseExtension<?> theUndeclaredExtension, boolean theModifier) {
assert theUndeclaredExtension != null;
myUndeclaredExtension = theUndeclaredExtension;
myModifier = theModifier;
}
public HeldExtension(RuntimeChildDeclaredExtensionDefinition theDef, IBase theValue) {
@ -1331,66 +1328,38 @@ public class JsonParser extends BaseParser implements IParser {
}
}
public String writeExtensionInDstu2Format(RuntimeResourceDefinition theResDef, IBaseResource theResource, JsonGenerator theEventWriter, String theCurrentlyWritingExtensionUrl,
String theParentExtensionUrl) throws IOException {
if (myUndeclaredExtension != null) {
return writeUndeclaredExtInDstu2Format(theResDef, theResource, theEventWriter, myUndeclaredExtension, theCurrentlyWritingExtensionUrl, theParentExtensionUrl);
} else {
String extensionUrl = myDef.getExtensionUrl();
checkIfNewExtensionUrlArrayIsNeeded(theEventWriter, extensionUrl, theCurrentlyWritingExtensionUrl, theParentExtensionUrl);
theEventWriter.writeStartObject();
BaseRuntimeElementDefinition<?> def = myDef.getChildElementDefinitionByDatatype(myValue.getClass());
if (def.getChildType() == ChildTypeEnum.RESOURCE_BLOCK) {
extractAndWriteExtensionsAsDirectChild(myValue, theEventWriter, def, theResDef, theResource, extensionUrl);
} else {
String childName = myDef.getChildNameByDatatype(myValue.getClass());
encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, myValue, def, childName, false);
}
theEventWriter.writeEnd();
return extensionUrl;
}
}
private void checkIfNewExtensionUrlArrayIsNeeded(JsonGenerator theEventWriter, String theExtensionUrl, String theCurrentlyWritingExtensionUrl, String theParentExtensionUrl) {
if (StringUtils.equals(theCurrentlyWritingExtensionUrl, theExtensionUrl) == false) {
if (isNotBlank(theCurrentlyWritingExtensionUrl)) {
theEventWriter.writeEnd();
}
String urlToWrite = UrlUtil.constructRelativeUrl(theParentExtensionUrl, theExtensionUrl);
theEventWriter.writeStartArray(urlToWrite);
}
}
private void writeUndeclaredExtInDstu1Format(RuntimeResourceDefinition theResDef, IBaseResource theResource, JsonGenerator theEventWriter, ExtensionDt ext) throws IOException {
IElement value = ext.getValue();
String extensionUrl = ext.getUrl().getValue();
private void writeUndeclaredExtInDstu1Format(RuntimeResourceDefinition theResDef, IBaseResource theResource, JsonGenerator theEventWriter, IBaseExtension<?> ext) throws IOException {
IBaseDatatype value = ext.getValue();
String extensionUrl = ext.getUrl();
theEventWriter.writeStartObject();
theEventWriter.write("url", extensionUrl);
boolean noValue = value == null || value.isEmpty();
if (noValue && ext.getAllUndeclaredExtensions().isEmpty()) {
if (noValue && ext.getExtension().isEmpty()) {
ourLog.debug("Extension with URL[{}] has no value", extensionUrl);
} else if (noValue) {
theEventWriter.writeStartArray("extension");
if (myModifier) {
theEventWriter.writeStartArray("modifierExtension");
}else {
theEventWriter.writeStartArray("extension");
}
for (ExtensionDt next : ext.getUndeclaredExtensions()) {
writeUndeclaredExtInDstu1Format(theResDef, theResource, theEventWriter, next);
for (Object next : ext.getExtension()) {
writeUndeclaredExtInDstu1Format(theResDef, theResource, theEventWriter, (IBaseExtension<?>) next);
}
theEventWriter.writeEnd();
} else {
RuntimeChildUndeclaredExtensionDefinition extDef = myContext.getRuntimeChildUndeclaredExtensionDefinition();
String childName = extDef.getChildNameByDatatype(value.getClass());
if (childName == null) {
childName = "value" + myContext.getElementDefinition(value.getClass()).getName();
}
BaseRuntimeElementDefinition<?> childDef = myContext.getElementDefinition(value.getClass());
if (childDef == null) {
throw new ConfigurationException("Unable to encode extension, unregognized child element type: " + value.getClass().getCanonicalName());
}
BaseRuntimeElementDefinition<?> childDef = extDef.getChildElementDefinitionByDatatype(value.getClass());
encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, value, childDef, childName, true);
}
@ -1399,53 +1368,10 @@ public class JsonParser extends BaseParser implements IParser {
theEventWriter.writeEnd();
}
private String writeUndeclaredExtInDstu2Format(RuntimeResourceDefinition theResDef, IBaseResource theResource, JsonGenerator theEventWriter, ExtensionDt ext,
String theCurrentlyWritingExtensionUrl, String theParentExtensionUrl) throws IOException {
IElement value = ext.getValue();
String extensionUrl = ext.getUrl().getValue();
checkIfNewExtensionUrlArrayIsNeeded(theEventWriter, extensionUrl, theCurrentlyWritingExtensionUrl, theParentExtensionUrl);
theEventWriter.writeStartObject();
boolean noValue = value == null || value.isEmpty();
if (noValue && ext.getAllUndeclaredExtensions().isEmpty()) {
ourLog.debug("Extension with URL[{}] has no value", extensionUrl);
} else if (noValue) {
BaseRuntimeElementDefinition<?> elemDef = null;
RuntimeResourceDefinition resDef = myContext.getResourceDefinition(theResource);
extractAndWriteExtensionsAsDirectChild(ext, theEventWriter, elemDef, resDef, theResource, extensionUrl);
} else {
RuntimeChildUndeclaredExtensionDefinition extDef = myContext.getRuntimeChildUndeclaredExtensionDefinition();
String childName = extDef.getChildNameByDatatype(value.getClass());
BaseRuntimeElementDefinition<?> childDef;
if (childName == null) {
childDef = myContext.getElementDefinition(value.getClass());
if (childDef == null) {
throw new ConfigurationException("Unable to encode extension, unrecognized child element type: " + value.getClass().getCanonicalName());
} else {
childName = RuntimeChildUndeclaredExtensionDefinition.createExtensionChildName(childDef);
}
} else {
childDef = extDef.getChildElementDefinitionByDatatype(value.getClass());
}
encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, value, childDef, childName, true);
}
theEventWriter.writeEnd();
return extensionUrl;
}
@Override
public int compareTo(HeldExtension theArg0) {
String url1 = myDef != null ? myDef.getExtensionUrl() : myUndeclaredExtension.getUrlAsString();
String url2 = theArg0.myDef != null ? theArg0.myDef.getExtensionUrl() : theArg0.myUndeclaredExtension.getUrlAsString();
String url1 = myDef != null ? myDef.getExtensionUrl() : myUndeclaredExtension.getUrl();
String url2 = theArg0.myDef != null ? theArg0.myDef.getExtensionUrl() : theArg0.myUndeclaredExtension.getUrl();
url1 = defaultString(url1);
url2 = defaultString(url2);
return url1.compareTo(url2);

View File

@ -32,14 +32,23 @@ import javax.xml.stream.events.XMLEvent;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.hl7.fhir.instance.model.Element;
import org.hl7.fhir.instance.model.IBase;
import org.hl7.fhir.instance.model.IBaseResource;
import org.hl7.fhir.instance.model.ICompositeType;
import org.hl7.fhir.instance.model.IPrimitiveType;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBaseDatatype;
import org.hl7.fhir.instance.model.api.IBaseElement;
import org.hl7.fhir.instance.model.api.IBaseExtension;
import org.hl7.fhir.instance.model.api.IBaseHasExtensions;
import org.hl7.fhir.instance.model.api.IBaseHasModifierExtensions;
import org.hl7.fhir.instance.model.api.IReference;
import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.context.BaseRuntimeChildDefinition.IMutator;
import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementDefinition;
import ca.uhn.fhir.context.ConfigurationException;
import ca.uhn.fhir.context.FhirContext;
import ca.uhn.fhir.context.FhirVersionEnum;
import ca.uhn.fhir.context.RuntimeChildDeclaredExtensionDefinition;
@ -56,6 +65,8 @@ import ca.uhn.fhir.model.api.ExtensionDt;
import ca.uhn.fhir.model.api.ICompositeDatatype;
import ca.uhn.fhir.model.api.ICompositeElement;
import ca.uhn.fhir.model.api.IElement;
import ca.uhn.fhir.model.api.IExtension;
import ca.uhn.fhir.model.api.IFhirVersion;
import ca.uhn.fhir.model.api.IIdentifiableElement;
import ca.uhn.fhir.model.api.IPrimitiveDatatype;
import ca.uhn.fhir.model.api.IResource;
@ -64,10 +75,10 @@ import ca.uhn.fhir.model.api.ISupportsUndeclaredExtensions;
import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
import ca.uhn.fhir.model.api.Tag;
import ca.uhn.fhir.model.api.TagList;
import ca.uhn.fhir.model.base.composite.BaseContainedDt;
import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt;
import ca.uhn.fhir.model.base.resource.BaseBinary;
import ca.uhn.fhir.model.base.resource.ResourceMetadataMap;
import ca.uhn.fhir.model.dstu.composite.ContainedDt;
import ca.uhn.fhir.model.dstu.composite.ResourceReferenceDt;
import ca.uhn.fhir.model.dstu.resource.Binary;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.InstantDt;
import ca.uhn.fhir.model.primitive.StringDt;
@ -117,6 +128,38 @@ class ParserState<T> {
return myState.isPreResource();
}
private Object newContainedDt(IResource theTarget) {
Object newChildInstance;
try {
newChildInstance = theTarget.getStructureFhirVersionEnum().getVersionImplementation().getContainedType().newInstance();
} catch (InstantiationException e) {
throw new ConfigurationException("Failed to instantiate " + myContext.getVersion().getResourceReferenceType(), e);
} catch (IllegalAccessException e) {
throw new ConfigurationException("Failed to instantiate " + myContext.getVersion().getResourceReferenceType(), e);
}
return newChildInstance;
}
private IBase newResourceReferenceDt(IBaseResource theTarget) {
IBase newChildInstance;
try {
IFhirVersion version;
if (theTarget instanceof IResource) {
version = ((IResource) theTarget).getStructureFhirVersionEnum().getVersionImplementation();
} else {
version = FhirVersionEnum.DSTU2_HL7ORG.getVersionImplementation();
}
newChildInstance = version.getResourceReferenceType().newInstance();
} catch (InstantiationException e) {
throw new ConfigurationException("Failed to instantiate " + myContext.getVersion().getResourceReferenceType(), e);
} catch (IllegalAccessException e) {
throw new ConfigurationException("Failed to instantiate " + myContext.getVersion().getResourceReferenceType(), e);
}
return newChildInstance;
}
private void pop() {
myState = myState.myStack;
myState.wereBack();
@ -188,7 +231,19 @@ class ParserState<T> {
*/
public static <T extends IBaseResource> ParserState<T> getPreResourceInstance(Class<T> theResourceType, FhirContext theContext, boolean theJsonMode) throws DataFormatException {
ParserState<T> retVal = new ParserState<T>(theContext, theJsonMode);
retVal.push(retVal.new PreResourceState(theResourceType));
if (theResourceType == null) {
if (theContext.getVersion().getVersion() != FhirVersionEnum.DSTU2_HL7ORG) {
retVal.push(retVal.new PreResourceStateHapi(theResourceType));
} else {
retVal.push(retVal.new PreResourceStateHl7Org(theResourceType));
}
} else {
if (IResource.class.isAssignableFrom(theResourceType)) {
retVal.push(retVal.new PreResourceStateHapi(theResourceType));
} else {
retVal.push(retVal.new PreResourceStateHl7Org(theResourceType));
}
}
return retVal;
}
@ -233,10 +288,10 @@ class ParserState<T> {
private static final int STATE_TERM = 1;
private int myCatState = STATE_NONE;
private TagList myTagList;
private String myTerm;
private String myLabel;
private String myScheme;
private TagList myTagList;
private String myTerm;
public AtomCategoryState(TagList theTagList) {
super(null);
@ -435,7 +490,7 @@ class ParserState<T> {
} else if ("author".equals(theLocalPart)) {
push(new AtomAuthorState(myEntry));
} else if ("content".equals(theLocalPart)) {
push(new PreResourceState(myEntry, myResourceType));
push(new PreResourceStateHapi(myEntry, myResourceType));
} else if ("summary".equals(theLocalPart)) {
push(new XhtmlState(getPreResourceState(), myEntry.getSummary(), false));
} else if ("category".equals(theLocalPart)) {
@ -718,8 +773,8 @@ class ParserState<T> {
}
for (IResource next : resources) {
List<ResourceReferenceDt> refs = myContext.newTerser().getAllPopulatedChildElementsOfType(next, ResourceReferenceDt.class);
for (ResourceReferenceDt nextRef : refs) {
List<BaseResourceReferenceDt> refs = myContext.newTerser().getAllPopulatedChildElementsOfType(next, BaseResourceReferenceDt.class);
for (BaseResourceReferenceDt nextRef : refs) {
if (nextRef.isEmpty() == false && nextRef.getReference() != null) {
IResource target = idToResource.get(nextRef.getReference().getValue());
if (target != null) {
@ -769,11 +824,29 @@ class ParserState<T> {
ExtensionState newState = new ExtensionState(myPreResourceState, newExtension);
push(newState);
} else {
throw new DataFormatException("Type " + getCurrentElement() + " does not support undeclared extentions, and found an extension with URL: " + theUrlAttr);
if (theIsModifier == false) {
if (getCurrentElement() instanceof IBaseHasExtensions) {
IBaseExtension<?> ext = ((IBaseHasExtensions)getCurrentElement()).addExtension();
ext.setUrl(theUrlAttr);
ParserState<T>.ExtensionState newState = new ExtensionState(myPreResourceState, ext);
push(newState);
} else {
throw new DataFormatException("Type " + getCurrentElement() + " does not support undeclared extentions, and found an extension with URL: " + theUrlAttr);
}
}else {
if (getCurrentElement() instanceof IBaseHasModifierExtensions) {
IBaseExtension<?> ext = ((IBaseHasModifierExtensions)getCurrentElement()).addModifierExtension();
ext.setUrl(theUrlAttr);
ParserState<T>.ExtensionState newState = new ExtensionState(myPreResourceState, ext);
push(newState);
} else {
throw new DataFormatException("Type " + getCurrentElement() + " does not support undeclared extentions, and found an extension with URL: " + theUrlAttr);
}
}
}
}
protected Object getCurrentElement() {
protected IBase getCurrentElement() {
return null;
}
@ -816,10 +889,10 @@ class ParserState<T> {
private static final int SUBSTATE_CONTENT = 2;
private static final int SUBSTATE_CT = 1;
private String myData;
private Binary myInstance;
private BaseBinary myInstance;
private int mySubState = 0;
public BinaryResourceStateForDstu1(PreResourceState thePreResourceState, Binary theInstance) {
public BinaryResourceStateForDstu1(PreResourceState thePreResourceState, BaseBinary theInstance) {
super(thePreResourceState);
myInstance = theInstance;
}
@ -829,7 +902,7 @@ class ParserState<T> {
if ("id".equals(theName)) {
if (myInstance instanceof IIdentifiableElement) {
((IIdentifiableElement) myInstance).setElementSpecificId((theValue));
} else if (myInstance instanceof IBaseResource) {
} else {
(myInstance).setId(new IdDt(theValue));
}
} else if ("contentType".equals(theName)) {
@ -928,6 +1001,33 @@ class ParserState<T> {
}
public class BundleEntrySearchState extends BaseState {
private BundleEntry myEntry;
public BundleEntrySearchState(BundleEntry theEntry) {
super(null);
myEntry = theEntry;
}
@Override
public void endingElement() throws DataFormatException {
pop();
}
@Override
public void enteringNewElement(String theNamespaceURI, String theLocalPart) throws DataFormatException {
if ("mode".equals(theLocalPart)) {
push(new PrimitiveState(getPreResourceState(), myEntry.getSearchMode()));
} else if ("score".equals(theLocalPart)) {
push(new PrimitiveState(getPreResourceState(), myEntry.getScore()));
} else {
throw new DataFormatException("Unexpected element in Bundle.entry.search: " + theLocalPart);
}
}
}
public class BundleEntryState extends BaseState {
private BundleEntry myEntry;
@ -957,7 +1057,7 @@ class ParserState<T> {
} else if ("score".equals(theLocalPart)) {
push(new PrimitiveState(getPreResourceState(), myEntry.getScore()));
} else if ("resource".equals(theLocalPart)) {
push(new PreResourceState(myEntry, myResourceType));
push(new PreResourceStateHapi(myEntry, myResourceType));
} else if ("deleted".equals(theLocalPart)) {
push(new BundleEntryDeletedState(getPreResourceState(), myEntry));
} else {
@ -1026,34 +1126,6 @@ class ParserState<T> {
}
public class BundleEntrySearchState extends BaseState {
private BundleEntry myEntry;
public BundleEntrySearchState(BundleEntry theEntry) {
super(null);
myEntry = theEntry;
}
@Override
public void endingElement() throws DataFormatException {
pop();
}
@Override
public void enteringNewElement(String theNamespaceURI, String theLocalPart) throws DataFormatException {
if ("mode".equals(theLocalPart)) {
push(new PrimitiveState(getPreResourceState(), myEntry.getSearchMode()));
} else if ("score".equals(theLocalPart)) {
push(new PrimitiveState(getPreResourceState(), myEntry.getScore()));
} else {
throw new DataFormatException("Unexpected element in Bundle.entry.search: " + theLocalPart);
}
}
}
public class BundleEntryTransactionState extends BaseState {
private BundleEntry myEntry;
@ -1072,7 +1144,7 @@ class ParserState<T> {
public void enteringNewElement(String theNamespaceURI, String theLocalPart) throws DataFormatException {
if ("operation".equals(theLocalPart)) {
push(new PrimitiveState(getPreResourceState(), myEntry.getTransactionOperation()));
} else if ("match".equals(theLocalPart)) {
} else if ("url".equals(theLocalPart)) {
push(new PrimitiveState(getPreResourceState(), myEntry.getLinkSearch()));
} else {
throw new DataFormatException("Unexpected element in Bundle.entry.search: " + theLocalPart);
@ -1080,15 +1152,15 @@ class ParserState<T> {
}
}
private class BundleLinkState extends BaseState {
private BundleEntry myEntry;
private String myHref;
private Bundle myInstance;
private String myRel;
private boolean myInRelation = false;
private Bundle myInstance;
private boolean myInUrl = false;
private String myRel;
public BundleLinkState(Bundle theInstance) {
super(null);
@ -1174,34 +1246,6 @@ class ParserState<T> {
pop();
}
@Override
public void wereBack() {
for (BundleEntry nextEntry : myInstance.getEntries()) {
IResource nextResource = nextEntry.getResource();
String bundleBaseUrl = myInstance.getLinkBase().getValue();
String entryBaseUrl = nextEntry.getLinkBase().getValue();
String version = ResourceMetadataKeyEnum.VERSION.get(nextResource);
String resourceName = myContext.getResourceDefinition(nextResource).getName();
String bundleIdPart = nextResource.getId().getIdPart();
if (isNotBlank(bundleIdPart)) {
if (isNotBlank(entryBaseUrl)) {
nextResource.setId(new IdDt(entryBaseUrl, resourceName, bundleIdPart, version));
} else {
nextResource.setId(new IdDt(bundleBaseUrl, resourceName, bundleIdPart, version));
}
}
}
String bundleVersion = (String) myInstance.getResourceMetadata().get(ResourceMetadataKeyEnum.VERSION);
String baseUrl = myInstance.getLinkBase().getValue();
String id = myInstance.getId().getIdPart();
if (isNotBlank(id)) {
myInstance.setId(new IdDt(baseUrl, "Bundle", id, bundleVersion));
}
}
@Override
public void enteringNewElement(String theNamespaceURI, String theLocalPart) throws DataFormatException {
if ("id".equals(theLocalPart)) {
@ -1260,12 +1304,40 @@ class ParserState<T> {
return myInstance;
}
@Override
public void wereBack() {
for (BundleEntry nextEntry : myInstance.getEntries()) {
IResource nextResource = nextEntry.getResource();
String bundleBaseUrl = myInstance.getLinkBase().getValue();
String entryBaseUrl = nextEntry.getLinkBase().getValue();
String version = ResourceMetadataKeyEnum.VERSION.get(nextResource);
String resourceName = myContext.getResourceDefinition(nextResource).getName();
String bundleIdPart = nextResource.getId().getIdPart();
if (isNotBlank(bundleIdPart)) {
if (isNotBlank(entryBaseUrl)) {
nextResource.setId(new IdDt(entryBaseUrl, resourceName, bundleIdPart, version));
} else {
nextResource.setId(new IdDt(bundleBaseUrl, resourceName, bundleIdPart, version));
}
}
}
String bundleVersion = (String) myInstance.getResourceMetadata().get(ResourceMetadataKeyEnum.VERSION);
String baseUrl = myInstance.getLinkBase().getValue();
String id = myInstance.getId().getIdPart();
if (isNotBlank(id)) {
myInstance.setId(new IdDt(baseUrl, "Bundle", id, bundleVersion));
}
}
}
private class ContainedResourcesState extends PreResourceState {
private class ContainedResourcesStateHapi extends PreResourceState {
public ContainedResourcesState(PreResourceState thePreResourcesState) {
super(thePreResourcesState);
public ContainedResourcesStateHapi(PreResourceState thePreResourcesState) {
super(thePreResourcesState, ((IResource) thePreResourcesState.myInstance).getStructureFhirVersionEnum());
}
@Override
@ -1286,8 +1358,11 @@ class ParserState<T> {
}
}
IResource preResCurrentElement = (IResource) getPreResourceState().getCurrentElement();
preResCurrentElement.getContained().getContainedResources().add(res);
@SuppressWarnings("unchecked")
List<IResource> containedResources = (List<IResource>) preResCurrentElement.getContained().getContainedResources();
containedResources.add(res);
}
}
@ -1336,9 +1411,9 @@ class ParserState<T> {
return;
}
case RESOURCE_REF: {
ResourceReferenceDt newChildInstance = new ResourceReferenceDt();
IBase newChildInstance = newResourceReferenceDt(myPreResourceState.myInstance);
myDefinition.getMutator().addValue(myParentInstance, newChildInstance);
ResourceReferenceState newState = new ResourceReferenceState(getPreResourceState(), newChildInstance);
BaseState newState = createResourceReferenceState(getPreResourceState(), newChildInstance);
push(newState);
return;
}
@ -1374,6 +1449,16 @@ class ParserState<T> {
}
private BaseState createResourceReferenceState(ParserState<T>.PreResourceState thePreResourceState, IBase newChildInstance) {
BaseState newState;
if (newChildInstance instanceof IReference) {
newState = new ResourceReferenceStateHl7Org(thePreResourceState, (IReference) newChildInstance);
} else {
newState = new ResourceReferenceStateHapi(thePreResourceState, (BaseResourceReferenceDt) newChildInstance);
}
return newState;
}
private class ElementCompositeState<T2 extends IBase> extends BaseState {
private BaseRuntimeElementCompositeDefinition<?> myDefinition;
@ -1390,8 +1475,8 @@ class ParserState<T> {
if ("id".equals(theName)) {
if (myInstance instanceof IIdentifiableElement) {
((IIdentifiableElement) myInstance).setElementSpecificId((theValue));
} else if (myInstance instanceof Element) {
((Element) myInstance).setId(theValue);
} else if (myInstance instanceof IBaseElement) {
((IBaseElement) myInstance).setId(theValue);
} else if (myInstance instanceof IBaseResource) {
new IdDt(theValue).applyTo((IBaseResource) myInstance);
}
@ -1430,9 +1515,9 @@ class ParserState<T> {
switch (target.getChildType()) {
case COMPOSITE_DATATYPE: {
BaseRuntimeElementCompositeDefinition<?> compositeTarget = (BaseRuntimeElementCompositeDefinition<?>) target;
ICompositeDatatype newChildInstance = (ICompositeDatatype) compositeTarget.newInstance(child.getInstanceConstructorArguments());
ICompositeType newChildInstance = (ICompositeType) compositeTarget.newInstance(child.getInstanceConstructorArguments());
child.getMutator().addValue(myInstance, newChildInstance);
ElementCompositeState<ICompositeElement> newState = new ElementCompositeState<ICompositeElement>(getPreResourceState(), compositeTarget, newChildInstance);
ParserState<T>.ElementCompositeState<ICompositeType> newState = new ElementCompositeState<ICompositeType>(getPreResourceState(), compositeTarget, newChildInstance);
push(newState);
return;
}
@ -1446,19 +1531,17 @@ class ParserState<T> {
return;
}
case RESOURCE_REF: {
RuntimeResourceReferenceDefinition resourceRefTarget = (RuntimeResourceReferenceDefinition) target;
ResourceReferenceDt newChildInstance = new ResourceReferenceDt();
getPreResourceState().getResourceReferences().add(newChildInstance);
IBase newChildInstance = newResourceReferenceDt(getPreResourceState().myInstance);
child.getMutator().addValue(myInstance, newChildInstance);
ResourceReferenceState newState = new ResourceReferenceState(getPreResourceState(), newChildInstance);
BaseState newState = createResourceReferenceState(getPreResourceState(), newChildInstance);
push(newState);
return;
}
case RESOURCE_BLOCK: {
RuntimeResourceBlockDefinition blockTarget = (RuntimeResourceBlockDefinition) target;
IResourceBlock newBlockInstance = blockTarget.newInstance();
IBase newBlockInstance = blockTarget.newInstance();
child.getMutator().addValue(myInstance, newBlockInstance);
ElementCompositeState<ICompositeElement> newState = new ElementCompositeState<ICompositeElement>(getPreResourceState(), blockTarget, newBlockInstance);
ElementCompositeState<IBase> newState = new ElementCompositeState<IBase>(getPreResourceState(), blockTarget, newBlockInstance);
push(newState);
return;
}
@ -1471,21 +1554,24 @@ class ParserState<T> {
return;
}
case CONTAINED_RESOURCES: {
RuntimeElemContainedResources targetElem = (RuntimeElemContainedResources) target;
List<? extends IBase> values = child.getAccessor().getValues(myInstance);
ContainedDt newDt;
Object newDt;
if (values == null || values.isEmpty() || values.get(0) == null) {
newDt = targetElem.newInstance();
child.getMutator().addValue(myInstance, newDt);
newDt = newContainedDt((IResource) getPreResourceState().myInstance);
child.getMutator().addValue(myInstance, (IBase) newDt);
} else {
newDt = (ContainedDt) values.get(0);
newDt = values.get(0);
}
ContainedResourcesState state = new ContainedResourcesState(getPreResourceState());
ContainedResourcesStateHapi state = new ContainedResourcesStateHapi(getPreResourceState());
push(state);
return;
}
case RESOURCE: {
ParserState<T>.PreResourceStateHl7Org state = new PreResourceStateHl7Org(myInstance, child.getMutator(), null);
push(state);
return;
}
case UNDECL_EXT:
case RESOURCE:
case EXTENSION_DECLARED: {
// Throw an exception because this shouldn't happen here
break;
@ -1515,16 +1601,16 @@ class ParserState<T> {
private class ExtensionState extends BaseState {
private ExtensionDt myExtension;
private IBaseExtension<?> myExtension;
public ExtensionState(PreResourceState thePreResourceState, ExtensionDt theExtension) {
public ExtensionState(PreResourceState thePreResourceState, IBaseExtension<?> theExtension) {
super(thePreResourceState);
myExtension = theExtension;
}
@Override
public void endingElement() throws DataFormatException {
if (myExtension.getValue() != null && myExtension.getUndeclaredExtensions().size() > 0) {
if (myExtension.getValue() != null && myExtension.getExtension().size() > 0) {
throw new DataFormatException("Extension must not have both a value and other contained extensions");
}
pop();
@ -1542,22 +1628,22 @@ class ParserState<T> {
BaseRuntimeElementCompositeDefinition<?> compositeTarget = (BaseRuntimeElementCompositeDefinition<?>) target;
ICompositeDatatype newChildInstance = (ICompositeDatatype) compositeTarget.newInstance();
myExtension.setValue(newChildInstance);
ElementCompositeState newState = new ElementCompositeState(getPreResourceState(), compositeTarget, newChildInstance);
ElementCompositeState<IBase> newState = new ElementCompositeState<IBase>(getPreResourceState(), compositeTarget, newChildInstance);
push(newState);
return;
}
case PRIMITIVE_DATATYPE: {
RuntimePrimitiveDatatypeDefinition primitiveTarget = (RuntimePrimitiveDatatypeDefinition) target;
IPrimitiveType<?> newChildInstance = primitiveTarget.newInstance();
myExtension.setValue((IElement) newChildInstance);
myExtension.setValue(newChildInstance);
PrimitiveState newState = new PrimitiveState(getPreResourceState(), newChildInstance);
push(newState);
return;
}
case RESOURCE_REF: {
ResourceReferenceDt newChildInstance = new ResourceReferenceDt();
BaseResourceReferenceDt newChildInstance = (BaseResourceReferenceDt) newResourceReferenceDt(getPreResourceState().myInstance);
myExtension.setValue(newChildInstance);
ResourceReferenceState newState = new ResourceReferenceState(getPreResourceState(), newChildInstance);
ResourceReferenceStateHapi newState = new ResourceReferenceStateHapi(getPreResourceState(), newChildInstance);
push(newState);
return;
}
@ -1572,7 +1658,7 @@ class ParserState<T> {
}
@Override
protected IElement getCurrentElement() {
protected IBaseExtension<?> getCurrentElement() {
return myExtension;
}
@ -1595,6 +1681,8 @@ class ParserState<T> {
public void enteringNewElement(String theNamespaceURI, String theLocalPart) throws DataFormatException {
if (theLocalPart.equals("versionId")) {
push(new MetaVersionElementState(getPreResourceState(), myMap));
// } else if (theLocalPart.equals("profile")) {
//
} else if (theLocalPart.equals("lastUpdated")) {
InstantDt updated = new InstantDt();
push(new PrimitiveState(getPreResourceState(), updated));
@ -1680,53 +1768,106 @@ class ParserState<T> {
}
private class ResourceState extends ElementCompositeState<IResource>
{
private class PreResourceStateHapi extends PreResourceState {
private BundleEntry myEntry;
public ResourceState(PreResourceState thePreResourceState, BaseRuntimeElementCompositeDefinition<?> theDef, IResource theInstance) {
super(thePreResourceState, theDef, theInstance);
public PreResourceStateHapi(BundleEntry theEntry, Class<? extends IBaseResource> theResourceType) {
super(theResourceType);
myEntry = theEntry;
}
public PreResourceStateHapi(Class<? extends IBaseResource> theResourceType) {
super(theResourceType);
}
@SuppressWarnings("unchecked")
@Override
public void wereBack() {
super.wereBack();
if (myEntry == null) {
myObject = (T) getCurrentElement();
}
IResource nextResource = (IResource) getCurrentElement();
String version = ResourceMetadataKeyEnum.VERSION.get(nextResource);
String resourceName = myContext.getResourceDefinition(nextResource).getName();
String bundleIdPart = nextResource.getId().getIdPart();
if (isNotBlank(bundleIdPart)) {
// if (isNotBlank(entryBaseUrl)) {
// nextResource.setId(new IdDt(entryBaseUrl, resourceName, bundleIdPart, version));
// } else {
nextResource.setId(new IdDt(null, resourceName, bundleIdPart, version));
// }
}
}
@Override
public void enteringNewElement(String theNamespace, String theChildName) throws DataFormatException {
if ("id".equals(theChildName)) {
push(new PrimitiveState(getPreResourceState(), getCurrentElement().getId()));
} else if ("meta".equals(theChildName)) {
push(new MetaElementState(getPreResourceState(), getCurrentElement().getResourceMetadata()));
}else {
super.enteringNewElement(theNamespace, theChildName);
public void enteringNewElement(String theNamespaceURI, String theLocalPart) throws DataFormatException {
super.enteringNewElement(theNamespaceURI, theLocalPart);
if (myEntry != null) {
myEntry.setResource((IResource) getCurrentElement());
}
}
}
private class PreResourceState extends BaseState {
private Map<String, IBaseResource> myContainedResources = new HashMap<String, IBaseResource>();
private BundleEntry myEntry;
private IResource myInstance;
private List<ResourceReferenceDt> myResourceReferences = new ArrayList<ResourceReferenceDt>();
private Class<? extends IBaseResource> myResourceType;
private class PreResourceStateHl7Org extends PreResourceState {
public PreResourceState(BundleEntry theEntry, Class<? extends IBaseResource> theResourceType) {
super(null);
myEntry = theEntry;
myResourceType = theResourceType;
private IMutator myMutator;
private Object myTarget;
public PreResourceStateHl7Org(Object theTarget, IMutator theMutator, Class<? extends IBaseResource> theResourceType) {
super(theResourceType);
myMutator = theMutator;
myTarget = theTarget;
}
/**
* @param theResourceType
* May be null
*/
public PreResourceStateHl7Org(Class<? extends IBaseResource> theResourceType) {
super(theResourceType);
}
@SuppressWarnings("unchecked")
@Override
public void wereBack() {
super.wereBack();
if (myTarget == null) {
myObject = (T) getCurrentElement();
}
}
@Override
public void enteringNewElement(String theNamespaceURI, String theLocalPart) throws DataFormatException {
super.enteringNewElement(theNamespaceURI, theLocalPart);
if (myMutator != null) {
myMutator.addValue(myTarget, getCurrentElement());
}
}
}
private abstract class PreResourceState extends BaseState {
private Map<String, IBaseResource> myContainedResources = new HashMap<String, IBaseResource>();
private IBaseResource myInstance;
private FhirVersionEnum myParentVersion;
private Class<? extends IBaseResource> myResourceType;
public PreResourceState(Class<? extends IBaseResource> theResourceType) {
super(null);
myResourceType = theResourceType;
if (theResourceType != null) {
myParentVersion = myContext.getResourceDefinition(theResourceType).getStructureVersion();
} else {
myParentVersion = myContext.getVersion().getVersion();
}
}
public PreResourceState(PreResourceState thePreResourcesState) {
public PreResourceState(PreResourceState thePreResourcesState, FhirVersionEnum theParentVersion) {
super(thePreResourcesState);
Validate.notNull(theParentVersion);
myParentVersion = theParentVersion;
}
@Override
@ -1738,9 +1879,9 @@ class ParserState<T> {
public void enteringNewElement(String theNamespaceURI, String theLocalPart) throws DataFormatException {
BaseRuntimeElementDefinition<?> definition;
if (myResourceType == null) {
definition = myContext.getResourceDefinition(theLocalPart);
definition = myContext.getResourceDefinition(myParentVersion, theLocalPart);
if ((definition == null)) {
throw new DataFormatException("Element '" + theLocalPart + "' is not a resource, expected a resource at this position");
throw new DataFormatException("Element '" + theLocalPart + "' is not a known resource type, expected a resource at this position");
}
} else {
definition = myContext.getResourceDefinition(myResourceType);
@ -1753,16 +1894,15 @@ class ParserState<T> {
}
RuntimeResourceDefinition def = (RuntimeResourceDefinition) definition;
myInstance = (IResource) def.newInstance();
if (myEntry != null) {
myEntry.setResource(myInstance);
}
myInstance = def.newInstance();
String resourceName = def.getName();
if ("Binary".equals(resourceName) && myContext.getVersion().getVersion() == FhirVersionEnum.DSTU1) {
push(new BinaryResourceStateForDstu1(getRootPreResourceState(), (Binary) myInstance));
push(new BinaryResourceStateForDstu1(getRootPreResourceState(), (BaseBinary) myInstance));
} else if (myInstance instanceof IResource) {
push(new ResourceStateHapi(getRootPreResourceState(), def, (IResource) myInstance));
} else {
push(new ResourceState(getRootPreResourceState(), def, myInstance));
push(new ResourceStateHl7Org(getRootPreResourceState(), def, myInstance));
}
}
@ -1775,10 +1915,6 @@ class ParserState<T> {
return myInstance;
}
public List<ResourceReferenceDt> getResourceReferences() {
return myResourceReferences;
}
private PreResourceState getRootPreResourceState() {
if (getPreResourceState() != null) {
return getPreResourceState();
@ -1795,16 +1931,12 @@ class ParserState<T> {
@SuppressWarnings("unchecked")
@Override
public void wereBack() {
if (myEntry == null) {
myObject = (T) myInstance;
}
myContext.newTerser().visit(myInstance, new IModelVisitor() {
@Override
public void acceptElement(IBase theElement, BaseRuntimeChildDefinition theChildDefinition, BaseRuntimeElementDefinition<?> theDefinition) {
if (theElement instanceof ResourceReferenceDt) {
ResourceReferenceDt nextRef = (ResourceReferenceDt) theElement;
if (theElement instanceof BaseResourceReferenceDt) {
BaseResourceReferenceDt nextRef = (BaseResourceReferenceDt) theElement;
String ref = nextRef.getReference().getValue();
if (isNotBlank(ref)) {
if (ref.startsWith("#")) {
@ -1853,7 +1985,7 @@ class ParserState<T> {
}
@Override
protected TagList getCurrentElement() {
protected IBase getCurrentElement() {
return myTagList;
}
@ -1885,8 +2017,8 @@ class ParserState<T> {
} else if ("id".equals(theName)) {
if (myInstance instanceof IIdentifiableElement) {
((IIdentifiableElement) myInstance).setElementSpecificId(theValue);
} else if (myInstance instanceof Element) {
((Element) myInstance).setId(theValue);
} else if (myInstance instanceof IBaseElement) {
((IBaseElement) myInstance).setId(theValue);
} else if (myInstance instanceof IBaseResource) {
new IdDt(theValue).applyTo((org.hl7.fhir.instance.model.IBaseResource) myInstance);
}
@ -1918,7 +2050,7 @@ class ParserState<T> {
push(new SwallowChildrenWholeState(getPreResourceState()));
return;
}
@Override
protected IBase getCurrentElement() {
return myInstance;
@ -1926,12 +2058,12 @@ class ParserState<T> {
}
private class ResourceReferenceState extends BaseState {
private class ResourceReferenceStateHl7Org extends BaseState {
private ResourceReferenceDt myInstance;
private IReference myInstance;
private ResourceReferenceSubState mySubState;
public ResourceReferenceState(PreResourceState thePreResourceState, ResourceReferenceDt theInstance) {
public ResourceReferenceStateHl7Org(PreResourceState thePreResourceState, IReference theInstance) {
super(thePreResourceState);
myInstance = theInstance;
mySubState = ResourceReferenceSubState.INITIAL;
@ -1988,6 +2120,75 @@ class ParserState<T> {
}
}
@Override
protected IReference getCurrentElement() {
return myInstance;
}
}
private class ResourceReferenceStateHapi extends BaseState {
private BaseResourceReferenceDt myInstance;
private ResourceReferenceSubState mySubState;
public ResourceReferenceStateHapi(PreResourceState thePreResourceState, BaseResourceReferenceDt theInstance) {
super(thePreResourceState);
myInstance = theInstance;
mySubState = ResourceReferenceSubState.INITIAL;
}
@Override
public void attributeValue(String theName, String theValue) throws DataFormatException {
if (!"value".equals(theName)) {
return;
}
switch (mySubState) {
case DISPLAY:
myInstance.getDisplayElement().setValue(theValue);
break;
case INITIAL:
throw new DataFormatException("Unexpected attribute: " + theValue);
case REFERENCE:
myInstance.getReference().setValue(theValue);
break;
}
}
@Override
public void endingElement() {
switch (mySubState) {
case INITIAL:
pop();
break;
case DISPLAY:
case REFERENCE:
mySubState = ResourceReferenceSubState.INITIAL;
}
}
@Override
public void enteringNewElement(String theNamespaceURI, String theLocalPart) throws DataFormatException {
switch (mySubState) {
case INITIAL:
if ("display".equals(theLocalPart)) {
mySubState = ResourceReferenceSubState.DISPLAY;
break;
} else if ("reference".equals(theLocalPart)) {
mySubState = ResourceReferenceSubState.REFERENCE;
break;
} else if ("resource".equals(theLocalPart)) {
mySubState = ResourceReferenceSubState.REFERENCE;
break;
}
//$FALL-THROUGH$
case DISPLAY:
case REFERENCE:
throw new DataFormatException("Unexpected element: " + theLocalPart);
}
}
@Override
protected IElement getCurrentElement() {
return myInstance;
@ -1999,6 +2200,33 @@ class ParserState<T> {
DISPLAY, INITIAL, REFERENCE
}
private class ResourceStateHapi extends ElementCompositeState<IResource> {
public ResourceStateHapi(PreResourceState thePreResourceState, BaseRuntimeElementCompositeDefinition<?> theDef, IResource theInstance) {
super(thePreResourceState, theDef, theInstance);
}
@Override
public void enteringNewElement(String theNamespace, String theChildName) throws DataFormatException {
if ("id".equals(theChildName)) {
push(new PrimitiveState(getPreResourceState(), getCurrentElement().getId()));
} else if ("meta".equals(theChildName)) {
push(new MetaElementState(getPreResourceState(), getCurrentElement().getResourceMetadata()));
} else {
super.enteringNewElement(theNamespace, theChildName);
}
}
}
private class ResourceStateHl7Org extends ElementCompositeState<IBaseResource> {
public ResourceStateHl7Org(PreResourceState thePreResourceState, BaseRuntimeElementCompositeDefinition<?> theDef, IBaseResource theInstance) {
super(thePreResourceState, theDef, theInstance);
}
}
private class SwallowChildrenWholeState extends BaseState {
private int myDepth;
@ -2041,6 +2269,11 @@ class ParserState<T> {
pop();
}
@Override
protected IBase getCurrentElement() {
return myTagList;
}
@Override
public void enteringNewElement(String theNamespaceURI, String theLocalPart) throws DataFormatException {
if (TagList.ATTR_CATEGORY.equals(theLocalPart)) {
@ -2059,11 +2292,11 @@ class ParserState<T> {
private static final int SCHEME = 3;
private static final int TERM = 1;
private String myLabel;
private String myScheme;
private int mySubState = 0;
private TagList myTagList;
private String myTerm;
private String myLabel;
private String myScheme;
public TagState(TagList theTagList) {
super(null);

View File

@ -27,8 +27,10 @@ import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javax.xml.namespace.QName;
import javax.xml.stream.FactoryConfigurationError;
@ -45,11 +47,16 @@ import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import org.apache.commons.lang3.StringUtils;
import org.hl7.fhir.instance.model.DomainResource;
import org.hl7.fhir.instance.model.IBase;
import org.hl7.fhir.instance.model.IBaseResource;
import org.hl7.fhir.instance.model.Narrative;
import org.hl7.fhir.instance.model.Resource;
import org.hl7.fhir.instance.model.IPrimitiveType;
import org.hl7.fhir.instance.model.api.IAnyResource;
import org.hl7.fhir.instance.model.api.IBaseDatatype;
import org.hl7.fhir.instance.model.api.IBaseExtension;
import org.hl7.fhir.instance.model.api.IBaseHasExtensions;
import org.hl7.fhir.instance.model.api.IBaseHasModifierExtensions;
import org.hl7.fhir.instance.model.api.IDomainResource;
import org.hl7.fhir.instance.model.api.INarrative;
import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition;
@ -72,15 +79,16 @@ import ca.uhn.fhir.model.api.ISupportsUndeclaredExtensions;
import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum;
import ca.uhn.fhir.model.api.Tag;
import ca.uhn.fhir.model.api.TagList;
import ca.uhn.fhir.model.dstu.composite.ContainedDt;
import ca.uhn.fhir.model.dstu.composite.NarrativeDt;
import ca.uhn.fhir.model.dstu.composite.ResourceReferenceDt;
import ca.uhn.fhir.model.dstu.resource.Binary;
import ca.uhn.fhir.model.base.composite.BaseContainedDt;
import ca.uhn.fhir.model.base.composite.BaseNarrativeDt;
import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt;
import ca.uhn.fhir.model.base.resource.BaseBinary;
import ca.uhn.fhir.model.primitive.IdDt;
import ca.uhn.fhir.model.primitive.InstantDt;
import ca.uhn.fhir.model.primitive.StringDt;
import ca.uhn.fhir.model.primitive.XhtmlDt;
import ca.uhn.fhir.narrative.INarrativeGenerator;
import ca.uhn.fhir.rest.method.BaseMethodBinding;
import ca.uhn.fhir.util.NonPrettyPrintWriterWrapper;
import ca.uhn.fhir.util.PrettyPrintWriterWrapper;
import ca.uhn.fhir.util.XmlUtil;
@ -101,8 +109,7 @@ public class XmlParser extends BaseParser implements IParser {
private boolean myPrettyPrint;
/**
* Do not use this constructor, the recommended way to obtain a new instance of the XML parser is to invoke
* {@link FhirContext#newXmlParser()}.
* Do not use this constructor, the recommended way to obtain a new instance of the XML parser is to invoke {@link FhirContext#newXmlParser()}.
*/
public XmlParser(FhirContext theContext) {
super(theContext);
@ -170,7 +177,6 @@ public class XmlParser extends BaseParser implements IParser {
throw new DataFormatException("Extension element has no 'url' attribute");
}
parserState.enteringNewElementExtension(elem, urlAttr.getValue(), true);
} else {
String elementName = elem.getName().getLocalPart();
@ -385,8 +391,22 @@ public class XmlParser extends BaseParser implements IParser {
for (BundleEntry nextEntry : theBundle.getEntries()) {
theEventWriter.writeStartElement("entry");
boolean deleted = false;
if (nextEntry.getDeletedAt() != null && nextEntry.getDeletedAt().isEmpty() == false) {
deleted = true;
}
writeOptionalTagWithValue(theEventWriter, "base", determineResourceBaseUrl(bundleBaseUrl, nextEntry));
IResource resource = nextEntry.getResource();
if (resource != null && !resource.isEmpty() && !deleted) {
theEventWriter.writeStartElement("resource");
encodeResourceToXmlStreamWriter(resource, theEventWriter, false);
theEventWriter.writeEndElement(); // content
} else {
ourLog.debug("Bundle entry contains null resource");
}
if (nextEntry.getSearchMode().isEmpty() == false || nextEntry.getScore().isEmpty() == false) {
theEventWriter.writeStartElement("search");
writeOptionalTagWithValue(theEventWriter, "mode", nextEntry.getSearchMode().getValueAsString());
@ -398,13 +418,11 @@ public class XmlParser extends BaseParser implements IParser {
if (nextEntry.getTransactionOperation().isEmpty() == false || nextEntry.getLinkSearch().isEmpty() == false) {
theEventWriter.writeStartElement("transaction");
writeOptionalTagWithValue(theEventWriter, "operation", nextEntry.getTransactionOperation().getValue());
writeOptionalTagWithValue(theEventWriter, "match", nextEntry.getLinkSearch().getValue());
writeOptionalTagWithValue(theEventWriter, "url", nextEntry.getLinkSearch().getValue());
theEventWriter.writeEndElement();
}
boolean deleted = false;
if (nextEntry.getDeletedAt() != null && nextEntry.getDeletedAt().isEmpty() == false) {
deleted = true;
if (deleted) {
theEventWriter.writeStartElement("deleted");
writeOptionalTagWithValue(theEventWriter, "type", nextEntry.getId().getResourceType());
writeOptionalTagWithValue(theEventWriter, "id", nextEntry.getId().getIdPart());
@ -413,15 +431,6 @@ public class XmlParser extends BaseParser implements IParser {
theEventWriter.writeEndElement();
}
IResource resource = nextEntry.getResource();
if (resource != null && !resource.isEmpty() && !deleted) {
theEventWriter.writeStartElement("resource");
encodeResourceToXmlStreamWriter(resource, theEventWriter, false);
theEventWriter.writeEndElement(); // content
} else {
ourLog.debug("Bundle entry contains null resource");
}
theEventWriter.writeEndElement(); // entry
}
@ -429,8 +438,8 @@ public class XmlParser extends BaseParser implements IParser {
theEventWriter.close();
}
private void encodeChildElementToStreamWriter(RuntimeResourceDefinition theResDef, IBaseResource theResource, XMLStreamWriter theEventWriter, IBase nextValue, String childName, BaseRuntimeElementDefinition<?> childDef, String theExtensionUrl, boolean theIncludedResource)
throws XMLStreamException, DataFormatException {
private void encodeChildElementToStreamWriter(IBaseResource theResource, XMLStreamWriter theEventWriter, IBase nextValue, String childName, BaseRuntimeElementDefinition<?> childDef,
String theExtensionUrl, boolean theIncludedResource) throws XMLStreamException, DataFormatException {
if (nextValue.isEmpty()) {
if (childDef.getChildType() == ChildTypeEnum.CONTAINED_RESOURCES && getContainedResources().isEmpty() == false && theIncludedResource == false) {
// We still want to go in..
@ -441,12 +450,12 @@ public class XmlParser extends BaseParser implements IParser {
switch (childDef.getChildType()) {
case PRIMITIVE_DATATYPE: {
IPrimitiveDatatype<?> pd = (IPrimitiveDatatype<?>) nextValue;
IPrimitiveType<?> pd = (IPrimitiveType<?>) nextValue;
String value = pd.getValueAsString();
if (value != null) {
theEventWriter.writeStartElement(childName);
theEventWriter.writeAttribute("value", value);
encodeExtensionsIfPresent(theResDef, theResource, theEventWriter, nextValue, theIncludedResource);
encodeExtensionsIfPresent(theResource, theEventWriter, nextValue, theIncludedResource);
theEventWriter.writeEndElement();
}
break;
@ -458,12 +467,12 @@ public class XmlParser extends BaseParser implements IParser {
theEventWriter.writeAttribute("url", theExtensionUrl);
}
BaseRuntimeElementCompositeDefinition<?> childCompositeDef = (BaseRuntimeElementCompositeDefinition<?>) childDef;
encodeCompositeElementToStreamWriter(theResDef, theResource, nextValue, theEventWriter, childCompositeDef, theIncludedResource);
encodeCompositeElementToStreamWriter(theResource, nextValue, theEventWriter, childCompositeDef, theIncludedResource);
theEventWriter.writeEndElement();
break;
}
case RESOURCE_REF: {
ResourceReferenceDt ref = (ResourceReferenceDt) nextValue;
BaseResourceReferenceDt ref = (BaseResourceReferenceDt) nextValue;
if (!ref.isEmpty()) {
theEventWriter.writeStartElement(childName);
encodeResourceReferenceToStreamWriter(theEventWriter, ref);
@ -472,12 +481,11 @@ public class XmlParser extends BaseParser implements IParser {
break;
}
case CONTAINED_RESOURCES: {
ContainedDt value = (ContainedDt) nextValue;
BaseContainedDt value = (BaseContainedDt) nextValue;
/*
* Disable per #103 for (IResource next : value.getContainedResources()) { if
* (getContainedResources().getResourceId(next) != null) { continue; }
* theEventWriter.writeStartElement("contained"); encodeResourceToXmlStreamWriter(next, theEventWriter,
* true, fixContainedResourceId(next.getId().getValue())); theEventWriter.writeEndElement(); }
* Disable per #103 for (IResource next : value.getContainedResources()) { if (getContainedResources().getResourceId(next) != null) { continue; }
* theEventWriter.writeStartElement("contained"); encodeResourceToXmlStreamWriter(next, theEventWriter, true, fixContainedResourceId(next.getId().getValue()));
* theEventWriter.writeEndElement(); }
*/
for (IBaseResource next : getContainedResources().getContainedResources()) {
IdDt resourceId = getContainedResources().getResourceId(next);
@ -488,7 +496,11 @@ public class XmlParser extends BaseParser implements IParser {
break;
}
case RESOURCE: {
throw new IllegalStateException(); // should not happen
theEventWriter.writeStartElement(childName);
IBaseResource resource = (IBaseResource) nextValue;
encodeResourceToXmlStreamWriter(resource, theEventWriter, false);
theEventWriter.writeEndElement();
break;
}
case PRIMITIVE_XHTML: {
XhtmlDt dt = (XhtmlDt) nextValue;
@ -505,34 +517,41 @@ public class XmlParser extends BaseParser implements IParser {
}
private void encodeCompositeElementChildrenToStreamWriter(RuntimeResourceDefinition theResDef, IBaseResource theResource, IBase theElement, XMLStreamWriter theEventWriter, List<? extends BaseRuntimeChildDefinition> children, boolean theIncludedResource) throws XMLStreamException,
DataFormatException {
private void encodeCompositeElementChildrenToStreamWriter(IBaseResource theResource, IBase theElement, XMLStreamWriter theEventWriter, List<? extends BaseRuntimeChildDefinition> children,
boolean theIncludedResource) throws XMLStreamException, DataFormatException {
for (BaseRuntimeChildDefinition nextChild : children) {
if (nextChild.getElementName().equals("extension") || nextChild.getElementName().equals("modifierExtension")) {
continue;
}
if (nextChild instanceof RuntimeChildNarrativeDefinition && !theIncludedResource) {
INarrativeGenerator gen = myContext.getNarrativeGenerator();
if (theResource instanceof IResource) {
NarrativeDt narr = ((IResource) theResource).getText();
BaseNarrativeDt<?> narr = ((IResource) theResource).getText();
if (gen != null && narr.isEmpty()) {
narr = gen.generateNarrative(theResDef.getResourceProfile(), theResource);
String resourceProfile = myContext.getResourceDefinition(theResource).getResourceProfile();
gen.generateNarrative(resourceProfile, theResource, narr);
}
if (narr != null) {
if (narr.isEmpty() == false) {
RuntimeChildNarrativeDefinition child = (RuntimeChildNarrativeDefinition) nextChild;
String childName = nextChild.getChildNameByDatatype(child.getDatatype());
BaseRuntimeElementDefinition<?> type = child.getChildByName(childName);
encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, narr, childName, type, null, theIncludedResource);
encodeChildElementToStreamWriter(theResource, theEventWriter, narr, childName, type, null, theIncludedResource);
continue;
}
} else {
Narrative narr1 = ((DomainResource) theResource).getText();
NarrativeDt narr2 = null;
INarrative narr1 = ((IDomainResource) theResource).getText();
BaseNarrativeDt<?> narr2 = null;
if (gen != null && narr1.isEmpty()) {
narr2 = gen.generateNarrative(theResDef.getResourceProfile(), theResource);
// TODO: need to implement this
String resourceProfile = myContext.getResourceDefinition(theResource).getResourceProfile();
gen.generateNarrative(resourceProfile, theResource, null);
}
if (narr2 != null) {
RuntimeChildNarrativeDefinition child = (RuntimeChildNarrativeDefinition) nextChild;
String childName = nextChild.getChildNameByDatatype(child.getDatatype());
BaseRuntimeElementDefinition<?> type = child.getChildByName(childName);
encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, narr2, childName, type, null, theIncludedResource);
encodeChildElementToStreamWriter(theResource, theEventWriter, narr2, childName, type, null, theIncludedResource);
continue;
}
}
@ -544,7 +563,7 @@ public class XmlParser extends BaseParser implements IParser {
}
for (IBase nextValue : values) {
if ((nextValue == null || nextValue.isEmpty()) && !(nextValue instanceof ContainedDt)) {
if ((nextValue == null || nextValue.isEmpty()) && !(nextValue instanceof BaseContainedDt)) {
continue;
}
Class<? extends IBase> type = nextValue.getClass();
@ -555,11 +574,11 @@ public class XmlParser extends BaseParser implements IParser {
super.throwExceptionForUnknownChildType(nextChild, type);
}
if (nextValue instanceof ExtensionDt) {
extensionUrl = ((ExtensionDt) nextValue).getUrlAsString();
encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, nextValue, childName, childDef, extensionUrl, theIncludedResource);
if (nextValue instanceof IBaseExtension && myContext.getVersion().getVersion() == FhirVersionEnum.DSTU1) {
// This is called for the Query resource in DSTU1 only
extensionUrl = ((IBaseExtension<?>) nextValue).getUrl();
encodeChildElementToStreamWriter(theResource, theEventWriter, nextValue, childName, childDef, extensionUrl, theIncludedResource);
} else if (extensionUrl != null && childName.equals("extension") == false) {
RuntimeChildDeclaredExtensionDefinition extDef = (RuntimeChildDeclaredExtensionDefinition) nextChild;
if (extDef.isModifier()) {
@ -569,32 +588,51 @@ public class XmlParser extends BaseParser implements IParser {
}
theEventWriter.writeAttribute("url", extensionUrl);
encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, nextValue, childName, childDef, null, theIncludedResource);
encodeChildElementToStreamWriter(theResource, theEventWriter, nextValue, childName, childDef, null, theIncludedResource);
theEventWriter.writeEndElement();
} else if (nextChild instanceof RuntimeChildNarrativeDefinition && theIncludedResource) {
// suppress narratives from contained resources
} else {
encodeChildElementToStreamWriter(theResDef, theResource, theEventWriter, nextValue, childName, childDef, extensionUrl, theIncludedResource);
encodeChildElementToStreamWriter(theResource, theEventWriter, nextValue, childName, childDef, extensionUrl, theIncludedResource);
}
}
}
}
private void encodeCompositeElementToStreamWriter(RuntimeResourceDefinition theResDef, IBaseResource theResource, IBase theElement, XMLStreamWriter theEventWriter, BaseRuntimeElementCompositeDefinition<?> resDef, boolean theIncludedResource) throws XMLStreamException, DataFormatException {
encodeExtensionsIfPresent(theResDef, theResource, theEventWriter, theElement, theIncludedResource);
encodeCompositeElementChildrenToStreamWriter(theResDef, theResource, theElement, theEventWriter, resDef.getExtensions(), theIncludedResource);
encodeCompositeElementChildrenToStreamWriter(theResDef, theResource, theElement, theEventWriter, resDef.getChildren(), theIncludedResource);
private void encodeCompositeElementToStreamWriter(IBaseResource theResource, IBase theElement, XMLStreamWriter theEventWriter, BaseRuntimeElementCompositeDefinition<?> theElementDefinition,
boolean theIncludedResource) throws XMLStreamException, DataFormatException {
encodeExtensionsIfPresent(theResource, theEventWriter, theElement, theIncludedResource);
encodeCompositeElementChildrenToStreamWriter(theResource, theElement, theEventWriter, theElementDefinition.getExtensions(), theIncludedResource);
encodeCompositeElementChildrenToStreamWriter(theResource, theElement, theEventWriter, theElementDefinition.getChildren(), theIncludedResource);
}
private void encodeExtensionsIfPresent(RuntimeResourceDefinition theResDef, IBaseResource theResource, XMLStreamWriter theWriter, IBase theElement, boolean theIncludedResource) throws XMLStreamException, DataFormatException {
private void encodeExtensionsIfPresent(IBaseResource theResource, XMLStreamWriter theWriter, IBase theElement, boolean theIncludedResource) throws XMLStreamException, DataFormatException {
if (theElement instanceof ISupportsUndeclaredExtensions) {
ISupportsUndeclaredExtensions res = (ISupportsUndeclaredExtensions) theElement;
encodeUndeclaredExtensions(theResDef, theResource, theWriter, res.getUndeclaredExtensions(), "extension", theIncludedResource);
encodeUndeclaredExtensions(theResDef, theResource, theWriter, res.getUndeclaredModifierExtensions(), "modifierExtension", theIncludedResource);
encodeUndeclaredExtensions(theResource, theWriter, toBaseExtensionList(res.getUndeclaredExtensions()), "extension", theIncludedResource);
encodeUndeclaredExtensions(theResource, theWriter, toBaseExtensionList(res.getUndeclaredModifierExtensions()), "modifierExtension", theIncludedResource);
}
if (theElement instanceof IBaseHasExtensions) {
IBaseHasExtensions res = (IBaseHasExtensions) theElement;
encodeUndeclaredExtensions(theResource, theWriter, res.getExtension(), "extension", theIncludedResource);
}
if (theElement instanceof IBaseHasModifierExtensions) {
IBaseHasModifierExtensions res = (IBaseHasModifierExtensions) theElement;
encodeUndeclaredExtensions(theResource, theWriter, res.getModifierExtension(), "modifierExtension", theIncludedResource);
}
}
private void encodeResourceReferenceToStreamWriter(XMLStreamWriter theEventWriter, ResourceReferenceDt theRef) throws XMLStreamException {
/**
* This is just to work around the fact that casting java.util.List<ca.uhn.fhir.model.api.ExtensionDt> to java.util.List<? extends org.hl7.fhir.instance.model.api.IBaseExtension<?>> seems to be
* rejected by the compiler some of the time.
*/
private <Q extends IBaseExtension<?>> List<IBaseExtension<?>> toBaseExtensionList(final List<Q> theList) {
List<IBaseExtension<?>> retVal = new ArrayList<IBaseExtension<?>>(theList.size());
retVal.addAll(theList);
return retVal;
}
private void encodeResourceReferenceToStreamWriter(XMLStreamWriter theEventWriter, BaseResourceReferenceDt theRef) throws XMLStreamException {
String reference = determineReferenceText(theRef);
if (StringUtils.isNotBlank(reference)) {
@ -602,17 +640,18 @@ public class XmlParser extends BaseParser implements IParser {
theEventWriter.writeAttribute("value", reference);
theEventWriter.writeEndElement();
}
if (!(theRef.getDisplay().isEmpty())) {
if (!(theRef.getDisplayElement().isEmpty())) {
theEventWriter.writeStartElement(RESREF_DISPLAY);
theEventWriter.writeAttribute("value", theRef.getDisplay().getValue());
theEventWriter.writeAttribute("value", theRef.getDisplayElement().getValue());
theEventWriter.writeEndElement();
}
}
private void encodeResourceToStreamWriterInDstu2Format(RuntimeResourceDefinition theResDef, IBaseResource theResource, IBase theElement, XMLStreamWriter theEventWriter, BaseRuntimeElementCompositeDefinition<?> resDef, boolean theIncludedResource) throws XMLStreamException, DataFormatException {
private void encodeResourceToStreamWriterInDstu2Format(RuntimeResourceDefinition theResDef, IBaseResource theResource, IBase theElement, XMLStreamWriter theEventWriter,
BaseRuntimeElementCompositeDefinition<?> resDef, boolean theIncludedResource) throws XMLStreamException, DataFormatException {
/*
* DSTU2 requires extensions to come in a specific spot within the encoded content - This is a bit of a messy
* way to make that happen, but hopefully this won't matter as much once we use the HL7 structures
* DSTU2 requires extensions to come in a specific spot within the encoded content - This is a bit of a messy way to make that happen, but hopefully this won't matter as much once we use the
* HL7 structures
*/
List<BaseRuntimeChildDefinition> preExtensionChildren = new ArrayList<BaseRuntimeChildDefinition>();
@ -627,12 +666,12 @@ public class XmlParser extends BaseParser implements IParser {
postExtensionChildren.add(next);
}
}
encodeCompositeElementChildrenToStreamWriter(theResDef, theResource, theElement, theEventWriter, preExtensionChildren, theIncludedResource);
encodeCompositeElementChildrenToStreamWriter(theResource, theElement, theEventWriter, preExtensionChildren, theIncludedResource);
encodeExtensionsIfPresent(theResDef, theResource, theEventWriter, theElement, theIncludedResource);
encodeCompositeElementChildrenToStreamWriter(theResDef, theResource, theElement, theEventWriter, resDef.getExtensions(), theIncludedResource);
encodeExtensionsIfPresent(theResource, theEventWriter, theElement, theIncludedResource);
encodeCompositeElementChildrenToStreamWriter(theResource, theElement, theEventWriter, resDef.getExtensions(), theIncludedResource);
encodeCompositeElementChildrenToStreamWriter(theResDef, theResource, theElement, theEventWriter, postExtensionChildren, theIncludedResource);
encodeCompositeElementChildrenToStreamWriter(theResource, theElement, theEventWriter, postExtensionChildren, theIncludedResource);
}
@ -670,7 +709,7 @@ public class XmlParser extends BaseParser implements IParser {
}
} else {
// HL7 structs
Resource resource = (Resource) theResource;
IAnyResource resource = (IAnyResource) theResource;
if (StringUtils.isNotBlank(resource.getId())) {
resourceId = resource.getId();
}
@ -692,50 +731,59 @@ public class XmlParser extends BaseParser implements IParser {
theEventWriter.writeStartElement(resDef.getName());
theEventWriter.writeDefaultNamespace(FHIR_NS);
if (myContext.getVersion().getVersion().isNewerThan(FhirVersionEnum.DSTU1)) {
if (theResource instanceof IAnyResource) {
// DSTU2+
IResource resource = (IResource) theResource;
writeOptionalTagWithValue(theEventWriter, "id", theResourceId);
InstantDt updated = (InstantDt) resource.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED);
IdDt resourceId = resource.getId();
if (resourceId != null && isNotBlank(resourceId.getVersionIdPart()) || (updated != null && !updated.isEmpty())) {
theEventWriter.writeStartElement("meta");
writeOptionalTagWithValue(theEventWriter, "versionId", resourceId.getVersionIdPart());
if (updated != null) {
writeOptionalTagWithValue(theEventWriter, "lastUpdated", updated.getValueAsString());
}
theEventWriter.writeEndElement();
}
// HL7.org Structures
encodeCompositeElementToStreamWriter(theResource, theResource, theEventWriter, resDef, theContainedResource);
} else {
// DSTU1
if (theResourceId != null && theContainedResource) {
theEventWriter.writeAttribute("id", theResourceId);
}
}
if (theResource instanceof Binary) {
Binary bin = (Binary) theResource;
if (myContext.getVersion().getVersion().isNewerThan(FhirVersionEnum.DSTU1)) {
writeOptionalTagWithValue(theEventWriter, "contentType", bin.getContentType());
writeOptionalTagWithValue(theEventWriter, "content", bin.getContentAsBase64());
} else {
if (bin.getContentType() != null) {
theEventWriter.writeAttribute("contentType", bin.getContentType());
}
theEventWriter.writeCharacters(bin.getContentAsBase64());
}
} else {
if (myContext.getVersion().getVersion().isNewerThan(FhirVersionEnum.DSTU1)) {
// DSTU2+
encodeResourceToStreamWriterInDstu2Format(resDef, theResource, theResource, theEventWriter, resDef, theContainedResource);
IResource resource = (IResource) theResource;
writeOptionalTagWithValue(theEventWriter, "id", theResourceId);
InstantDt updated = (InstantDt) resource.getResourceMetadata().get(ResourceMetadataKeyEnum.UPDATED);
IdDt resourceId = resource.getId();
if (resourceId != null && isNotBlank(resourceId.getVersionIdPart()) || (updated != null && !updated.isEmpty())) {
theEventWriter.writeStartElement("meta");
String versionIdPart = resourceId.getVersionIdPart();
if (isBlank(versionIdPart)) {
versionIdPart = ResourceMetadataKeyEnum.VERSION.get(resource);
}
writeOptionalTagWithValue(theEventWriter, "versionId", versionIdPart);
if (updated != null) {
writeOptionalTagWithValue(theEventWriter, "lastUpdated", updated.getValueAsString());
}
theEventWriter.writeEndElement();
}
if (theResource instanceof BaseBinary) {
BaseBinary bin = (BaseBinary) theResource;
writeOptionalTagWithValue(theEventWriter, "contentType", bin.getContentType());
writeOptionalTagWithValue(theEventWriter, "content", bin.getContentAsBase64());
} else {
encodeResourceToStreamWriterInDstu2Format(resDef, theResource, theResource, theEventWriter, resDef, theContainedResource);
}
} else {
// DSTU1
encodeCompositeElementToStreamWriter(resDef, theResource, theResource, theEventWriter, resDef, theContainedResource);
if (theResourceId != null && theContainedResource) {
theEventWriter.writeAttribute("id", theResourceId);
}
if (theResource instanceof BaseBinary) {
BaseBinary bin = (BaseBinary) theResource;
if (bin.getContentType() != null) {
theEventWriter.writeAttribute("contentType", bin.getContentType());
}
theEventWriter.writeCharacters(bin.getContentAsBase64());
} else {
encodeCompositeElementToStreamWriter(theResource, theResource, theEventWriter, resDef, theContainedResource);
}
}
}
@ -774,24 +822,20 @@ public class XmlParser extends BaseParser implements IParser {
}
}
private void encodeUndeclaredExtensions(RuntimeResourceDefinition theResDef, IBaseResource theResource, XMLStreamWriter theWriter, List<ExtensionDt> theExtensions, String tagName, boolean theIncludedResource) throws XMLStreamException, DataFormatException {
for (ExtensionDt next : theExtensions) {
private void encodeUndeclaredExtensions(IBaseResource theResource, XMLStreamWriter theWriter, List<? extends IBaseExtension<?>> theExtensions, String tagName, boolean theIncludedResource)
throws XMLStreamException, DataFormatException {
for (IBaseExtension<?> next : theExtensions) {
if (next == null) {
continue;
}
theWriter.writeStartElement(tagName);
theWriter.writeAttribute("url", next.getUrl().getValue());
String url = next.getUrl();
theWriter.writeAttribute("url", url);
if (next.getValue() != null) {
IElement value = next.getValue();
// RuntimeChildUndeclaredExtensionDefinition extDef =
// myContext.getRuntimeChildUndeclaredExtensionDefinition();
// String childName = extDef.getChildNameByDatatype(nextValue.getClass());
// if (childName == null) {
// throw new ConfigurationException("Unable to encode extension, unregognized child element type: " +
// nextValue.getClass().getCanonicalName());
// }
// BaseRuntimeElementDefinition<?> childDef =
// extDef.getChildElementDefinitionByDatatype(nextValue.getClass());
//
//
IBaseDatatype value = next.getValue();
RuntimeChildUndeclaredExtensionDefinition extDef = myContext.getRuntimeChildUndeclaredExtensionDefinition();
String childName = extDef.getChildNameByDatatype(value.getClass());
BaseRuntimeElementDefinition<?> childDef;
@ -805,11 +849,11 @@ public class XmlParser extends BaseParser implements IParser {
} else {
childDef = extDef.getChildElementDefinitionByDatatype(value.getClass());
}
encodeChildElementToStreamWriter(theResDef, theResource, theWriter, value, childName, childDef, null, theIncludedResource);
encodeChildElementToStreamWriter(theResource, theWriter, value, childName, childDef, null, theIncludedResource);
}
// child extensions
encodeExtensionsIfPresent(theResDef, theResource, theWriter, next, theIncludedResource);
encodeExtensionsIfPresent(theResource, theWriter, next, theIncludedResource);
theWriter.writeEndElement();
}
@ -921,9 +965,8 @@ public class XmlParser extends BaseParser implements IParser {
}
@Override
public <T extends IBaseResource> T parseResource(Class<T> theResourceType, Reader theReader) {
public <T extends IBaseResource> T doParseResource(Class<T> theResourceType, Reader theReader) {
XMLEventReader streamReader = createStreamReader(theReader);
return parseResource(theResourceType, streamReader);
}

View File

@ -1,4 +1,4 @@
package org.hl7.fhir.instance.model.annotations;
package ca.uhn.fhir.rest.annotation;
/*
* #%L
@ -25,26 +25,8 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Class annotation which indicates a resource definition class
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(value= {ElementType.TYPE})
public @interface ResourceDef {
/**
* The name of the resource (e.g. "Patient" or "DiagnosticReport")
*/
String name();
/**
* Not currently used
*/
String id() default "";
/**
* The URL indicating the profile for this resource definition, if known
*/
String profile() default "";
@Target(ElementType.PARAMETER)
public @interface ConditionalOperationParam {
// just a marker
}

View File

@ -131,6 +131,10 @@ public class MethodOutcome {
return myVersionId;
}
/**
* This will be set to {@link Boolean#TRUE} for instance of MethodOutcome which are
* returned to client instances, if the server has responded with an HTTP 201 Created.
*/
public Boolean getCreated() {
return myCreated;
}
@ -146,8 +150,9 @@ public class MethodOutcome {
* If not null, indicates whether the resource was created (as opposed to being updated). This is generally not needed, since the server can assume based on the method being called
* whether the result was a creation or an update. However, it can be useful if you are implementing an update method that does a create if the ID doesn't already exist.
*/
public void setCreated(Boolean theCreated) {
public MethodOutcome setCreated(Boolean theCreated) {
myCreated = theCreated;
return this;
}
/**

View File

@ -182,9 +182,14 @@ public abstract class BaseClient {
}
try {
ContentType ct = ContentType.get(response.getEntity());
String mimeType = ct != null ? ct.getMimeType() : null;
String mimeType;
if (Constants.STATUS_HTTP_204_NO_CONTENT == response.getStatusLine().getStatusCode()) {
mimeType = null;
} else {
ContentType ct = ContentType.get(response.getEntity());
mimeType = ct != null ? ct.getMimeType() : null;
}
Map<String, List<String>> headers = new HashMap<String, List<String>>();
if (response.getAllHeaders() != null) {
for (Header next : response.getAllHeaders()) {
@ -398,7 +403,9 @@ public abstract class BaseClient {
charset = ct.getCharset();
}
if (charset == null) {
ourLog.warn("Response did not specify a charset.");
if (Constants.STATUS_HTTP_204_NO_CONTENT != theResponse.getStatusLine().getStatusCode()) {
ourLog.warn("Response did not specify a charset.");
}
charset = Charset.forName("UTF-8");
}

View File

@ -59,6 +59,9 @@ public abstract class BaseHttpClientInvocation {
public abstract HttpRequestBase asHttpRequest(String theUrlBase, Map<String, List<String>> theExtraParams, EncodingEnum theEncoding);
protected static void appendExtraParamsWithQuestionMark(Map<String, List<String>> theExtraParams, StringBuilder theUrlBuilder, boolean theWithQuestionMark) {
if (theExtraParams==null) {
return;
}
boolean first = theWithQuestionMark;
if (theExtraParams != null && theExtraParams.isEmpty() == false) {

View File

@ -56,10 +56,14 @@ import ca.uhn.fhir.rest.client.exceptions.NonFhirResponseException;
import ca.uhn.fhir.rest.gclient.IClientExecutable;
import ca.uhn.fhir.rest.gclient.ICreate;
import ca.uhn.fhir.rest.gclient.ICreateTyped;
import ca.uhn.fhir.rest.gclient.ICreateWithQuery;
import ca.uhn.fhir.rest.gclient.ICreateWithQueryTyped;
import ca.uhn.fhir.rest.gclient.ICriterion;
import ca.uhn.fhir.rest.gclient.ICriterionInternal;
import ca.uhn.fhir.rest.gclient.IDelete;
import ca.uhn.fhir.rest.gclient.IDeleteTyped;
import ca.uhn.fhir.rest.gclient.IDeleteWithQuery;
import ca.uhn.fhir.rest.gclient.IDeleteWithQueryTyped;
import ca.uhn.fhir.rest.gclient.IGetPage;
import ca.uhn.fhir.rest.gclient.IGetPageTyped;
import ca.uhn.fhir.rest.gclient.IGetTags;
@ -76,6 +80,8 @@ import ca.uhn.fhir.rest.gclient.IUntypedQuery;
import ca.uhn.fhir.rest.gclient.IUpdate;
import ca.uhn.fhir.rest.gclient.IUpdateExecutable;
import ca.uhn.fhir.rest.gclient.IUpdateTyped;
import ca.uhn.fhir.rest.gclient.IUpdateWithQuery;
import ca.uhn.fhir.rest.gclient.IUpdateWithQueryTyped;
import ca.uhn.fhir.rest.method.DeleteMethodBinding;
import ca.uhn.fhir.rest.method.HistoryMethodBinding;
import ca.uhn.fhir.rest.method.HttpDeleteClientInvocation;
@ -237,10 +243,10 @@ public class GenericClient extends BaseClient implements IGenericClient {
return new LoadPageInternal();
}
@Override
public <T extends IBaseResource> T read(final Class<T> theType, IdDt theId) {
return doReadOrVRead(theType, theId, false, null, null);
}
// @Override
// public <T extends IBaseResource> T read(final Class<T> theType, IdDt theId) {
// return doReadOrVRead(theType, theId, false, null, null);
// }
@Override
public <T extends IBaseResource> T read(Class<T> theType, String theId) {
@ -248,8 +254,9 @@ public class GenericClient extends BaseClient implements IGenericClient {
}
@Override
public <T extends IResource> T read(final Class<T> theType, UriDt theUrl) {
return read(theType, new IdDt(theUrl));
public <T extends IBaseResource> T read(final Class<T> theType, UriDt theUrl) {
IdDt id = theUrl instanceof IdDt ? ((IdDt) theUrl) : new IdDt(theUrl);
return doReadOrVRead(theType, id, false, null, null);
}
@Override
@ -446,7 +453,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
if (theIfVersionMatches != null) {
invocation.addHeader(Constants.HEADER_IF_NONE_MATCH, '"' + theIfVersionMatches + '"');
}
ResourceResponseHandler<T> binding = new ResourceResponseHandler<T>(theType, id);
if (theNotModifiedHandler == null) {
@ -474,18 +481,18 @@ public class GenericClient extends BaseClient implements IGenericClient {
return vread(theType, resId);
}
private static void addParam(Map<String, List<String>> params, String parameterName, String parameterValue) {
if (!params.containsKey(parameterName)) {
params.put(parameterName, new ArrayList<String>());
}
params.get(parameterName).add(parameterValue);
}
private abstract class BaseClientExecutable<T extends IClientExecutable<?, ?>, Y> implements IClientExecutable<T, Y> {
private EncodingEnum myParamEncoding;
private Boolean myPrettyPrint;
private boolean myQueryLogRequestAndResponse;
protected void addParam(Map<String, List<String>> params, String parameterName, String parameterValue) {
if (!params.containsKey(parameterName)) {
params.put(parameterName, new ArrayList<String>());
}
params.get(parameterName).add(parameterValue);
}
@SuppressWarnings("unchecked")
@Override
public T andLogRequestAndResponse(boolean theLogRequestAndResponse) {
@ -574,11 +581,13 @@ public class GenericClient extends BaseClient implements IGenericClient {
}
}
private class CreateInternal extends BaseClientExecutable<ICreateTyped, MethodOutcome> implements ICreate, ICreateTyped {
private class CreateInternal extends BaseClientExecutable<ICreateTyped, MethodOutcome> implements ICreate, ICreateTyped, ICreateWithQuery, ICreateWithQueryTyped {
private String myId;
private IResource myResource;
private String myResourceBody;
private String mySearchUrl;
private CriterionList myCriterionList;
@Override
public MethodOutcome execute() {
@ -592,7 +601,14 @@ public class GenericClient extends BaseClient implements IGenericClient {
myResourceBody = null;
}
BaseHttpClientInvocation invocation = MethodUtil.createCreateInvocation(myResource, myResourceBody, myId, myContext);
BaseHttpClientInvocation invocation;
if (mySearchUrl != null) {
invocation = MethodUtil.createCreateInvocation(myResource, myResourceBody, myId, myContext, mySearchUrl);
} else if (myCriterionList != null) {
invocation = MethodUtil.createCreateInvocation(myResource, myResourceBody, myId, myContext, myCriterionList.toParamList());
} else {
invocation = MethodUtil.createCreateInvocation(myResource, myResourceBody, myId, myContext);
}
RuntimeResourceDefinition def = myContext.getResourceDefinition(myResource);
final String resourceName = def.getName();
@ -630,15 +646,50 @@ public class GenericClient extends BaseClient implements IGenericClient {
return this;
}
@Override
public ICreateTyped conditionalByUrl(String theSearchUrl) {
mySearchUrl = theSearchUrl;
return this;
}
@Override
public ICreateWithQuery conditional() {
myCriterionList = new CriterionList();
return this;
}
@Override
public ICreateWithQueryTyped where(ICriterion<?> theCriterion) {
myCriterionList.add((ICriterionInternal) theCriterion);
return this;
}
@Override
public ICreateWithQueryTyped and(ICriterion<?> theCriterion) {
myCriterionList.add((ICriterionInternal) theCriterion);
return this;
}
}
private class DeleteInternal extends BaseClientExecutable<IDeleteTyped, BaseOperationOutcome> implements IDelete, IDeleteTyped {
private class DeleteInternal extends BaseClientExecutable<IDeleteTyped, BaseOperationOutcome> implements IDelete, IDeleteTyped, IDeleteWithQuery, IDeleteWithQueryTyped {
private IdDt myId;
private String mySearchUrl;
private String myResourceType;
private CriterionList myCriterionList;
@Override
public BaseOperationOutcome execute() {
HttpDeleteClientInvocation invocation = DeleteMethodBinding.createDeleteInvocation(myId);
HttpDeleteClientInvocation invocation;
if (myId != null) {
invocation = DeleteMethodBinding.createDeleteInvocation(myId);
} else if (myCriterionList != null) {
Map<String, List<String>> params = myCriterionList.toParamList();
invocation = DeleteMethodBinding.createDeleteInvocation(myResourceType, params);
} else {
invocation = DeleteMethodBinding.createDeleteInvocation(mySearchUrl);
}
OperationOutcomeResponseHandler binding = new OperationOutcomeResponseHandler();
Map<String, List<String>> params = new HashMap<String, List<String>>();
return invoke(params, binding, invocation);
@ -679,6 +730,56 @@ public class GenericClient extends BaseClient implements IGenericClient {
myId = new IdDt(theResourceType, theLogicalId);
return this;
}
@Override
public IDeleteTyped resourceConditionalByUrl(String theSearchUrl) {
Validate.notBlank(theSearchUrl, "theSearchUrl can not be blank/null");
mySearchUrl = theSearchUrl;
return this;
}
@Override
public IDeleteWithQuery resourceConditionalByType(String theResourceType) {
Validate.notBlank(theResourceType, "theResourceType can not be blank/null");
if (myContext.getResourceDefinition(theResourceType) == null) {
throw new IllegalArgumentException("Unknown resource type: " + theResourceType);
}
myResourceType = theResourceType;
myCriterionList = new CriterionList();
return this;
}
@Override
public IDeleteWithQueryTyped where(ICriterion<?> theCriterion) {
myCriterionList.add((ICriterionInternal) theCriterion);
return this;
}
@Override
public IDeleteWithQueryTyped and(ICriterion<?> theCriterion) {
myCriterionList.add((ICriterionInternal) theCriterion);
return this;
}
}
private static class CriterionList extends ArrayList<ICriterionInternal> {
private static final long serialVersionUID = 1L;
public void populateParamList(Map<String, List<String>> theParams) {
for (ICriterionInternal next : this) {
String parameterName = next.getParameterName();
String parameterValue = next.getParameterValue();
addParam(theParams, parameterName, parameterValue);
}
}
public Map<String, List<String>> toParamList() {
LinkedHashMap<String, List<String>> retVal = new LinkedHashMap<String, List<String>>();
populateParamList(retVal);
return retVal;
}
}
private class GetPageInternal extends BaseClientExecutable<IGetPageTyped, Bundle> implements IGetPageTyped {
@ -995,7 +1096,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
private class SearchInternal extends BaseClientExecutable<IQuery, Bundle> implements IQuery, IUntypedQuery {
private String myCompartmentName;
private List<ICriterionInternal> myCriterion = new ArrayList<ICriterionInternal>();
private CriterionList myCriterion = new CriterionList();
private List<Include> myInclude = new ArrayList<Include>();
private Integer myParamLimit;
private String myResourceId;
@ -1024,11 +1125,7 @@ public class GenericClient extends BaseClient implements IGenericClient {
// params.putAll(initial);
// }
for (ICriterionInternal next : myCriterion) {
String parameterName = next.getParameterName();
String parameterValue = next.getParameterValue();
addParam(params, parameterName, parameterValue);
}
myCriterion.populateParamList(params);
for (Include next : myInclude) {
addParam(params, Constants.PARAM_INCLUDE, next.getValue());
@ -1223,30 +1320,39 @@ public class GenericClient extends BaseClient implements IGenericClient {
}
private class UpdateInternal extends BaseClientExecutable<IUpdateExecutable, MethodOutcome> implements IUpdate, IUpdateTyped, IUpdateExecutable {
private class UpdateInternal extends BaseClientExecutable<IUpdateExecutable, MethodOutcome> implements IUpdate, IUpdateTyped, IUpdateExecutable, IUpdateWithQuery, IUpdateWithQueryTyped {
private IdDt myId;
private IResource myResource;
private String myResourceBody;
private String mySearchUrl;
private CriterionList myCriterionList;
@Override
public MethodOutcome execute() {
if (myResource == null) {
myResource = parseResourceBody(myResourceBody);
}
if (myId == null) {
myId = myResource.getId();
}
if (myId == null || myId.hasIdPart() == false) {
throw new InvalidRequestException("No ID supplied for resource to update, can not invoke server");
}
// If an explicit encoding is chosen, we will re-serialize to ensure the right encoding
if (getParamEncoding() != null) {
myResourceBody = null;
}
BaseHttpClientInvocation invocation = MethodUtil.createUpdateInvocation(myResource, myResourceBody, myId, myContext);
BaseHttpClientInvocation invocation;
if (mySearchUrl != null) {
invocation = MethodUtil.createUpdateInvocation(myContext, myResource, myResourceBody, mySearchUrl);
} else if (myCriterionList != null) {
invocation = MethodUtil.createUpdateInvocation(myContext, myResource, myResourceBody, myCriterionList.toParamList());
} else {
if (myId == null) {
myId = myResource.getId();
}
if (myId == null || myId.hasIdPart() == false) {
throw new InvalidRequestException("No ID supplied for resource to update, can not invoke server");
}
invocation = MethodUtil.createUpdateInvocation(myResource, myResourceBody, myId, myContext);
}
RuntimeResourceDefinition def = myContext.getResourceDefinition(myResource);
final String resourceName = def.getName();
@ -1296,6 +1402,30 @@ public class GenericClient extends BaseClient implements IGenericClient {
return this;
}
@Override
public IUpdateTyped conditionalByUrl(String theSearchUrl) {
mySearchUrl = theSearchUrl;
return this;
}
@Override
public IUpdateWithQuery conditional() {
myCriterionList = new CriterionList();
return this;
}
@Override
public IUpdateWithQueryTyped where(ICriterion<?> theCriterion) {
myCriterionList.add((ICriterionInternal) theCriterion);
return this;
}
@Override
public IUpdateWithQueryTyped and(ICriterion<?> theCriterion) {
myCriterionList.add((ICriterionInternal) theCriterion);
return this;
}
}
}

View File

@ -151,23 +151,23 @@ public interface IGenericClient {
*/
IRead read();
/**
* Implementation of the "instance read" method. This method will only ever do a "read" for the latest version of a
* given resource instance, even if the ID passed in contains a version. If you wish to request a specific version
* of a resource (the "vread" operation), use {@link #vread(Class, IdDt)} instead.
* <p>
* Note that if an absolute resource ID is passed in (i.e. a URL containing a protocol and host as well as the
* resource type and ID) the server base for the client will be ignored, and the URL passed in will be queried.
* </p>
*
* @param theType
* The type of resource to load
* @param theId
* The ID to load, including the resource ID and the resource version ID. Valid values include
* "Patient/123/_history/222", or "http://example.com/fhir/Patient/123/_history/222"
* @return The resource
*/
<T extends IBaseResource> T read(Class<T> theType, IdDt theId);
// /**
// * Implementation of the "instance read" method. This method will only ever do a "read" for the latest version of a
// * given resource instance, even if the ID passed in contains a version. If you wish to request a specific version
// * of a resource (the "vread" operation), use {@link #vread(Class, IdDt)} instead.
// * <p>
// * Note that if an absolute resource ID is passed in (i.e. a URL containing a protocol and host as well as the
// * resource type and ID) the server base for the client will be ignored, and the URL passed in will be queried.
// * </p>
// *
// * @param theType
// * The type of resource to load
// * @param theId
// * The ID to load, including the resource ID and the resource version ID. Valid values include
// * "Patient/123/_history/222", or "http://example.com/fhir/Patient/123/_history/222"
// * @return The resource
// */
// <T extends IBaseResource> T read(Class<T> theType, IdDt theId);
/**
* Implementation of the "instance read" method.
@ -189,7 +189,7 @@ public interface IGenericClient {
* The absolute URL, e.g. "http://example.com/fhir/Patient/123"
* @return The returned resource from the server
*/
<T extends IResource> T read(Class<T> theType, UriDt theUrl);
<T extends IBaseResource> T read(Class<T> theType, UriDt theUrl);
/**
* Perform the "read" operation (retrieve the latest version of a resource instance by ID) using an absolute URL.

View File

@ -150,6 +150,14 @@ public interface IRestfulClientFactory {
*/
void setProxy(String theHost, Integer thePort);
/**
* Sets the credentials to use to authenticate with the HTTP proxy,
* if one is defined. Set to null to use no authentication with the proxy.
* @param theUsername The username
* @param thePassword The password
*/
void setProxyCredentials(String theUsername, String thePassword);
/**
* Sets the server validation mode for any clients created from this factory. Server
* validation involves the client requesting the server's conformance statement

View File

@ -23,6 +23,7 @@ package ca.uhn.fhir.rest.client;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
@ -32,9 +33,15 @@ import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.ProxyAuthenticationStrategy;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import ca.uhn.fhir.context.ConfigurationException;
@ -100,18 +107,35 @@ public class RestfulClientFactory implements IRestfulClientFactory {
.setProxy(myProxy)
.build();
myHttpClient = HttpClients.custom()
HttpClientBuilder builder = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(defaultRequestConfig)
.disableCookieManagement()
.build();
.disableCookieManagement();
if (myProxy != null && StringUtils.isNotBlank(myProxyUsername) && StringUtils.isNotBlank(myProxyPassword)) {
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(myProxy.getHostName(), myProxy.getPort()), new UsernamePasswordCredentials(myProxyUsername, myProxyPassword));
builder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());
builder.setDefaultCredentialsProvider(credsProvider);
}
myHttpClient = builder.build();
//@formatter:on
}
return myHttpClient;
}
private String myProxyUsername;
private String myProxyPassword;
@Override
public void setProxyCredentials(String theUsername, String thePassword) {
myProxyUsername=theUsername;
myProxyPassword=thePassword;
}
@Override
public ServerValidationModeEnum getServerValidationModeEnum() {
return myServerValidationMode;

View File

@ -0,0 +1,29 @@
package ca.uhn.fhir.rest.gclient;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 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%
*/
public interface IBaseQuery<T> {
T where(ICriterion<?> theCriterion);
T and(ICriterion<?> theCriterion);
}

View File

@ -37,4 +37,20 @@ public interface ICreateTyped extends IClientExecutable<ICreateTyped, MethodOutc
*/
ICreateTyped withId(IdDt theId);
/**
* Specifies that the create should be performed as a conditional create
* against a given search URL.
*
* @param theSearchUrl The search URL to use. The format of this URL should be of the form <code>[ResourceType]?[Parameters]</code>,
* for example: <code>Patient?name=Smith&amp;identifier=13.2.4.11.4%7C847366</code>
*
* @since HAPI 0.9 / FHIR DSTU 2
*/
ICreateTyped conditionalByUrl(String theSearchUrl);
/**
* @since HAPI 0.9 / FHIR DSTU 2
*/
ICreateWithQuery conditional();
}

View File

@ -0,0 +1,26 @@
package ca.uhn.fhir.rest.gclient;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 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%
*/
public interface ICreateWithQuery extends IBaseQuery<ICreateWithQueryTyped> {
}

View File

@ -0,0 +1,25 @@
package ca.uhn.fhir.rest.gclient;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 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%
*/
public interface ICreateWithQueryTyped extends ICreateTyped, ICreateWithQuery {
}

View File

@ -30,5 +30,21 @@ public interface IDelete {
IDeleteTyped resourceById(IdDt theId);
IDeleteTyped resourceById(String theResourceType, String theLogicalId);
/**
* Specifies that the delete should be performed as a conditional delete
* against a given search URL.
*
* @param theSearchUrl The search URL to use. The format of this URL should be of the form <code>[ResourceType]?[Parameters]</code>,
* for example: <code>Patient?name=Smith&amp;identifier=13.2.4.11.4%7C847366</code>
*
* @since HAPI 0.9 / FHIR DSTU 2
*/
IDeleteTyped resourceConditionalByUrl(String theSearchUrl);
/**
* @since HAPI 0.9 / FHIR DSTU 2
*/
IDeleteWithQuery resourceConditionalByType(String theResourceType);
}

View File

@ -0,0 +1,25 @@
package ca.uhn.fhir.rest.gclient;
/*
* #%L
* HAPI FHIR - Core Library
* %%
* Copyright (C) 2014 - 2015 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%
*/
public interface IDeleteWithQuery extends IBaseQuery<IDeleteWithQueryTyped> {
}

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