Externalized code now committed

This commit is contained in:
James Agnew 2019-01-13 14:33:14 -06:00
commit 806ab9fac8
2564 changed files with 2278383 additions and 0 deletions

155
.gitignore vendored Normal file
View File

@ -0,0 +1,155 @@
.attach*
/bin
/target
target/
.idea/
.metadata/
RemoteSystemsTempFiles/
Servers/
*.iml
*.log
*.log*
nohup.out
.DS_Store
*.orig
tmp.txt
*.hprof
tmp.txt
ca.uhn.fhir.jpa.entity.ResourceIndexedSearchParamString/
ca.uhn.fhir.jpa.entity.ResourceTable/
ca.uhn.fhir.jpa.entity.TermConcept/
# Vagrant stuff.
.vagrant
/vagrant/build
/vagrant/chef/tmp
jpaserver_derby_files
# Created by https://www.gitignore.io
### Java ###
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
*.class
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*
tbl_bck*.png
### Maven ###
target/
pom.xml.tag
pom.xml.releaseBackup
pom.xml.versionsBackup
pom.xml.next
release.properties
dependency-reduced-pom.xml
buildNumber.properties
### Vim ###
[._]*.s[a-w][a-z]
[._]s[a-w][a-z]
*.un~
Session.vim
.netrwhist
*~
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm
*.iml
## Directory-based project format:
.idea/
# if you remove the above rule, at least ignore the following:
# User-specific stuff:
# .idea/workspace.xml
# .idea/tasks.xml
# .idea/dictionaries
# Sensitive or high-churn files:
# .idea/dataSources.ids
# .idea/dataSources.xml
# .idea/sqlDataSources.xml
# .idea/dynamic.xml
# .idea/uiDesigner.xml
# Gradle:
# .idea/gradle.xml
# .idea/libraries
# Mongo Explorer plugin:
# .idea/mongoSettings.xml
## File-based project format:
*.ipr
*.iws
## Plugin-specific files:
# IntelliJ
/out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
### Eclipse ###
*.pydevproject
.metadata
.gradle
bin/
tmp/
*.tmp
*.bak
*.swp
*~.nib
local.properties
.loadpath
*.hprof
# External tool builders
.externalToolBuilders/
# Locally stored "Eclipse launch configurations"
*.launch
# CDT-specific
.cproject
# JDT-specific (Eclipse Java Development Tools)
**/.settings
**/.target
**/.project
**/.classpath
**/.factorypath
**/.springBeans
# PDT-specific
.buildpath
# sbteclipse plugin
.target
# TeXlipse plugin
.texlipse

201
LICENSE.txt Normal file
View File

@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.

18
README.md Normal file
View File

@ -0,0 +1,18 @@
HAPI FHIR - HL7 FHIR Core Artifacts
===================================
# Building this Project
This project uses [Apache Maven](http://maven.apache.org) to build. To build:
```
mvn install
```
Note that unit tests will run, but are currently not set to fail the build as they do not all pass. This is being worked on.
To skip unit tests:
```
mvn -Dmaven.test.skip install
```

View File

@ -0,0 +1,69 @@
<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>org.hl7.fhir</groupId>
<artifactId>org.hl7.fhir.core</artifactId>
<version>3.7.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>org.hl7.fhir.convertors</artifactId>
<packaging>jar</packaging>
<dependencies>
<!-- HAPI Dependencies -->
<dependency>
<groupId>ca.uhn.hapi.fhir</groupId>
<artifactId>hapi-fhir-base</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.hl7.fhir</groupId>
<artifactId>org.hl7.fhir.utilities</artifactId>
<version>${project.version}</version>
</dependency>
<!-- FHIR Versions -->
<dependency>
<groupId>org.hl7.fhir</groupId>
<artifactId>org.hl7.fhir.dstu2</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.hl7.fhir</groupId>
<artifactId>org.hl7.fhir.dstu2016may</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.hl7.fhir</groupId>
<artifactId>org.hl7.fhir.dstu3</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.hl7.fhir</groupId>
<artifactId>org.hl7.fhir.r4</artifactId>
<version>${project.version}</version>
</dependency>
<!-- UCUM -->
<dependency>
<groupId>org.fhir</groupId>
<artifactId>ucum</artifactId>
<version>1.0.2</version>
<optional>true</optional>
</dependency>
<!-- Java Parser -->
<dependency>
<groupId>com.google.code.javaparser</groupId>
<artifactId>javaparser</artifactId>
<version>1.0.11</version>
<optional>true</optional>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,243 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!--
#%L
org.hl7.fhir.convertors
%%
Copyright (C) 2014 - 2019 Health Level 7
%%
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%
-->
<!-- WARNING: Eclipse auto-generated file.
Any modifications will be overwritten.
To include a user specific buildfile here, simply create one in the same
directory with the processing instruction <?eclipse.ant.import?>
as the first entry and export the buildfile again. --><project basedir="." default="build" name="org.hl7.fhir.convertors">
<property environment="env"/>
<property name="org.hl7.fhir.tools.location" value="../../../tools/java/org.hl7.fhir.tools.core"/>
<property name="ECLIPSE_HOME" value="../../../../../../tools/eclipse/eclipse/"/>
<property name="org.hl7.fhir.utilities.location" value="../org.hl7.fhir.utilities"/>
<property name="org.hl7.fhir.dstu3.location" value="../../../implementations/java/org.hl7.fhir.dstu3"/>
<property name="org.hl7.fhir.r4.location" value="../../../implementations/java/org.hl7.fhir.r4"/>
<property name="org.hl7.fhir.dstu2.location" value="../org.hl7.fhir.dstu2"/>
<property name="org.hl7.fhir.dstu14.location" value="../org.hl7.fhir.dstu2016may"/>
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.8"/>
<property name="source" value="1.8"/>
<path id="org.hl7.fhir.utilities.classpath">
<pathelement location="${org.hl7.fhir.utilities.location}/bin"/>
<pathelement location="${org.hl7.fhir.utilities.location}/../../../tools/java/imports/xpp3_xpath-1.1.4c.jar"/>
<pathelement location="${org.hl7.fhir.utilities.location}/../../../tools/java/imports/xpp3-1.1.4c.jar"/>
<pathelement location="${org.hl7.fhir.utilities.location}/../../../tools/java/imports/commons-io-1.2.jar"/>
<pathelement location="${org.hl7.fhir.utilities.location}/../../../tools/java/imports/commons-codec-1.9.jar"/>
<pathelement location="${org.hl7.fhir.utilities.location}/../../../tools/java/imports/Saxon-HE-9.5.1-5.jar"/>
<pathelement location="${org.hl7.fhir.utilities.location}/../../../tools/java/imports/txtmark-0.11.jar"/>
<pathelement location="${org.hl7.fhir.utilities.location}/../../../tools/java/imports/hapi-fhir-base-3.4.0.jar"/>
</path>
<path id="org.hl7.fhir.dstu2.classpath">
<pathelement location="${org.hl7.fhir.dstu2.location}/bin"/>
<path refid="org.hl7.fhir.utilities.classpath"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/commons-codec-1.9.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/commons-discovery-0.2.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/commons-httpclient-3.0.1.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/commons-io-1.2.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/commons-logging-1.1.1.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/commons-logging-api-1.1.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/commons-lang3-3.3.2.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/xpp3_xpath-1.1.4c.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/xpp3-1.1.4c.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/junit-4.11.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/hamcrest-core-1.3.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/fluent-hc-4.2.3.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/httpclient-4.2.3.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/httpcore-4.2.2.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/httpmime-4.2.3.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/jdom-1.1.3.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/gson-2.3.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/txtmark-0.11.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/rhino-1.8R4.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/jackson-core-2.5.2.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/jackson-databind-2.5.2.jar"/>
<pathelement location="${org.hl7.fhir.dstu2.location}/../../../tools/java/imports/Saxon-HE-9.5.1-5.jar"/>
<pathelement location="../../../tools/java/imports/ucum-1.0-SNAPSHOT.jar"/>
</path>
<path id="org.hl7.fhir.dstu14.classpath">
<pathelement location="${org.hl7.fhir.dstu14.location}/bin"/>
<path refid="org.hl7.fhir.utilities.classpath"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/commons-codec-1.9.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/commons-discovery-0.2.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/commons-httpclient-3.0.1.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/commons-io-1.2.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/commons-logging-1.1.1.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/commons-logging-api-1.1.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/commons-lang3-3.3.2.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/xpp3_xpath-1.1.4c.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/xpp3-1.1.4c.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/junit-4.11.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/hamcrest-core-1.3.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/fluent-hc-4.2.3.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/httpclient-4.2.3.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/httpcore-4.2.2.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/httpmime-4.2.3.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/jdom-1.1.3.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/gson-2.3.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/txtmark-0.11.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/rhino-1.8R4.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/jackson-core-2.5.2.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/jackson-databind-2.5.2.jar"/>
<pathelement location="${org.hl7.fhir.dstu14.location}/../../../tools/java/imports/Saxon-HE-9.5.1-5.jar"/>
</path>
<path id="JUnit 4.libraryclasspath">
<pathelement location="../../../../../../Users/Grahame Grieve/.p2/pool/plugins/org.junit_4.12.0.v201504281640/junit.jar"/>
<pathelement location="../../../../../../Users/Grahame Grieve/.p2/pool/plugins/org.hamcrest.core_1.3.0.v201303031735.jar"/>
</path>
<path id="org.hl7.fhir.dstu3.classpath">
<pathelement location="${org.hl7.fhir.dstu3.location}/bin"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/commons-codec-1.9.jar"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/xpp3_xpath-1.1.4c.jar"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/xpp3-1.1.4c.jar"/>
<path refid="org.hl7.fhir.utilities.classpath"/>
<path refid="JUnit 4.libraryclasspath"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/commons-httpclient-3.0.1.jar"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/httpclient-4.2.3.jar"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/httpcore-4.2.2.jar"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/httpmime-4.2.3.jar"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/commons-io-1.2.jar"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/commons-lang3-3.3.2.jar"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/gson-2.3.jar"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/txtmark-0.11.jar"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/rhino-1.8R4.jar"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/pegdown-1.5.0.jar"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/commons-logging-1.1.1.jar"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/commons-logging-api-1.1.jar"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/hapi-fhir-base-3.4.0.jar"/>
<pathelement location="${org.hl7.fhir.dstu3.location}/../../../tools/java/imports/ST4-4.0.7.jar"/>
</path>
<path id="org.hl7.fhir.r4.classpath">
<pathelement location="${org.hl7.fhir.r4.location}/bin"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/commons-codec-1.9.jar"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/xpp3_xpath-1.1.4c.jar"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/xpp3-1.1.4c.jar"/>
<path refid="org.hl7.fhir.utilities.classpath"/>
<path refid="JUnit 4.libraryclasspath"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/commons-httpclient-3.0.1.jar"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/httpclient-4.2.3.jar"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/httpcore-4.2.2.jar"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/httpmime-4.2.3.jar"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/commons-io-1.2.jar"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/commons-lang3-3.3.2.jar"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/gson-2.3.jar"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/txtmark-0.11.jar"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/rhino-1.8R4.jar"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/pegdown-1.5.0.jar"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/commons-logging-1.1.1.jar"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/commons-logging-api-1.1.jar"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/hapi-fhir-base-3.4.0.jar"/>
<pathelement location="${org.hl7.fhir.r4.location}/../../../tools/java/imports/ST4-4.0.7.jar"/>
</path>
<path id="org.hl7.fhir.convertors.classpath">
<pathelement location="bin"/>
<path refid="org.hl7.fhir.utilities.classpath"/>
<pathelement location="../../../tools/java/imports/gson-2.3.jar"/>
<pathelement location="../../../tools/java/imports/xpp3_xpath-1.1.4c.jar"/>
<pathelement location="../../../tools/java/imports/xpp3-1.1.4c.jar"/>
<pathelement location="../../../tools/java/imports/commons-logging-1.1.1.jar"/>
<pathelement location="../../../tools/java/imports/commons-logging-api-1.1.jar"/>
<pathelement location="../../../tools/java/imports/commons-io-1.2.jar"/>
<pathelement location="../../../tools/java/imports/commons-lang3-3.3.2.jar"/>
<pathelement location="../../../tools/java/imports/commons-httpclient-3.0.1.jar"/>
<pathelement location="../../../tools/java/imports/javaparser-1.0.11.jar"/>
<path refid="org.hl7.fhir.dstu14.classpath"/>
<path refid="org.hl7.fhir.dstu2.classpath"/>
<path refid="org.hl7.fhir.dstu3.classpath"/>
<path refid="org.hl7.fhir.r4.classpath"/>
<pathelement location="../../../tools/java/imports/hapi-fhir-base-3.4.0.jar"/>
<pathelement location="../../../tools/java/imports/commons-codec-1.9.jar"/>
<pathelement location="../../../tools/java/imports/ucum-1.0-SNAPSHOT.jar"/>
</path>
<target name="init">
<mkdir dir="bin"/>
<copy includeemptydirs="false" todir="bin">
<fileset dir="src">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
<target name="clean">
<delete dir="bin"/>
</target>
<target depends="clean" name="cleanall">
<ant antfile="build.xml" dir="${org.hl7.fhir.utilities.location}" inheritAll="false" target="clean"/>
<ant antfile="build.xml" dir="${org.hl7.fhir.dstu3.location}" inheritAll="false" target="clean"/>
<ant antfile="build.xml" dir="${org.hl7.fhir.r4.location}" inheritAll="false" target="clean"/>
<ant antfile="build.xml" dir="${org.hl7.fhir.dstu2.location}" inheritAll="false" target="clean"/>
<ant antfile="build.xml" dir="${org.hl7.fhir.dstu14.location}" inheritAll="false" target="clean"/>
</target>
<target depends="build-subprojects,build-project" name="build"/>
<target name="build-subprojects">
<ant antfile="build.xml" dir="${org.hl7.fhir.utilities.location}" inheritAll="false" target="build-project">
<propertyset>
<propertyref name="build.compiler"/>
</propertyset>
</ant>
<ant antfile="build.xml" dir="${org.hl7.fhir.dstu3.location}" inheritAll="false" target="build-project">
<propertyset>
<propertyref name="build.compiler"/>
</propertyset>
</ant>
<ant antfile="build.xml" dir="${org.hl7.fhir.r4.location}" inheritAll="false" target="build-project">
<propertyset>
<propertyref name="build.compiler"/>
</propertyset>
</ant>
<ant antfile="build.xml" dir="${org.hl7.fhir.dstu2.location}" inheritAll="false" target="build-project">
<propertyset>
<propertyref name="build.compiler"/>
</propertyset>
</ant>
<ant antfile="build.xml" dir="${org.hl7.fhir.dstu14.location}" inheritAll="false" target="build-project">
<propertyset>
<propertyref name="build.compiler"/>
</propertyset>
</ant>
</target>
<target depends="init" name="build-project">
<echo message="${ant.project.name}: ${ant.file}"/>
<javac debug="true" debuglevel="${debuglevel}" destdir="bin" includeantruntime="false" source="${source}" target="${target}">
<src path="src"/>
<classpath refid="org.hl7.fhir.convertors.classpath"/>
</javac>
</target>
<target description="Build all projects which reference this project. Useful to propagate changes." name="build-refprojects">
<ant antfile="build.xml" dir="${org.hl7.fhir.tools.location}" inheritAll="false" target="clean"/>
<ant antfile="build.xml" dir="${org.hl7.fhir.tools.location}" inheritAll="false" target="build">
<propertyset>
<propertyref name="build.compiler"/>
</propertyset>
</ant>
</target>
<target description="copy Eclipse compiler jars to ant lib directory" name="init-eclipse-compiler">
<copy todir="${ant.library.dir}">
<fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar"/>
</copy>
<unzip dest="${ant.library.dir}">
<patternset includes="jdtCompilerAdapter.jar"/>
<fileset dir="${ECLIPSE_HOME}/plugins" includes="org.eclipse.jdt.core_*.jar"/>
</unzip>
</target>
<target description="compile project with Eclipse compiler" name="build-eclipse-compiler">
<property name="build.compiler" value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
<antcall target="build"/>
</target>
</project>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
#%L
org.hl7.fhir.convertors
%%
Copyright (C) 2014 - 2019 Health Level 7
%%
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%
-->
<Bundle xmlns="http://hl7.org/fhir">
<id value="urn:oid:2.16.840.1.113883.19.5.99999.1::TT988"/>
<meta>
<lastUpdated value="2014-11-29T23:54:58.955+11:00"/>
<tag/>
</meta>
</Bundle>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,462 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;
import org.hl7.fhir.convertors.ExtensionDefinitionGenerator.StringReplacement;
import org.hl7.fhir.dstu3.elementmodel.Manager.FhirFormat;
import org.hl7.fhir.exceptions.DefinitionException;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.exceptions.FHIRFormatError;
import org.hl7.fhir.r4.model.Enumerations.FHIRVersion;
import org.hl7.fhir.r4.model.Enumerations.PublicationStatus;
import org.hl7.fhir.r4.model.ImplementationGuide.ImplementationGuideDependsOnComponent;
import org.hl7.fhir.r4.model.ImplementationGuide.SPDXLicense;
import org.hl7.fhir.r4.utils.NPMPackageGenerator;
import org.hl7.fhir.r4.utils.NPMPackageGenerator.Category;
import org.hl7.fhir.r4.conformance.ProfileUtilities;
import org.hl7.fhir.r4.context.BaseWorkerContext;
import org.hl7.fhir.r4.context.SimpleWorkerContext;
import org.hl7.fhir.r4.formats.JsonParser;
import org.hl7.fhir.r4.model.Constants;
import org.hl7.fhir.r4.model.ContactDetail;
import org.hl7.fhir.r4.model.ElementDefinition;
import org.hl7.fhir.r4.model.ElementDefinition.TypeRefComponent;
import org.hl7.fhir.r4.model.Enumeration;
import org.hl7.fhir.r4.model.Resource;
import org.hl7.fhir.r4.model.StructureDefinition;
import org.hl7.fhir.r4.model.StructureDefinition.StructureDefinitionKind;
import org.hl7.fhir.r4.model.StructureDefinition.TypeDerivationRule;
import org.hl7.fhir.r4.model.UriType;
import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.cache.NpmPackage;
import org.hl7.fhir.utilities.cache.PackageCacheManager;
import org.hl7.fhir.utilities.cache.PackageGenerator.PackageType;
import org.hl7.fhir.utilities.cache.ToolsVersion;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
public class ExtensionDefinitionGenerator {
public class StringReplacement {
public String source;
public String replacement;
public StringReplacement(String source, String replacement) {
super();
this.source = source;
this.replacement = replacement;
}
}
public static void main(String[] args) throws IOException, FHIRException {
if (args.length == 0) {
System.out.println("Extension Generator");
System.out.println("===================");
System.out.println("");
System.out.println("See http://hl7.org/fhir/versions.html#extensions. This generates the packages");
System.out.println("");
System.out.println("parameters: -srcver [version] -tgtver [version] -package [filename]");
System.out.println("");
System.out.println("srcver: the source version to load");
System.out.println("tgtver: the version to generate extension definitions for");
System.out.println("package: the package to produce");
} else {
ExtensionDefinitionGenerator self = new ExtensionDefinitionGenerator();
self.setSourceVersion(FHIRVersion.fromCode(getNamedParam(args, "-srcver")));
self.setTargetVersion(FHIRVersion.fromCode(getNamedParam(args, "-tgtver")));
self.setFilename(getNamedParam(args, "-package"));
self.generate();
}
}
private static String getNamedParam(String[] args, String param) {
boolean found = false;
for (String a : args) {
if (found)
return a;
if (a.equals(param)) {
found = true;
}
}
throw new Error("Unable to find parameter "+param);
}
private FHIRVersion sourceVersion;
private FHIRVersion targetVersion;
private String filename;
private StructureDefinition extbase;
private ElementDefinition extv;
private ProfileUtilities pu;
private BaseWorkerContext context;
public FHIRVersion getSourceVersion() {
return sourceVersion;
}
public void setSourceVersion(FHIRVersion sourceVersion) {
this.sourceVersion = sourceVersion;
}
public FHIRVersion getTargetVersion() {
return targetVersion;
}
public void setTargetVersion(FHIRVersion targetVersion) {
this.targetVersion = targetVersion;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
private void generate() throws IOException, FHIRException {
List<StructureDefinition> definitions = loadSource();
List<StructureDefinition> extensions = buildExtensions(definitions);
for (StructureDefinition ext : extensions)
pu.generateSnapshot(extbase, ext, ext.getUrl(), ext.getName());
savePackage(extensions);
}
private List<StructureDefinition> buildExtensions(List<StructureDefinition> definitions) throws DefinitionException, FHIRException {
Set<String> types = new HashSet<>();
List<StructureDefinition> list = new ArrayList<>();
for (StructureDefinition type : definitions)
if (type.getDerivation() == TypeDerivationRule.SPECIALIZATION && !type.getName().contains(".") && !types.contains(type.getName()) && type.getKind() != StructureDefinitionKind.PRIMITIVETYPE && !Utilities.existsInList(type.getName(), "Extension", "Narrative")) {
types.add(type.getName());
buildExtensions(type, list);
}
return list;
}
private void buildExtensions(StructureDefinition type, List<StructureDefinition> list) throws DefinitionException, FHIRException {
for (ElementDefinition ed : type.getDifferential().getElement()) {
if (ed.getPath().contains(".")) {
if (!ed.getPath().endsWith(".extension") && !ed.getPath().endsWith(".modifierExtension")) {
StructureDefinition ext = generateExtension(type, ed);
if (ext != null) {
list.add(ext);
context.cacheResource(ext);
}
}
}
}
}
private StructureDefinition generateExtension(StructureDefinition type, ElementDefinition ed) throws DefinitionException, FHIRException {
StructureDefinition ext = new StructureDefinition();
ext.setId("extension-"+ed.getPath().replace("[x]", ""));
ext.setUrl("http://hl7.org/fhir/"+sourceVersion.toCode(3)+"/StructureDefinition/"+ext.getId());
if (ext.getId().length() > 64)
ext.setId(contract(ext.getId()));
ext.setVersion(sourceVersion.toCode());
ext.setName("ExtensionR"+sourceVersion.toCode(1)+ed.getPath().replace(".", ""));
ext.setTitle("Extension definition for R"+sourceVersion.toCode(1)+" element " +ed.getPath());
ext.setStatus(PublicationStatus.ACTIVE);
ext.setDate(type.getDate());
ext.setFhirVersion(type.getFhirVersion());
ext.setDescription(ed.getDefinition());
ext.setKind(StructureDefinitionKind.COMPLEXTYPE);
ext.setBaseDefinition("http://hl7.org/fhir/StructureDefinition/Extension");
ext.setDerivation(TypeDerivationRule.CONSTRAINT);
if (ed.hasType() && ("Element".equals(ed.getType().get(0).getCode()) || "BackboneElement".equals(ed.getType().get(0).getCode()))) {
ElementDefinition v = ed.copy();
v.setPath("Extension");
v.getType().clear();
v.setIsSummaryElement(null);
ext.getDifferential().addElement(v);
List<ElementDefinition> children = ProfileUtilities.getChildList(type, ed);
for (ElementDefinition child : children) {
String n = tail(child.getPath());
if (!Utilities.existsInList(n, "id", "extension", "modifierExtension") && !hasNonValidType(child)) {
v = child.copy();
v.setId("Extension.extension:"+n);
v.setPath("Extension.extension");
v.setSliceName(n);
v.getType().clear();
v.setIsSummaryElement(null);
v.addType().setCode("Extension").addProfile("http://hl7.org/fhir/"+sourceVersion.toCode(3)+"/StructureDefinition/extension-"+child.getPath().replace("[x]", ""));
ext.getDifferential().addElement(v);
}
}
ext.getDifferential().addElement(genElement("Extension.url").setFixed(new UriType(ext.getUrl())));
ext.getDifferential().addElement(genElement("Extension.value[x]").setMax("0"));
} else if (ed.hasType() && Utilities.existsInList(ed.getType().get(0).getCode(), "Resource", "Narrative")) {
return null;
} else if (ed.hasType() && !goesInExtension(ed.getType().get(0).getCode())) {
ElementDefinition v = ed.copy();
v.setPath("Extension");
v.getType().clear();
v.setIsSummaryElement(null);
ext.getDifferential().addElement(v);
List<ElementDefinition> children = ProfileUtilities.getChildList(type, ed);
for (ElementDefinition child : children) {
String n = tail(child.getPath());
if (!Utilities.existsInList(n, "id", "extension", "modifierExtension") && !hasNonValidType(child)) {
v = child.copy();
v.setId("Extension.extension:"+n);
v.setPath("Extension.extension");
v.setSliceName(n);
v.getType().clear();
v.setIsSummaryElement(null);
v.addType().setCode("Extension").addProfile("http://hl7.org/fhir/"+sourceVersion.toCode(3)+"/StructureDefinition/extension-"+child.getPath().replace("[x]", ""));
ext.getDifferential().addElement(v);
}
}
ext.getDifferential().addElement(genElement("Extension.url").setFixed(new UriType(ext.getUrl())));
ext.getDifferential().addElement(genElement("Extension.value[x]").setMax("0"));
} else {
// simple type...
ElementDefinition v = ed.copy();
v.setPath("Extension");
v.getType().clear();
v.setIsSummaryElement(null);
ext.getDifferential().addElement(v);
ext.getDifferential().addElement(genElement("Extension.extension").setMax("0"));
ext.getDifferential().addElement(genElement("Extension.url").setFixed(new UriType(ext.getUrl())));
v = ed.copy();
v.setPath("Extension.value[x]");
v.setId("Extension.value");
v.setMax("1");
v.setIsSummaryElement(null);
ext.getDifferential().addElement(v);
}
return ext;
}
private boolean hasNonValidType(ElementDefinition ed) {
return ed.hasType() && Utilities.existsInList(ed.getType().get(0).getCode(), "Resource", "Narrative");
}
private boolean goesInExtension(String code) {
if (code == null)
return true;
for (TypeRefComponent tr : extv.getType()) {
if (code.equals(tr.getCode()))
return true;
}
return false;
}
private String tail(String path) {
return path.substring(path.lastIndexOf(".")+1);
}
private ElementDefinition genElement(String path) {
return new ElementDefinition().setPath(path);
}
private String contract(String id) {
List<StringReplacement> abbrevs = new ArrayList<>();
abbrevs.add(new StringReplacement("AdverseEvent", "AE"));
abbrevs.add(new StringReplacement("CoverageEligibilityResponse", "CERsp"));
abbrevs.add(new StringReplacement("CoverageEligibilityRequest", "CEReq"));
abbrevs.add(new StringReplacement("EffectEvidenceSynthesis", "EES"));
abbrevs.add(new StringReplacement("ExplanationOfBenefit", "EoB"));
abbrevs.add(new StringReplacement("ImmunizationRecommendation", "IR"));
abbrevs.add(new StringReplacement("MeasureReport", "MR"));
abbrevs.add(new StringReplacement("MedicationKnowledge", "MK"));
abbrevs.add(new StringReplacement("CapabilityStatement", "CS"));
abbrevs.add(new StringReplacement("ChargeItemDefinition", "CID"));
abbrevs.add(new StringReplacement("ClaimResponse", "CR"));
abbrevs.add(new StringReplacement("InsurancePlan", "IP"));
abbrevs.add(new StringReplacement("MedicationRequest", "MR"));
abbrevs.add(new StringReplacement("MedicationOrder", "MO"));
abbrevs.add(new StringReplacement("MedicationDispense", "MD"));
abbrevs.add(new StringReplacement("NutritionOrder", "NO"));
abbrevs.add(new StringReplacement("MedicinalProductAuthorization", "MPA"));
abbrevs.add(new StringReplacement("MedicinalProductContraindication", "MPC"));
abbrevs.add(new StringReplacement("MedicinalProductIngredient", "MPI"));
abbrevs.add(new StringReplacement("MedicinalProductPharmaceutical", "MPP"));
abbrevs.add(new StringReplacement("MedicinalProduct", "MP"));
abbrevs.add(new StringReplacement("ResearchElementDefinition", "RED"));
abbrevs.add(new StringReplacement("RiskEvidenceSynthesis", "RES"));
abbrevs.add(new StringReplacement("ObservationDefinition", "OD"));
abbrevs.add(new StringReplacement("SubstanceReferenceInformation", "SRI"));
abbrevs.add(new StringReplacement("SubstanceSourceMaterial", "SSM"));
abbrevs.add(new StringReplacement("SpecimenDefinition", "SD"));
abbrevs.add(new StringReplacement("SubstanceSpecification", "SS"));
abbrevs.add(new StringReplacement("SubstancePolymer", "SP"));
abbrevs.add(new StringReplacement("TerminologyCapabilities", "TC"));
abbrevs.add(new StringReplacement("VerificationResult", "VR"));
abbrevs.add(new StringReplacement("EligibilityResponse", "ERsp"));
abbrevs.add(new StringReplacement("ExpansionProfile", "EP"));
abbrevs.add(new StringReplacement("ImagingObjectSelection", "IOS"));
abbrevs.add(new StringReplacement("administrationGuidelines.patientCharacteristics", "ag.pc"));
abbrevs.add(new StringReplacement("manufacturingBusinessOperation", "mbo"));
abbrevs.add(new StringReplacement("strength.referenceStrength", "strength.rs"));
abbrevs.add(new StringReplacement("MPP.routeOfAdministration", "MPP.roa"));
abbrevs.add(new StringReplacement("supportingInformation", "si"));
abbrevs.add(new StringReplacement("structuralRepresentation", "sr"));
abbrevs.add(new StringReplacement("compareToSourceExpression", "ctse"));
abbrevs.add(new StringReplacement("TestScript.setup.action.assert", "TestScript.s.a.a"));
for (StringReplacement s : abbrevs)
if (id.contains(s.source))
id = id.replace(s.source,s.replacement);
if (id.length() > 64)
throw new Error("Still too long: "+id);
return id;
}
private String timezone() {
TimeZone tz = TimeZone.getDefault();
Calendar cal = GregorianCalendar.getInstance(tz);
int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
offset = (offsetInMillis >= 0 ? "+" : "-") + offset;
return offset;
}
private void savePackage(List<StructureDefinition> extensions) throws FHIRException, IOException {
JsonObject npm = new JsonObject();
npm.addProperty("name", "hl7.fhir.extensions.r"+sourceVersion.toCode(1));
npm.addProperty("version", targetVersion.toCode(3));
npm.addProperty("tools-version", ToolsVersion.TOOLS_VERSION);
npm.addProperty("type", PackageType.IG.getCode());
npm.addProperty("license", SPDXLicense.CC01_0.toCode());
npm.addProperty("canonical", "http://hl7.org/fhir/"+sourceVersion.toCode(3)+"/extensions/"+targetVersion.toCode(3));
npm.addProperty("url", "http://hl7.org/fhir/"+sourceVersion.toCode(3)+"/extensions/"+targetVersion.toCode(3));
npm.addProperty("title", "Extension Definitions for representing elements from "+sourceVersion.toCode()+" in "+targetVersion.toCode());
npm.addProperty("description", "Extension Definitions for representing elements from "+sourceVersion.toCode()+" in "+targetVersion.toCode()+" built "+new SimpleDateFormat("EEE, MMM d, yyyy HH:mmZ", new Locale("en", "US")).format(Calendar.getInstance().getTime())+timezone()+")");
JsonObject dep = new JsonObject();
npm.add("dependencies", dep);
dep.addProperty("hl7.fhir.core", targetVersion.toCode());
npm.addProperty("author", "FHIR Project");
JsonArray m = new JsonArray();
JsonObject md = new JsonObject();
m.add(md);
md.addProperty("name", "FHIR Project");
md.addProperty("url", "http://hl7.org/fhir");
NPMPackageGenerator pi = new NPMPackageGenerator(filename, npm);
for (StructureDefinition sd : extensions) {
byte[] cnt = saveResource(sd, targetVersion);
pi.addFile(Category.RESOURCE, "StructureDefinition-"+sd.getId()+".json", cnt);
}
pi.finish();
}
private List<StructureDefinition> loadSource() throws IOException, FHIRException {
List<StructureDefinition> list = new ArrayList<>();
PackageCacheManager pcm = new PackageCacheManager(true, ToolsVersion.TOOLS_VERSION);
NpmPackage npm = pcm.loadPackageCache("hl7.fhir.core", sourceVersion.toCode());
if (sourceVersion == FHIRVersion._4_0_0)
context = SimpleWorkerContext.fromPackage(npm);
else if (sourceVersion == FHIRVersion._3_0_1)
context = SimpleWorkerContext.fromPackage(npm, new R3ToR4Loader());
else if (sourceVersion == FHIRVersion._1_4_0)
context = SimpleWorkerContext.fromPackage(npm, new R2016MayToR4Loader());
else if (sourceVersion == FHIRVersion._1_0_2)
context = SimpleWorkerContext.fromPackage(npm, new R2ToR4Loader());
pu = new ProfileUtilities(context, null, null);
for (String fn : npm.list("package")) {
if (fn.endsWith(".json") && fn.startsWith("StructureDefinition-")) {
list.add((StructureDefinition) loadResource(npm.load("package", fn), sourceVersion));
}
}
for (StructureDefinition sd : list)
if (sd.getName().equals("Extension")) {
extbase = sd;
extv = extbase.getSnapshot().getElement().get(extbase.getSnapshot().getElement().size() -1);
}
return list;
}
private byte[] saveResource(Resource resource, FHIRVersion v) throws IOException, FHIRException {
if (v == FHIRVersion._3_0_1) {
org.hl7.fhir.dstu3.model.Resource res = VersionConvertor_30_40.convertResource(resource, true);
return new org.hl7.fhir.dstu3.formats.JsonParser().composeBytes(res);
} else if (v == FHIRVersion._1_4_0) {
org.hl7.fhir.dstu2016may.model.Resource res = VersionConvertor_14_40.convertResource(resource);
return new org.hl7.fhir.dstu2016may.formats.JsonParser().composeBytes(res);
} else if (v == FHIRVersion._1_0_2) {
VersionConvertorAdvisor40 advisor = new IGR2ConvertorAdvisor();
org.hl7.fhir.dstu2.model.Resource res = new VersionConvertor_10_40(advisor ).convertResource(resource);
return new org.hl7.fhir.dstu2.formats.JsonParser().composeBytes(res);
} else if (v == FHIRVersion._4_0_0) {
return new JsonParser().composeBytes(resource);
} else
throw new Error("Unsupported version "+v);
}
private Resource loadResource(InputStream inputStream, FHIRVersion v) throws IOException, FHIRException {
if (v == FHIRVersion._3_0_1) {
org.hl7.fhir.dstu3.model.Resource res = new org.hl7.fhir.dstu3.formats.JsonParser().parse(inputStream);
return VersionConvertor_30_40.convertResource(res, true);
} else if (v == FHIRVersion._1_4_0) {
org.hl7.fhir.dstu2016may.model.Resource res = new org.hl7.fhir.dstu2016may.formats.JsonParser().parse(inputStream);
return VersionConvertor_14_40.convertResource(res);
} else if (v == FHIRVersion._1_0_2) {
org.hl7.fhir.dstu2.model.Resource res = new org.hl7.fhir.dstu2.formats.JsonParser().parse(inputStream);
VersionConvertorAdvisor40 advisor = new IGR2ConvertorAdvisor();
return new VersionConvertor_10_40(advisor ).convertResource(res);
} else if (v == FHIRVersion._4_0_0) {
return new JsonParser().parse(inputStream);
} else
throw new Error("Unsupported version "+v);
}
}

View File

@ -0,0 +1,95 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import org.hl7.fhir.dstu2.model.Resource;
import org.hl7.fhir.dstu3.formats.IParser.OutputStyle;
import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent;
import org.hl7.fhir.dstu3.model.Bundle.BundleType;
import org.hl7.fhir.dstu3.model.CodeSystem;
import org.hl7.fhir.dstu3.model.ValueSet;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.utilities.Utilities;
public class IGPackConverter102 implements VersionConvertorAdvisor30 {
public static void main(String[] args) throws Exception {
new IGPackConverter102().process();
}
private Bundle cslist = new Bundle();
private void process() throws FileNotFoundException, IOException, FHIRException {
initCSList();
for (String s : new File("C:\\temp\\igpack2").list()) {
if (s.endsWith(".xml") && !s.startsWith("z-") && !Utilities.existsInList(s, "expansions.xml", "v3-codesystems.xml", "v2-tables.xml")) {
System.out.println("process "+s);
org.hl7.fhir.dstu2.formats.XmlParser xp = new org.hl7.fhir.dstu2.formats.XmlParser();
org.hl7.fhir.dstu2.model.Resource r10 = xp.parse(new FileInputStream("C:\\temp\\igpack2\\"+s));
org.hl7.fhir.dstu3.model.Resource r17 = new VersionConvertor_10_30(this).convertResource(r10);
org.hl7.fhir.dstu3.formats.XmlParser xc = new org.hl7.fhir.dstu3.formats.XmlParser();
xc.setOutputStyle(OutputStyle.PRETTY);
xc.compose(new FileOutputStream("C:\\temp\\igpack2\\"+s), r17);
}
}
System.out.println("save codesystems");
org.hl7.fhir.dstu3.formats.XmlParser xc = new org.hl7.fhir.dstu3.formats.XmlParser();
xc.setOutputStyle(OutputStyle.PRETTY);
xc.compose(new FileOutputStream("C:\\temp\\igpack2\\codesystems.xml"), cslist);
System.out.println("done");
}
private void initCSList() {
cslist.setId("codesystems");
cslist.setType(BundleType.COLLECTION);
cslist.getMeta().setLastUpdated(new Date());
}
@Override
public boolean ignoreEntry(BundleEntryComponent src) {
return false;
}
@Override
public Resource convert(org.hl7.fhir.dstu3.model.Resource resource) throws FHIRException {
return null;
}
@Override
public void handleCodeSystem(CodeSystem tgtcs, ValueSet vs) {
cslist.addEntry().setFullUrl(tgtcs.getUrl()).setResource(tgtcs);
}
@Override
public CodeSystem getCodeSystem(ValueSet src) {
return null;
}
}

View File

@ -0,0 +1,48 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.hl7.fhir.dstu3.formats.IParser.OutputStyle;
public class IGPackConverter140 {
public static void main(String[] args) throws Exception {
for (String s : new File("C:\\temp\\igpack").list()) {
// if (s.endsWith(".xml") && !s.contains("z-")) {
if (s.equals("expansions.xml")) {
System.out.println("process "+s);
org.hl7.fhir.dstu2016may.formats.XmlParser xp = new org.hl7.fhir.dstu2016may.formats.XmlParser();
org.hl7.fhir.dstu2016may.model.Resource r14 = xp.parse(new FileInputStream("C:\\temp\\igpack\\"+s));
org.hl7.fhir.dstu3.model.Resource r17 = VersionConvertor_14_30.convertResource(r14);
org.hl7.fhir.dstu3.formats.XmlParser xc = new org.hl7.fhir.dstu3.formats.XmlParser();
xc.setOutputStyle(OutputStyle.PRETTY);
xc.compose(new FileOutputStream("C:\\temp\\igpack\\z-"+s), r17);
}
}
System.out.println("done");
}
}

View File

@ -0,0 +1,62 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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.dstu2.model.Resource;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent;
import org.hl7.fhir.r4.model.CodeSystem;
import org.hl7.fhir.r4.model.ValueSet;
public class IGR2ConvertorAdvisor implements VersionConvertorAdvisor40 {
@Override
public boolean ignoreEntry(BundleEntryComponent src) {
return false;
}
@Override
public Resource convertR2(org.hl7.fhir.r4.model.Resource resource) throws FHIRException {
return null;
}
@Override
public org.hl7.fhir.dstu2016may.model.Resource convertR2016May(org.hl7.fhir.r4.model.Resource resource) throws FHIRException {
return null;
}
@Override
public org.hl7.fhir.dstu3.model.Resource convertR3(org.hl7.fhir.r4.model.Resource resource) throws FHIRException {
return null;
}
@Override
public void handleCodeSystem(CodeSystem cs, ValueSet vs) {
cs.setId(vs.getId());
}
@Override
public CodeSystem getCodeSystem(ValueSet src) {
return null;
}
}

View File

@ -0,0 +1,151 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.hl7.fhir.dstu2016may.formats.JsonParser;
import org.hl7.fhir.dstu2016may.formats.XmlParser;
import org.hl7.fhir.dstu2016may.model.Resource;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.r4.conformance.ProfileUtilities;
import org.hl7.fhir.r4.context.SimpleWorkerContext.IContextResourceLoader;
import org.hl7.fhir.r4.model.Bundle;
import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent;
import org.hl7.fhir.r4.model.Bundle.BundleType;
import org.hl7.fhir.r4.model.CodeSystem;
import org.hl7.fhir.r4.model.MetadataResource;
import org.hl7.fhir.r4.model.StructureDefinition;
import org.hl7.fhir.r4.model.StructureDefinition.StructureDefinitionKind;
import org.hl7.fhir.r4.model.UriType;
import org.hl7.fhir.r4.model.ValueSet;
public class R2016MayToR4Loader implements IContextResourceLoader, VersionConvertorAdvisor40 {
private List<CodeSystem> cslist = new ArrayList<>();
private boolean patchUrls;
private boolean killPrimitives;;
@Override
public Bundle loadBundle(InputStream stream, boolean isJson) throws FHIRException, IOException {
Resource r2016may = null;
if (isJson)
r2016may = new JsonParser().parse(stream);
else
r2016may = new XmlParser().parse(stream);
org.hl7.fhir.r4.model.Resource r4 = VersionConvertor_14_40.convertResource(r2016may);
Bundle b;
if (r4 instanceof Bundle)
b = (Bundle) r4;
else {
b = new Bundle();
b.setId(UUID.randomUUID().toString().toLowerCase());
b.setType(BundleType.COLLECTION);
b.addEntry().setResource(r4).setFullUrl(r4 instanceof MetadataResource ? ((MetadataResource) r4).getUrl() : null);
}
for (CodeSystem cs : cslist) {
BundleEntryComponent be = b.addEntry();
be.setFullUrl(cs.getUrl());
be.setResource(cs);
}
if (killPrimitives) {
List<BundleEntryComponent> remove = new ArrayList<BundleEntryComponent>();
for (BundleEntryComponent be : b.getEntry()) {
if (be.hasResource() && be.getResource() instanceof StructureDefinition) {
StructureDefinition sd = (StructureDefinition) be.getResource();
if (sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE)
remove.add(be);
}
}
b.getEntry().removeAll(remove);
}
for (BundleEntryComponent be : b.getEntry()) {
if (be.hasResource() && be.getResource() instanceof StructureDefinition) {
StructureDefinition sd = (StructureDefinition) be.getResource();
new ProfileUtilities(null, null, null).setIds(sd, false);
if (patchUrls) {
sd.setUrl(sd.getUrl().replace("http://hl7.org/fhir/", "http://hl7.org/fhir/2016May/"));
sd.addExtension().setUrl("http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace").setValue(new UriType("http://hl7.org/fhir"));
}
}
}
return b;
}
@Override
public boolean ignoreEntry(BundleEntryComponent src) {
return false;
}
@Override
public org.hl7.fhir.dstu2.model.Resource convertR2(org.hl7.fhir.r4.model.Resource resource) throws FHIRException {
return null;
}
@Override
public Resource convertR2016May(org.hl7.fhir.r4.model.Resource resource) throws FHIRException {
return null;
}
@Override
public org.hl7.fhir.dstu3.model.Resource convertR3(org.hl7.fhir.r4.model.Resource resource) throws FHIRException {
return null;
}
@Override
public void handleCodeSystem(CodeSystem cs, ValueSet vs) {
cs.setId(vs.getId());
cs.setValueSet(vs.getUrl());
cslist.add(cs);
}
@Override
public CodeSystem getCodeSystem(ValueSet src) {
return null;
}
public boolean isPatchUrls() {
return patchUrls;
}
public R2016MayToR4Loader setPatchUrls(boolean patchUrls) {
this.patchUrls = patchUrls;
return this;
}
public boolean isKillPrimitives() {
return killPrimitives;
}
public R2016MayToR4Loader setKillPrimitives(boolean killPrimitives) {
this.killPrimitives = killPrimitives;
return this;
}
}

View File

@ -0,0 +1,401 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.hl7.fhir.dstu3.context.SimpleWorkerContext;
import org.hl7.fhir.dstu3.elementmodel.Manager;
import org.hl7.fhir.dstu3.elementmodel.Manager.FhirFormat;
import org.hl7.fhir.dstu3.formats.FormatUtilities;
import org.hl7.fhir.dstu3.formats.IParser.OutputStyle;
import org.hl7.fhir.dstu3.formats.JsonParser;
import org.hl7.fhir.dstu3.model.Base;
import org.hl7.fhir.dstu3.model.Coding;
import org.hl7.fhir.dstu3.model.ExpansionProfile;
import org.hl7.fhir.dstu3.model.MetadataResource;
import org.hl7.fhir.dstu3.model.PractitionerRole;
import org.hl7.fhir.dstu3.model.Resource;
import org.hl7.fhir.dstu3.model.ResourceFactory;
import org.hl7.fhir.dstu3.model.StructureDefinition;
import org.hl7.fhir.dstu3.model.StructureDefinition.StructureDefinitionKind;
import org.hl7.fhir.dstu3.model.StructureMap;
import org.hl7.fhir.dstu3.model.UriType;
import org.hl7.fhir.dstu3.utils.StructureMapUtilities;
import org.hl7.fhir.dstu3.utils.StructureMapUtilities.ITransformerServices;
import org.hl7.fhir.exceptions.DefinitionException;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.exceptions.FHIRFormatError;
import org.hl7.fhir.utilities.TextFile;
/**
* This class manages conversion from R2 to R3 and vice versa
*
* To use this class, do the following:
*
* - provide a stream or path (file or URL) that points to R2 definitions (from http://hl7.org/fhir/DSTU2/downloads.html)
* - provide a stream or a path (file or URL) that points to the R3 definitions (from http://hl7.org/fhir/STU3/downloads.html)
* - provide a stream or a path (file or URL) that points to R2/R3 map files (from http://hl7.org/fhir/r2r3maps.zip)
*
* - call convert() (can call this more than once, but not multithread safe)
*
* @author Grahame Grieve
*
*/
public class R2R3ConversionManager implements ITransformerServices {
public class TransformContext {
private SimpleWorkerContext context;
private String id;
public TransformContext(SimpleWorkerContext context, String id) {
this.context = context;
this.id = id;
}
public SimpleWorkerContext getContext() {
return context;
}
public String getId() {
return id;
}
}
private SimpleWorkerContext contextR2;
private SimpleWorkerContext contextR3;
private Map<String, StructureMap> library = new HashMap<String, StructureMap>();
private boolean needPrepare = false;
private List<Resource> extras = new ArrayList<Resource>();
private StructureMapUtilities smu3;
private StructureMapUtilities smu2;
private OutputStyle style = OutputStyle.PRETTY;
public OutputStyle getStyle() {
return style;
}
public void setStyle(OutputStyle style) {
this.style = style;
}
public List<Resource> getExtras() {
return extras;
}
// set up ------------------------------------------------------------------
public void setR2Definitions(InputStream stream) throws IOException, FHIRException {
needPrepare = true;
R2ToR3Loader ldr = new R2ToR3Loader().setPatchUrls(true).setKillPrimitives(true);
Map<String, InputStream> files = readInputStream(stream);
contextR2 = new SimpleWorkerContext();
contextR2.setAllowLoadingDuplicates(true);
contextR2.loadFromFile(files.get("profiles-types.xml"), "profiles-types.xml", ldr);
contextR2.loadFromFile(files.get("profiles-resources.xml"), "profiles-resources.xml", ldr);
contextR2.loadFromFile(files.get("valuesets.xml"), "valuesets.xml", ldr);
}
public void setR2Definitions(String source) throws IOException, FHIRException {
File f = new File(source);
if (f.exists())
setR2Definitions(new FileInputStream(f));
else
setR2Definitions(fetch(source));
}
public void setR3Definitions(InputStream stream) throws IOException, FHIRException {
needPrepare = true;
Map<String, InputStream> files = readInputStream(stream);
contextR3 = new SimpleWorkerContext();
contextR2.setAllowLoadingDuplicates(true);
contextR3.loadFromFile(files.get("profiles-types.xml"), "profiles-types.xml", null);
contextR3.loadFromFile(files.get("profiles-resources.xml"), "profiles-resources.xml", null);
contextR3.loadFromFile(files.get("extension-definitions.xml"), "extension-definitions.xml", null);
contextR3.loadFromFile(files.get("valuesets.xml"), "valuesets.xml", null);
contextR3.setCanRunWithoutTerminology(true);
}
public void setR3Definitions(String source) throws FileNotFoundException, IOException, FHIRException {
File f = new File(source);
if (f.exists())
setR3Definitions(new FileInputStream(f));
else
setR3Definitions(fetch(source));
}
public void setMappingLibrary(InputStream stream) throws IOException, FHIRException {
needPrepare = true;
Map<String, InputStream> files = readInputStream(stream);
for (InputStream s : files.values()) {
StructureMap sm = new StructureMapUtilities(contextR3).parse(TextFile.streamToString(s));
library.put(sm.getUrl(), sm);
}
}
public void setMappingLibrary(String source) throws IOException, FHIRException {
File f = new File(source);
if (f.exists())
setMappingLibrary(new FileInputStream(f));
else
setMappingLibrary(fetch(source));
}
// support
private InputStream fetch(String source) {
throw new Error("not done yet");
}
private Map<String, InputStream> readInputStream(InputStream stream) throws IOException {
Map<String, InputStream> res = new HashMap<String, InputStream>();
ZipInputStream zip = new ZipInputStream(stream);
ZipEntry ze = null;
while ((ze = zip.getNextEntry()) != null) {
String n = ze.getName();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
for (int c = zip.read(); c != -1; c = zip.read()) {
bs.write(c);
}
bs.close();
res.put(n, new ByteArrayInputStream(bs.toByteArray()));
zip.closeEntry();
}
zip.close();
return res;
}
private void prepare() throws FHIRException {
if (contextR2 == null)
throw new FHIRException("No R2 definitions provided");
if (contextR3 == null)
throw new FHIRException("No R3 definitions provided");
if (library == null)
throw new FHIRException("No R2/R# conversion maps provided");
if (needPrepare) {
for (StructureDefinition sd : contextR2.allStructures()) {
StructureDefinition sdn = sd.copy();
sdn.getExtension().clear();
contextR3.seeResource(sdn.getUrl(), sdn);
}
for (StructureDefinition sd : contextR3.allStructures()) {
if (sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE) {
contextR2.seeResource(sd.getUrl(), sd);
StructureDefinition sdn = sd.copy();
sdn.setUrl(sdn.getUrl().replace("http://hl7.org/fhir/", "http://hl7.org/fhir/DSTU2/"));
sdn.addExtension().setUrl("http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace").setValue(new UriType("http://hl7.org/fhir"));
contextR2.seeResource(sdn.getUrl(), sdn);
contextR3.seeResource(sdn.getUrl(), sdn);
}
}
contextR2.setExpansionProfile(new ExpansionProfile().setUrl("urn:uuid:"+UUID.randomUUID().toString().toLowerCase()));
contextR3.setExpansionProfile(new ExpansionProfile().setUrl("urn:uuid:"+UUID.randomUUID().toString().toLowerCase()));
smu3 = new StructureMapUtilities(contextR3, library, this);
smu2 = new StructureMapUtilities(contextR2, library, this);
needPrepare = false;
}
}
// execution
public byte[] convert(byte[] source, boolean r2ToR3, FhirFormat format) throws FHIRException, IOException {
prepare();
ByteArrayOutputStream bs = new ByteArrayOutputStream();
if (r2ToR3)
convertToR3(new ByteArrayInputStream(source), bs, format);
else
convertToR2(new ByteArrayInputStream(source), bs, format);
bs.close();
return bs.toByteArray();
}
public void convert(InputStream source, OutputStream dest, boolean r2ToR3, FhirFormat format) throws FHIRException, IOException {
prepare();
if (r2ToR3)
convertToR3(source, dest, format);
else
convertToR2(source, dest, format);
}
public org.hl7.fhir.dstu2.model.Resource convert(org.hl7.fhir.dstu3.model.Resource source) throws IOException, FHIRFormatError, FHIRException {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
new JsonParser().compose(bs, source);
bs.close();
return new org.hl7.fhir.dstu2.formats.JsonParser().parse(convert(bs.toByteArray(), false, FhirFormat.JSON));
}
public org.hl7.fhir.dstu3.model.Resource convert(org.hl7.fhir.dstu2.model.Resource source) throws IOException, FHIRFormatError, FHIRException {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
new org.hl7.fhir.dstu2.formats.JsonParser().compose(bs, source);
bs.close();
return new JsonParser().parse(convert(bs.toByteArray(), false, FhirFormat.JSON));
}
private void convertToR3(InputStream source, OutputStream dest, FhirFormat format) throws FHIRFormatError, DefinitionException, FHIRException, IOException {
org.hl7.fhir.dstu3.elementmodel.Element r2 = new org.hl7.fhir.dstu3.elementmodel.XmlParser(contextR2).parse(source);
StructureMap map = library.get("http://hl7.org/fhir/StructureMap/"+r2.fhirType()+"2to3");
if (map == null)
throw new FHIRException("No Map Found from R2 to R3 for "+r2.fhirType());
String tn = smu3.getTargetType(map).getType();
Resource r3 = ResourceFactory.createResource(tn);
smu3.transform(new TransformContext(contextR3, r2.getChildValue("id")), r2, map, r3);
FormatUtilities.makeParser(format).setOutputStyle(style).compose(dest, r3);
}
private void convertToR2(InputStream source, OutputStream dest, FhirFormat format) throws FHIRFormatError, DefinitionException, FHIRException, IOException {
org.hl7.fhir.dstu3.elementmodel.Element r3 = new org.hl7.fhir.dstu3.elementmodel.XmlParser(contextR3).parse(source);
StructureMap map = library.get("??");
String tn = smu3.getTargetType(map).getType();
StructureDefinition sd = smu2.getTargetType(map);
org.hl7.fhir.dstu3.elementmodel.Element r2 = Manager.build(contextR2, sd);
smu2.transform(contextR2, r3, map, r2);
org.hl7.fhir.dstu3.elementmodel.Manager.compose(contextR2, r2, dest, format, style, null);
}
@Override
public void log(String message) {
// System.out.println(message);
}
@Override
public Base createType(Object appInfo, String name) throws FHIRException {
SimpleWorkerContext context = ((TransformContext) appInfo).getContext();
if (context == contextR2) {
StructureDefinition sd = context.fetchResource(StructureDefinition.class, "http://hl7.org/fhir/DSTU2/StructureDefinition/"+name);
if (sd == null)
throw new FHIRException("Type not found: '"+name+"'");
return Manager.build(context, sd);
} else
return ResourceFactory.createResourceOrType(name);
}
@Override
public Base createResource(Object appInfo, Base res) {
if (res instanceof Resource && (res.fhirType().equals("CodeSystem") || res.fhirType().equals("CareTeam")) || res.fhirType().equals("PractitionerRole")) {
Resource r = (Resource) res;
extras.add(r);
r.setId(((TransformContext) appInfo).getId()+"-"+extras.size()); //todo: get this into appinfo
}
return res;
}
@Override
public Coding translate(Object appInfo, Coding source, String conceptMapUrl) throws FHIRException {
throw new Error("translate not done yet");
}
@Override
public Base resolveReference(Object appContext, String url) {
for (Resource r : extras) {
if (r instanceof MetadataResource) {
MetadataResource mr = (MetadataResource) r;
if (url.equals(mr.getUrl()))
return mr;
}
if (url.equals(r.fhirType()+"/"+r.getId()))
return r;
}
return null;
}
@Override
public List<Base> performSearch(Object appContext, String url) {
List<Base> results = new ArrayList<Base>();
String[] parts = url.split("\\?");
if (parts.length == 2 && parts[0].substring(1).equals("PractitionerRole")) {
String[] vals = parts[1].split("\\=");
if (vals.length == 2 && vals[0].equals("practitioner"))
for (Resource r : extras) {
if (r instanceof PractitionerRole && ((PractitionerRole) r).getPractitioner().getReference().equals("Practitioner/"+vals[1])) {
results.add(r);
}
}
}
return results;
}
public static void main(String[] args) throws IOException, FHIRException {
if (args.length == 0 || !hasParam(args, "-d2") || !hasParam(args, "-d3") || !hasParam(args, "-maps") || !hasParam(args, "-src") || !hasParam(args, "-dest") || (!hasParam(args, "-r2") && !hasParam(args, "-r3"))) {
System.out.println("R2 <--> R3 Convertor");
System.out.println("====================");
System.out.println("");
System.out.println("parameters: -d2 [r2 definitions] -d3 [r3 definitions] -maps [map source] -src [source] -dest [dest] -r2/3 - fmt [format]");
System.out.println("");
System.out.println("d2: definitions from http://hl7.org/fhir/DSTU2/downloads.html");
System.out.println("d3: definitions from http://hl7.org/fhir/STU3/downloads.html");
System.out.println("maps: R2/R3 maps from http://hl7.org/fhir/r2r3maps.zip");
System.out.println("src: filename for source to convert");
System.out.println("dest: filename for destination of conversion");
System.out.println("-r2: source is r2, convert to r3");
System.out.println("-r3: source is r3, convert to r2");
System.out.println("-fmt: xml | json (xml is default)");
} else {
R2R3ConversionManager self = new R2R3ConversionManager();
self.setR2Definitions(getNamedParam(args, "-d2"));
self.setR3Definitions(getNamedParam(args, "-d3"));
self.setMappingLibrary(getNamedParam(args, "-maps"));
FhirFormat fmt = hasParam(args, "-fmt") ? getNamedParam(args, "-fmt").equalsIgnoreCase("json") ? FhirFormat.JSON : FhirFormat.XML : FhirFormat.XML;
InputStream src = new FileInputStream(getNamedParam(args, "-src"));
OutputStream dst = new FileOutputStream(getNamedParam(args, "-dest"));
self.convert(src, dst, hasParam(args, "-r2"), fmt);
}
}
private static boolean hasParam(String[] args, String param) {
for (String a : args)
if (a.equals(param))
return true;
return false;
}
private static String getNamedParam(String[] args, String param) {
boolean found = false;
for (String a : args) {
if (found)
return a;
if (a.equals(param)) {
found = true;
}
}
return null;
}
}

View File

@ -0,0 +1,138 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.hl7.fhir.dstu2.formats.JsonParser;
import org.hl7.fhir.dstu2.formats.XmlParser;
import org.hl7.fhir.dstu2.model.Resource;
import org.hl7.fhir.dstu3.context.SimpleWorkerContext.IContextResourceLoader;
import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent;
import org.hl7.fhir.dstu3.model.Bundle.BundleType;
import org.hl7.fhir.dstu3.model.CodeSystem;
import org.hl7.fhir.dstu3.model.MetadataResource;
import org.hl7.fhir.dstu3.model.StructureDefinition;
import org.hl7.fhir.dstu3.model.StructureDefinition.StructureDefinitionKind;
import org.hl7.fhir.dstu3.model.UriType;
import org.hl7.fhir.dstu3.model.ValueSet;
import org.hl7.fhir.exceptions.FHIRException;
public class R2ToR3Loader implements IContextResourceLoader, VersionConvertorAdvisor30 {
private List<CodeSystem> cslist = new ArrayList<>();
private boolean patchUrls;
private boolean killPrimitives;;
@Override
public Bundle loadBundle(InputStream stream, boolean isJson) throws FHIRException, IOException {
Resource r2 = null;
if (isJson)
r2 = new JsonParser().parse(stream);
else
r2 = new XmlParser().parse(stream);
org.hl7.fhir.dstu3.model.Resource r3 = new VersionConvertor_10_30(this).convertResource(r2);
Bundle b;
if (r3 instanceof Bundle)
b = (Bundle) r3;
else {
b = new Bundle();
b.setId(UUID.randomUUID().toString().toLowerCase());
b.setType(BundleType.COLLECTION);
b.addEntry().setResource(r3).setFullUrl(r3 instanceof MetadataResource ? ((MetadataResource) r3).getUrl() : null);
}
for (CodeSystem cs : cslist) {
BundleEntryComponent be = b.addEntry();
be.setFullUrl(cs.getUrl());
be.setResource(cs);
}
cslist.clear();
if (killPrimitives) {
List<BundleEntryComponent> remove = new ArrayList<BundleEntryComponent>();
for (BundleEntryComponent be : b.getEntry()) {
if (be.hasResource() && be.getResource() instanceof StructureDefinition) {
StructureDefinition sd = (StructureDefinition) be.getResource();
if (sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE)
remove.add(be);
}
}
b.getEntry().removeAll(remove);
}
if (patchUrls) {
for (BundleEntryComponent be : b.getEntry()) {
if (be.hasResource() && be.getResource() instanceof StructureDefinition) {
StructureDefinition sd = (StructureDefinition) be.getResource();
sd.setUrl(sd.getUrl().replace("http://hl7.org/fhir/", "http://hl7.org/fhir/DSTU2/"));
sd.addExtension().setUrl("http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace").setValue(new UriType("http://hl7.org/fhir"));
}
}
}
return b;
}
@Override
public boolean ignoreEntry(BundleEntryComponent src) {
return false;
}
@Override
public Resource convert(org.hl7.fhir.dstu3.model.Resource resource) throws FHIRException {
return null;
}
@Override
public void handleCodeSystem(CodeSystem cs, ValueSet vs) {
cs.setId(vs.getId());
cs.setValueSet(vs.getUrl());
cslist.add(cs);
}
@Override
public CodeSystem getCodeSystem(ValueSet src) {
return null;
}
public boolean isPatchUrls() {
return patchUrls;
}
public R2ToR3Loader setPatchUrls(boolean patchUrls) {
this.patchUrls = patchUrls;
return this;
}
public boolean isKillPrimitives() {
return killPrimitives;
}
public R2ToR3Loader setKillPrimitives(boolean killPrimitives) {
this.killPrimitives = killPrimitives;
return this;
}
}

View File

@ -0,0 +1,148 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.hl7.fhir.dstu2.formats.JsonParser;
import org.hl7.fhir.dstu2.formats.XmlParser;
import org.hl7.fhir.dstu2.model.Resource;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.r4.context.SimpleWorkerContext.IContextResourceLoader;
import org.hl7.fhir.r4.model.Bundle;
import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent;
import org.hl7.fhir.r4.model.Bundle.BundleType;
import org.hl7.fhir.r4.model.CodeSystem;
import org.hl7.fhir.r4.model.MetadataResource;
import org.hl7.fhir.r4.model.StructureDefinition;
import org.hl7.fhir.r4.model.StructureDefinition.StructureDefinitionKind;
import org.hl7.fhir.r4.model.UriType;
import org.hl7.fhir.r4.model.ValueSet;
public class R2ToR4Loader implements IContextResourceLoader, VersionConvertorAdvisor40 {
private List<CodeSystem> cslist = new ArrayList<>();
private boolean patchUrls;
private boolean killPrimitives;;
@Override
public Bundle loadBundle(InputStream stream, boolean isJson) throws FHIRException, IOException {
Resource r2 = null;
if (isJson)
r2 = new JsonParser().parse(stream);
else
r2 = new XmlParser().parse(stream);
org.hl7.fhir.r4.model.Resource r4 = new VersionConvertor_10_40(this).convertResource(r2);
Bundle b;
if (r4 instanceof Bundle)
b = (Bundle) r4;
else {
b = new Bundle();
b.setId(UUID.randomUUID().toString().toLowerCase());
b.setType(BundleType.COLLECTION);
b.addEntry().setResource(r4).setFullUrl(r4 instanceof MetadataResource ? ((MetadataResource) r4).getUrl() : null);
}
// Add any code systems defined as part of processing value sets to the end of the converted Bundle
for (CodeSystem cs : cslist) {
BundleEntryComponent be = b.addEntry();
be.setFullUrl(cs.getUrl());
be.setResource(cs);
}
cslist.clear();
if (killPrimitives) {
List<BundleEntryComponent> remove = new ArrayList<BundleEntryComponent>();
for (BundleEntryComponent be : b.getEntry()) {
if (be.hasResource() && be.getResource() instanceof StructureDefinition) {
StructureDefinition sd = (StructureDefinition) be.getResource();
if (sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE)
remove.add(be);
}
}
b.getEntry().removeAll(remove);
}
if (patchUrls) {
for (BundleEntryComponent be : b.getEntry()) {
if (be.hasResource() && be.getResource() instanceof StructureDefinition) {
StructureDefinition sd = (StructureDefinition) be.getResource();
sd.setUrl(sd.getUrl().replace("http://hl7.org/fhir/", "http://hl7.org/fhir/DSTU2/"));
sd.addExtension().setUrl("http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace").setValue(new UriType("http://hl7.org/fhir"));
}
}
}
return b;
}
@Override
public boolean ignoreEntry(BundleEntryComponent src) {
return false;
}
@Override
public Resource convertR2(org.hl7.fhir.r4.model.Resource resource) throws FHIRException {
return null;
}
@Override
public org.hl7.fhir.dstu2016may.model.Resource convertR2016May(org.hl7.fhir.r4.model.Resource resource) throws FHIRException {
return null;
}
public org.hl7.fhir.dstu3.model.Resource convertR3(org.hl7.fhir.r4.model.Resource resource) throws FHIRException {
return null;
}
@Override
public void handleCodeSystem(CodeSystem cs, ValueSet vs) {
cs.setId(vs.getId());
cs.setValueSet(vs.getUrl());
cslist.add(cs);
}
@Override
public CodeSystem getCodeSystem(ValueSet src) {
return null;
}
public boolean isPatchUrls() {
return patchUrls;
}
public R2ToR4Loader setPatchUrls(boolean patchUrls) {
this.patchUrls = patchUrls;
return this;
}
public boolean isKillPrimitives() {
return killPrimitives;
}
public R2ToR4Loader setKillPrimitives(boolean killPrimitives) {
this.killPrimitives = killPrimitives;
return this;
}
}

View File

@ -0,0 +1,166 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.hl7.fhir.dstu3.formats.JsonParser;
import org.hl7.fhir.dstu3.formats.XmlParser;
import org.hl7.fhir.dstu3.model.Resource;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.r4.context.SimpleWorkerContext.IContextResourceLoader;
import org.hl7.fhir.r4.model.Bundle;
import org.hl7.fhir.r4.model.Bundle.BundleEntryComponent;
import org.hl7.fhir.r4.model.Bundle.BundleType;
import org.hl7.fhir.r4.model.CanonicalType;
import org.hl7.fhir.r4.model.CodeSystem;
import org.hl7.fhir.r4.model.ElementDefinition;
import org.hl7.fhir.r4.model.ElementDefinition.TypeRefComponent;
import org.hl7.fhir.r4.model.MetadataResource;
import org.hl7.fhir.r4.model.StructureDefinition;
import org.hl7.fhir.r4.model.StructureDefinition.StructureDefinitionKind;
import org.hl7.fhir.r4.model.UriType;
import org.hl7.fhir.r4.model.ValueSet;
public class R3ToR4Loader implements IContextResourceLoader, VersionConvertorAdvisor40 {
private List<CodeSystem> cslist = new ArrayList<>();
private boolean patchUrls;
private boolean killPrimitives;;
@Override
public Bundle loadBundle(InputStream stream, boolean isJson) throws FHIRException, IOException {
Resource r3 = null;
if (isJson)
r3 = new JsonParser().parse(stream);
else
r3 = new XmlParser().parse(stream);
org.hl7.fhir.r4.model.Resource r4 = VersionConvertor_30_40.convertResource(r3, false);
Bundle b;
if (r4 instanceof Bundle)
b = (Bundle) r4;
else {
b = new Bundle();
b.setId(UUID.randomUUID().toString().toLowerCase());
b.setType(BundleType.COLLECTION);
b.addEntry().setResource(r4).setFullUrl(r4 instanceof MetadataResource ? ((MetadataResource) r4).getUrl() : null);
}
for (CodeSystem cs : cslist) {
BundleEntryComponent be = b.addEntry();
be.setFullUrl(cs.getUrl());
be.setResource(cs);
}
if (killPrimitives) {
List<BundleEntryComponent> remove = new ArrayList<BundleEntryComponent>();
for (BundleEntryComponent be : b.getEntry()) {
if (be.hasResource() && be.getResource() instanceof StructureDefinition) {
StructureDefinition sd = (StructureDefinition) be.getResource();
if (sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE)
remove.add(be);
}
}
b.getEntry().removeAll(remove);
}
if (patchUrls) {
for (BundleEntryComponent be : b.getEntry()) {
if (be.hasResource() && be.getResource() instanceof StructureDefinition) {
StructureDefinition sd = (StructureDefinition) be.getResource();
sd.setUrl(sd.getUrl().replace("http://hl7.org/fhir/", "http://hl7.org/fhir/3.0/"));
sd.addExtension().setUrl("http://hl7.org/fhir/StructureDefinition/elementdefinition-namespace").setValue(new UriType("http://hl7.org/fhir"));
for (ElementDefinition ed : sd.getSnapshot().getElement())
patchUrl(ed);
for (ElementDefinition ed : sd.getDifferential().getElement())
patchUrl(ed);
}
}
}
return b;
}
private void patchUrl(ElementDefinition ed) {
for (TypeRefComponent tr : ed.getType()) {
for (CanonicalType s : tr.getTargetProfile()) {
s.setValue(s.getValue().replace("http://hl7.org/fhir/", "http://hl7.org/fhir/3.0/"));
}
for (CanonicalType s : tr.getProfile()) {
s.setValue(s.getValue().replace("http://hl7.org/fhir/", "http://hl7.org/fhir/3.0/"));
}
}
}
@Override
public boolean ignoreEntry(BundleEntryComponent src) {
return false;
}
@Override
public org.hl7.fhir.dstu2.model.Resource convertR2(org.hl7.fhir.r4.model.Resource resource) throws FHIRException {
return null;
}
@Override
public org.hl7.fhir.dstu2016may.model.Resource convertR2016May(org.hl7.fhir.r4.model.Resource resource) throws FHIRException {
return null;
}
@Override
public Resource convertR3(org.hl7.fhir.r4.model.Resource resource) throws FHIRException {
return null;
}
@Override
public void handleCodeSystem(CodeSystem cs, ValueSet vs) {
cs.setId(vs.getId());
cs.setValueSet(vs.getUrl());
cslist.add(cs);
}
@Override
public CodeSystem getCodeSystem(ValueSet src) {
return null;
}
public boolean isPatchUrls() {
return patchUrls;
}
public R3ToR4Loader setPatchUrls(boolean patchUrls) {
this.patchUrls = patchUrls;
return this;
}
public boolean isKillPrimitives() {
return killPrimitives;
}
public R3ToR4Loader setKillPrimitives(boolean killPrimitives) {
this.killPrimitives = killPrimitives;
return this;
}
}

View File

@ -0,0 +1,56 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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.net.URISyntaxException;
import org.hl7.fhir.r4.model.FhirPublication;
import org.hl7.fhir.r4.terminologies.TerminologyClient;
import org.hl7.fhir.r4.terminologies.TerminologyClientR4;
import org.hl7.fhir.utilities.Utilities;
public class TerminologyClientFactory {
public static TerminologyClient makeClient(String url, FhirPublication v) throws URISyntaxException {
if (v == null)
return new TerminologyClientR4(checkEndsWith("/r4", url));
switch (v) {
case DSTU2016May: return new TerminologyClientR3(checkEndsWith("/r3", url)); // r3 is the least worst match
case DSTU1: throw new Error("The version "+v.toString()+" is not currently supported");
case DSTU2: return new TerminologyClientR2(checkEndsWith("/r2", url));
case R4: return new TerminologyClientR4(checkEndsWith("/r4", url));
case STU3: return new TerminologyClientR3(checkEndsWith("/r3", url));
default: throw new Error("The version "+v.toString()+" is not currently supported");
}
}
private static String checkEndsWith(String term, String url) {
if (url.endsWith(term))
return url;
if (url.startsWith("http://tx.fhir.org"))
return Utilities.pathURL(url, term);
if (url.equals("http://local.fhir.org:960"))
return Utilities.pathURL(url, term);
return url;
}
}

View File

@ -0,0 +1,97 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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.net.URISyntaxException;
import java.util.Map;
import org.hl7.fhir.dstu2.utils.client.FHIRToolingClient;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.r4.context.HTMLClientLogger;
import org.hl7.fhir.r4.model.CapabilityStatement;
import org.hl7.fhir.r4.model.Parameters;
import org.hl7.fhir.r4.model.TerminologyCapabilities;
import org.hl7.fhir.r4.model.ValueSet;
import org.hl7.fhir.r4.terminologies.TerminologyClient;
public class TerminologyClientR2 implements TerminologyClient {
private FHIRToolingClient client; // todo: use the R2 client
private VersionConvertor_10_40 conv;
public TerminologyClientR2(String address) throws URISyntaxException {
client = new FHIRToolingClient(address);
conv = new VersionConvertor_10_40(null);
}
@Override
public TerminologyCapabilities getTerminologyCapabilities() throws FHIRException {
return (TerminologyCapabilities) conv.convertTerminologyCapabilities(client.getTerminologyCapabilities());
}
@Override
public String getAddress() {
return client.getAddress();
}
@Override
public ValueSet expandValueset(ValueSet vs, Parameters p, Map<String, String> params) throws FHIRException {
org.hl7.fhir.dstu2.model.ValueSet vs2 = (org.hl7.fhir.dstu2.model.ValueSet) conv.convertResource(vs);
org.hl7.fhir.dstu2.model.Parameters p2 = (org.hl7.fhir.dstu2.model.Parameters) conv.convertResource(p);
vs2 = client.expandValueset(vs2, p2, params);
return (ValueSet) conv.convertResource(vs2);
}
@Override
public Parameters validateCS(Parameters pin) throws FHIRException {
org.hl7.fhir.dstu2.model.Parameters p2 = (org.hl7.fhir.dstu2.model.Parameters) conv.convertResource(pin);
p2 = client.operateType(org.hl7.fhir.dstu2.model.ValueSet.class, "validate-code", p2);
return (Parameters) conv.convertResource(p2);
}
@Override
public Parameters validateVS(Parameters pin) throws FHIRException {
org.hl7.fhir.dstu2.model.Parameters p2 = (org.hl7.fhir.dstu2.model.Parameters) conv.convertResource(pin);
p2 = client.operateType(org.hl7.fhir.dstu2.model.ValueSet.class, "validate-code", p2);
return (Parameters) conv.convertResource(p2);
}
@Override
public void setTimeout(int i) {
// ignored in this version - need to roll R4 internal changes back to R2 if desired
}
@Override
public void setLogger(HTMLClientLogger txLog) {
// ignored in this version - need to roll R4 internal changes back to R2 if desired
}
@Override
public CapabilityStatement getCapabilitiesStatementQuick() throws FHIRException {
return (CapabilityStatement) conv.convertResource(client.getConformanceStatementQuick());
}
@Override
public Parameters lookupCode(Map<String, String> params) throws FHIRException {
return (Parameters) conv.convertResource(client.lookupCode(params));
}
}

View File

@ -0,0 +1,96 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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.net.URISyntaxException;
import java.util.Map;
import org.hl7.fhir.dstu3.utils.client.FHIRToolingClient;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.r4.context.HTMLClientLogger;
import org.hl7.fhir.r4.model.CapabilityStatement;
import org.hl7.fhir.r4.model.Parameters;
import org.hl7.fhir.r4.model.TerminologyCapabilities;
import org.hl7.fhir.r4.model.ValueSet;
import org.hl7.fhir.r4.terminologies.TerminologyClient;
public class TerminologyClientR3 implements TerminologyClient {
private FHIRToolingClient client; // todo: use the R2 client
public TerminologyClientR3(String address) throws URISyntaxException {
client = new FHIRToolingClient(address);
}
@Override
public TerminologyCapabilities getTerminologyCapabilities() throws FHIRException {
return (TerminologyCapabilities) VersionConvertor_30_40.convertTerminologyCapabilities(client.getTerminologyCapabilities(), false);
}
@Override
public String getAddress() {
return client.getAddress();
}
@Override
public ValueSet expandValueset(ValueSet vs, Parameters p, Map<String, String> params) throws FHIRException {
org.hl7.fhir.dstu3.model.ValueSet vs2 = (org.hl7.fhir.dstu3.model.ValueSet) VersionConvertor_30_40.convertResource(vs, false);
org.hl7.fhir.dstu3.model.ExpansionProfile p2 = (org.hl7.fhir.dstu3.model.ExpansionProfile) VersionConvertor_30_40.convertResource(p, false);
vs2 = client.expandValueset(vs2, p2, params); // todo: second parameter
return (ValueSet) VersionConvertor_30_40.convertResource(vs2, false);
}
@Override
public Parameters validateCS(Parameters pin) throws FHIRException {
org.hl7.fhir.dstu3.model.Parameters p2 = (org.hl7.fhir.dstu3.model.Parameters) VersionConvertor_30_40.convertResource(pin, false);
p2 = client.operateType(org.hl7.fhir.dstu3.model.CodeSystem.class, "validate-code", p2);
return (Parameters) VersionConvertor_30_40.convertResource(p2, false);
}
@Override
public Parameters validateVS(Parameters pin) throws FHIRException {
org.hl7.fhir.dstu3.model.Parameters p2 = (org.hl7.fhir.dstu3.model.Parameters) VersionConvertor_30_40.convertResource(pin, false);
p2 = client.operateType(org.hl7.fhir.dstu3.model.ValueSet.class, "validate-code", p2);
return (Parameters) VersionConvertor_30_40.convertResource(p2, false);
}
@Override
public void setTimeout(int i) {
// ignored in this version - need to roll R4 internal changes back to R2 if desired
}
@Override
public void setLogger(HTMLClientLogger txLog) {
// ignored in this version - need to roll R4 internal changes back to R2 if desired
}
@Override
public CapabilityStatement getCapabilitiesStatementQuick() throws FHIRException {
return (CapabilityStatement) VersionConvertor_30_40.convertResource(client.getCapabilitiesStatementQuick(), false);
}
@Override
public Parameters lookupCode(Map<String, String> params) throws FHIRException {
return (Parameters) VersionConvertor_30_40.convertResource(client.lookupCode(params), false);
}
}

View File

@ -0,0 +1,259 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.IOException;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.r4.elementmodel.Manager.FhirFormat;
import org.hl7.fhir.r4.formats.IParser.OutputStyle;
import org.hl7.fhir.r4.model.FhirPublication;
public class VersionConversionService {
/**
* use the package manager to load relevant conversion packages, and then initialise internally as required
*
* not thread safe
*
* @param system - true if the software is running in system context, not in a user context
* @param txServer - Address of the terminology server to use (null = use http://tx.fhir.org
*/
public VersionConversionService(boolean system, String txServer) throws FHIRException {
}
/**
* convert from one version to another.
*
* This routine is thread safe
*
* @param src - the resource to convert
* @param srcVersion - the version of the resource to convert
* @param dstVersion - the target version to convert to
* @return the converted resource
* @throws FHIRException - if the source resource cannot be parsed, no single path exists from source to dest version, or the conversion process fails
* @throws IOException
*/
public byte[] convert(byte[] src, FhirFormat srcFormat, FhirPublication srcVersion, FhirFormat dstFormat, FhirPublication dstVersion, boolean useJava, OutputStyle style) throws FHIRException, IOException {
if (src == null)
throw new FHIRException("No source specified");
if (srcVersion == null)
throw new FHIRException("No source version specified");
if (dstVersion == null)
throw new FHIRException("No destination version specified");
switch (srcVersion) {
case DSTU1: throw new FHIRException("FHIR Version #1 is not supported by the inter-version convertor");
case DSTU2: return convert10(parseResource10(src, srcFormat), dstFormat, dstVersion, useJava, style);
case DSTU2016May: return convert14(parseResource14(src, srcFormat), dstFormat, dstVersion, useJava, style);
case R4: return convert40(parseResource40(src, srcFormat), dstFormat, dstVersion, useJava, style);
case STU3: return convert30(parseResource30(src, srcFormat), dstFormat, dstVersion, useJava, style);
default: throw new FHIRException("FHIR Version 'unknown' is not supported by the inter-version convertor");
}
}
private org.hl7.fhir.dstu2.model.Resource parseResource10(byte[] src, FhirFormat srcFormat) throws FHIRException, IOException {
switch (srcFormat) {
case JSON: return new org.hl7.fhir.dstu2.formats.JsonParser().parse(src);
case TEXT: throw new FHIRException("Text format not supported for DSTU2");
case TURTLE: throw new FHIRException("Turtle format not supported for DSTU2");
case VBAR: throw new FHIRException("Vertical Bar format not supported for DSTU2");
case XML: return new org.hl7.fhir.dstu2.formats.XmlParser().parse(src);
default: throw new FHIRException("Unknown format not supported for DSTU2");
}
}
private org.hl7.fhir.dstu2016may.model.Resource parseResource14(byte[] src, FhirFormat srcFormat) throws FHIRException, IOException {
switch (srcFormat) {
case JSON: return new org.hl7.fhir.dstu2016may.formats.JsonParser().parse(src);
case TEXT: throw new FHIRException("Text format not supported for DSTU2");
case TURTLE: throw new FHIRException("Turtle format not supported for DSTU2");
case VBAR: throw new FHIRException("Vertical Bar format not supported for DSTU2");
case XML: return new org.hl7.fhir.dstu2016may.formats.XmlParser().parse(src);
default: throw new FHIRException("Unknown format not supported for DSTU2");
}
}
private org.hl7.fhir.dstu3.model.Resource parseResource30(byte[] src, FhirFormat srcFormat) throws FHIRException, IOException {
switch (srcFormat) {
case JSON: return new org.hl7.fhir.dstu3.formats.JsonParser().parse(src);
case TEXT: throw new FHIRException("Text format not supported for DSTU2");
case TURTLE: return new org.hl7.fhir.dstu3.formats.RdfParser().parse(src);
case VBAR: throw new FHIRException("Vertical Bar format not supported for DSTU2");
case XML: return new org.hl7.fhir.dstu3.formats.XmlParser().parse(src);
default: throw new FHIRException("Unknown format not supported for DSTU2");
}
}
private org.hl7.fhir.r4.model.Resource parseResource40(byte[] src, FhirFormat srcFormat) throws FHIRException, IOException {
switch (srcFormat) {
case JSON: return new org.hl7.fhir.r4.formats.JsonParser().parse(src);
case TEXT: throw new FHIRException("Text format not supported for DSTU2");
case TURTLE: return new org.hl7.fhir.r4.formats.RdfParser().parse(src);
case VBAR: throw new FHIRException("Vertical Bar format not supported for DSTU2");
case XML: return new org.hl7.fhir.r4.formats.XmlParser().parse(src);
default: throw new FHIRException("Unknown format not supported for DSTU2");
}
}
private org.hl7.fhir.dstu2.formats.IParser.OutputStyle style10(OutputStyle style) {
return style == OutputStyle.CANONICAL ? org.hl7.fhir.dstu2.formats.IParser.OutputStyle.CANONICAL : style == OutputStyle.NORMAL ? org.hl7.fhir.dstu2.formats.IParser.OutputStyle.NORMAL : org.hl7.fhir.dstu2.formats.IParser.OutputStyle.PRETTY;
}
private org.hl7.fhir.dstu2016may.formats.IParser.OutputStyle style14(OutputStyle style) {
return style == OutputStyle.CANONICAL ? org.hl7.fhir.dstu2016may.formats.IParser.OutputStyle.CANONICAL : style == OutputStyle.NORMAL ? org.hl7.fhir.dstu2016may.formats.IParser.OutputStyle.NORMAL : org.hl7.fhir.dstu2016may.formats.IParser.OutputStyle.PRETTY;
}
private org.hl7.fhir.dstu3.formats.IParser.OutputStyle style30(OutputStyle style) {
return style == OutputStyle.CANONICAL ? org.hl7.fhir.dstu3.formats.IParser.OutputStyle.CANONICAL : style == OutputStyle.NORMAL ? org.hl7.fhir.dstu3.formats.IParser.OutputStyle.NORMAL : org.hl7.fhir.dstu3.formats.IParser.OutputStyle.PRETTY;
}
private byte[] saveResource10(org.hl7.fhir.dstu2.model.Resource src, FhirFormat dstFormat, OutputStyle style) throws FHIRException, IOException {
switch (dstFormat) {
case JSON: return new org.hl7.fhir.dstu2.formats.JsonParser().setOutputStyle(style10(style)).composeBytes(src);
case TEXT: throw new FHIRException("Text format not supported for DSTU2");
case TURTLE: throw new FHIRException("Turtle format not supported for DSTU2");
case VBAR: throw new FHIRException("Vertical Bar format not supported for DSTU2");
case XML: return new org.hl7.fhir.dstu2.formats.XmlParser().setOutputStyle(style10(style)).composeBytes(src);
default: throw new FHIRException("Unknown format not supported for DSTU2");
}
}
private byte[] saveResource14(org.hl7.fhir.dstu2016may.model.Resource src, FhirFormat dstFormat, OutputStyle style) throws FHIRException, IOException {
switch (dstFormat) {
case JSON: return new org.hl7.fhir.dstu2016may.formats.JsonParser().setOutputStyle(style14(style)).composeBytes(src);
case TEXT: throw new FHIRException("Text format not supported for DSTU2");
case TURTLE: throw new FHIRException("Turtle format not supported for DSTU2");
case VBAR: throw new FHIRException("Vertical Bar format not supported for DSTU2");
case XML: return new org.hl7.fhir.dstu2016may.formats.XmlParser().setOutputStyle(style14(style)).composeBytes(src);
default: throw new FHIRException("Unknown format not supported for DSTU2");
}
}
private byte[] saveResource30(org.hl7.fhir.dstu3.model.Resource src, FhirFormat dstFormat, OutputStyle style) throws FHIRException, IOException {
switch (dstFormat) {
case JSON: return new org.hl7.fhir.dstu3.formats.JsonParser().setOutputStyle(style30(style)).composeBytes(src);
case TEXT: throw new FHIRException("Text format not supported for DSTU2");
case TURTLE: return new org.hl7.fhir.dstu3.formats.RdfParser().setOutputStyle(style30(style)).composeBytes(src);
case VBAR: throw new FHIRException("Vertical Bar format not supported for DSTU2");
case XML: return new org.hl7.fhir.dstu3.formats.XmlParser().setOutputStyle(style30(style)).composeBytes(src);
default: throw new FHIRException("Unknown format not supported for DSTU2");
}
}
private byte[] saveResource40(org.hl7.fhir.r4.model.Resource src, FhirFormat dstFormat, OutputStyle style) throws FHIRException, IOException {
switch (dstFormat) {
case JSON: return new org.hl7.fhir.r4.formats.JsonParser().setOutputStyle(style).composeBytes(src);
case TEXT: throw new FHIRException("Text format not supported for DSTU2");
case TURTLE: return new org.hl7.fhir.r4.formats.RdfParser().setOutputStyle(style).composeBytes(src);
case VBAR: throw new FHIRException("Vertical Bar format not supported for DSTU2");
case XML: return new org.hl7.fhir.r4.formats.XmlParser().setOutputStyle(style).composeBytes(src);
default: throw new FHIRException("Unknown format not supported for DSTU2");
}
}
private byte[] convert10(org.hl7.fhir.dstu2.model.Resource src, FhirFormat dstFormat, FhirPublication dstVersion, boolean useJava, OutputStyle style) throws FHIRException, IOException {
switch (dstVersion) {
case DSTU1: throw new FHIRException("FHIR Version #1 is not supported by the inter-version convertor");
case DSTU2: return saveResource10(src, dstFormat, style);
case DSTU2016May: throw new FHIRException("Conversion from DSTU2 to 2016May version is not supported");
case R4:
if (useJava && VersionConvertor_10_40.convertsResource(src.fhirType()))
return saveResource40(new VersionConvertor_10_40(null).convertResource(src), dstFormat, style); // todo: handle code system?
else
throw new FHIRException("Conversion from R4 to 2016May version is not supported for resources of type "+src.fhirType());
case STU3:
if (useJava && VersionConvertor_10_30.convertsResource(src.fhirType()))
return saveResource30(new VersionConvertor_10_30(null).convertResource(src), dstFormat, style); // todo: handle code system?
else
throw new FHIRException("todo: use script based conversion....");
default: throw new FHIRException("FHIR Version 'unknown' is not supported by the inter-version convertor");
}
}
private byte[] convert14(org.hl7.fhir.dstu2016may.model.Resource src, FhirFormat dstFormat, FhirPublication dstVersion, boolean useJava, OutputStyle style) throws FHIRException, IOException {
switch (dstVersion) {
case DSTU1: throw new FHIRException("FHIR Version #1 is not supported by the inter-version convertor");
case DSTU2: throw new FHIRException("Conversion from 2016May version to DSTU2 is not supported");
case DSTU2016May: return saveResource14(src, dstFormat, style);
case R4:
if (useJava && VersionConvertor_14_40.convertsResource(src.fhirType()))
return saveResource40(VersionConvertor_14_40.convertResource(src), dstFormat, style);
else
throw new FHIRException("Conversion from 2016May version to R4 is not supported for resources of type "+src.fhirType());
case STU3:
if (useJava && VersionConvertor_14_30.convertsResource(src.fhirType()))
return saveResource30(VersionConvertor_14_30.convertResource(src), dstFormat, style);
else
throw new FHIRException("Conversion from 2016May version to STU3 is not supported for resources of type "+src.fhirType());
default: throw new FHIRException("FHIR Version 'unknown' is not supported by the inter-version convertor");
}
}
private byte[] convert30(org.hl7.fhir.dstu3.model.Resource src, FhirFormat dstFormat, FhirPublication dstVersion, boolean useJava, OutputStyle style) throws FHIRException, IOException {
switch (dstVersion) {
case DSTU1: throw new FHIRException("FHIR Version #1 is not supported by the inter-version convertor");
case DSTU2:
if (useJava && VersionConvertor_10_30.convertsResource(src.fhirType()))
return saveResource10(new VersionConvertor_10_30(null).convertResource(src), dstFormat, style); // todo: handle code system?
else
throw new FHIRException("todo: use script based conversion....");
case DSTU2016May:
if (useJava && VersionConvertor_14_30.convertsResource(src.fhirType()))
return saveResource14(VersionConvertor_14_30.convertResource(src), dstFormat, style);
else
throw new FHIRException("Conversion from R3 to 2016May version is not supported for resources of type "+src.fhirType());
case R4:
if (useJava && VersionConvertor_30_40.convertsResource(src.fhirType()))
return saveResource40(VersionConvertor_30_40.convertResource(src, false), dstFormat, style);
else
throw new FHIRException("todo: use script based conversion....");
case STU3: return saveResource30(src, dstFormat, style);
default: throw new FHIRException("FHIR Version 'unknown' is not supported by the inter-version convertor");
}
}
private byte[] convert40(org.hl7.fhir.r4.model.Resource src, FhirFormat dstFormat, FhirPublication dstVersion, boolean useJava, OutputStyle style) throws FHIRException, IOException {
switch (dstVersion) {
case DSTU1: throw new FHIRException("FHIR Version #1 is not supported by the inter-version convertor");
case DSTU2:
if (useJava && VersionConvertor_10_40.convertsResource(src.fhirType()))
return saveResource10(new VersionConvertor_10_40(null).convertResource(src), dstFormat, style); // todo: handle code system?
else
throw new FHIRException("Conversion from R4 to DSTU2 version is not supported for resources of type "+src.fhirType());
case DSTU2016May:
if (useJava && VersionConvertor_14_40.convertsResource(src.fhirType()))
return saveResource14(VersionConvertor_14_40.convertResource(src), dstFormat, style);
else
throw new FHIRException("Conversion from DSTU2 to 2016May version is not supported for resources of type "+src.fhirType());
case R4: return saveResource40(src, dstFormat, style);
case STU3:
if (useJava && VersionConvertor_30_40.convertsResource(src.fhirType()))
return saveResource30(VersionConvertor_30_40.convertResource(src, false), dstFormat, style);
else
throw new FHIRException("todo: use script based conversion....");
default: throw new FHIRException("FHIR Version 'unknown' is not supported by the inter-version convertor");
}
}
}

View File

@ -0,0 +1,36 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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.exceptions.FHIRException;
public interface VersionConvertorAdvisor30 {
boolean ignoreEntry(org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent src);
// called ?
org.hl7.fhir.dstu2.model.Resource convert(org.hl7.fhir.dstu3.model.Resource resource) throws FHIRException;
// called when an r2 value set has a codeSystem in it
void handleCodeSystem(org.hl7.fhir.dstu3.model.CodeSystem tgtcs, org.hl7.fhir.dstu3.model.ValueSet source) throws FHIRException;
org.hl7.fhir.dstu3.model.CodeSystem getCodeSystem(org.hl7.fhir.dstu3.model.ValueSet src) throws FHIRException;
}

View File

@ -0,0 +1,38 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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.exceptions.FHIRException;
public interface VersionConvertorAdvisor40 {
boolean ignoreEntry(org.hl7.fhir.r4.model.Bundle.BundleEntryComponent src);
// called ?
org.hl7.fhir.dstu2.model.Resource convertR2(org.hl7.fhir.r4.model.Resource resource) throws FHIRException;
org.hl7.fhir.dstu2016may.model.Resource convertR2016May(org.hl7.fhir.r4.model.Resource resource) throws FHIRException;
org.hl7.fhir.dstu3.model.Resource convertR3(org.hl7.fhir.r4.model.Resource resource) throws FHIRException;
// called when an r2 value set has a codeSystem in it
void handleCodeSystem(org.hl7.fhir.r4.model.CodeSystem tgtcs, org.hl7.fhir.r4.model.ValueSet source) throws FHIRException;
org.hl7.fhir.r4.model.CodeSystem getCodeSystem(org.hl7.fhir.r4.model.ValueSet src) throws FHIRException;
}

View File

@ -0,0 +1,89 @@
package org.hl7.fhir.convertors;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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 class VersionConvertorConstants {
public final static String IG_DEPENDSON_PACKAGE_EXTENSION = "http://hl7.org/fhir/4.0/StructureDefinition/extension-ImplentationGuide.dependency.packageId";
public final static String IG_DEPENDSON_VERSION_EXTENSION = "http://hl7.org/fhir/4.0/StructureDefinition/extension-ImplentationGuide.dependency.version";
public final static String MODIFIER_REASON_EXTENSION = "http://hl7.org/fhir/4.0/StructureDefinition/extension-ElementDefinition.isModifierReason";
public final static String MODIFIER_TAKEN = "http://hl7.org/fhir/4.0/StructureDefinition/extension-MedicationStatment.taken";
public final static String MODIFIER_REASON_LEGACY = "No Modifier Reason provideed in previous versions of FHIR";
public static String refToVS(String url) {
if (url == null)
return null;
if (url.equals("http://www.genenames.org"))
return "http://hl7.org/fhir/ValueSet/genenames";
else if (url.equals("http://varnomen.hgvs.org/"))
return "http://hl7.org/fhir/ValueSet/variants";
else if (url.equals("http://www.ncbi.nlm.nih.gov/nuccore?db=nuccore"))
return "http://hl7.org/fhir/ValueSet/ref-sequences";
else if (url.equals("http://www.ensembl.org/"))
return "http://hl7.org/fhir/ValueSet/ensembl";
else if (url.equals("http://www.ncbi.nlm.nih.gov/clinvar/variation"))
return "http://hl7.org/fhir/ValueSet/clinvar";
else if (url.equals("http://cancer.sanger.ac.uk/cancergenome/projects/cosmic/"))
return "http://hl7.org/fhir/ValueSet/cosmic";
else if (url.equals("http://www.ncbi.nlm.nih.gov/projects/SNP/"))
return "http://hl7.org/fhir/ValueSet/bbsnp";
else if (url.equals("http://www.sequenceontology.org/"))
return "http://hl7.org/fhir/ValueSet/sequenceontology";
else if (url.equals("http://www.ebi.ac.uk/"))
return "http://hl7.org/fhir/ValueSet/allelename";
else if (url.equals("https://www.iso.org/iso-4217-currency-codes.html"))
return "http://hl7.org/fhir/ValueSet/currencies";
else if (url.equals("http://www.rfc-editor.org/bcp/bcp13.txt"))
return "http://hl7.org/fhir/ValueSet/mimetypes";
else
return url;
}
public static String vsToRef(String url) {
if (url == null)
return null;
if (url.equals("http://hl7.org/fhir/ValueSet/genenames"))
return "http://www.genenames.org";
else if (url.equals("http://hl7.org/fhir/ValueSet/variants"))
return "http://varnomen.hgvs.org/";
else if (url.equals("http://hl7.org/fhir/ValueSet/ref-sequences"))
return "http://www.ncbi.nlm.nih.gov/nuccore?db=nuccore";
else if (url.equals("http://hl7.org/fhir/ValueSet/ensembl"))
return "http://www.ensembl.org/";
else if (url.equals("http://hl7.org/fhir/ValueSet/clinvar"))
return "http://www.ncbi.nlm.nih.gov/clinvar/variation";
else if (url.equals("http://hl7.org/fhir/ValueSet/cosmic"))
return "http://cancer.sanger.ac.uk/cancergenome/projects/cosmic/";
else if (url.equals("http://hl7.org/fhir/ValueSet/bbsnp"))
return "http://www.ncbi.nlm.nih.gov/projects/SNP/";
else if (url.equals("http://hl7.org/fhir/ValueSet/sequenceontology"))
return "http://www.sequenceontology.org/";
else if (url.equals("http://hl7.org/fhir/ValueSet/allelename"))
return "http://www.ebi.ac.uk/";
else if (url.equals("http://hl7.org/fhir/ValueSet/currencies"))
return "https://www.iso.org/iso-4217-currency-codes.html";
else if (url.equals("http://hl7.org/fhir/ValueSet/mimetypes"))
return "http://www.rfc-editor.org/bcp/bcp13.txt";
else
return null;
}
}

View File

@ -0,0 +1,334 @@
package org.hl7.fhir.convertors.misc;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.lang3.CharUtils;
import org.hl7.fhir.dstu3.formats.IParser.OutputStyle;
import org.hl7.fhir.dstu3.formats.XmlParser;
import org.hl7.fhir.dstu3.model.ElementDefinition;
import org.hl7.fhir.dstu3.model.Enumerations.PublicationStatus;
import org.hl7.fhir.dstu3.model.StructureDefinition;
import org.hl7.fhir.utilities.xml.XMLUtil;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
public class ADLImporter {
public class Cardinality {
private String min;
private String max;
}
public class TextSet {
private String text;
private String description;
private String comment;
public String getText() {
return text;
}
public String getDescription() {
return description;
}
public String getComment() {
return comment;
}
public void setText(String value) {
this.text = value;
}
public void setDescription(String value) {
this.description = value;
}
public void setComment(String value) {
this.comment = value;
}
}
public class NodeTreeEntry {
private String name;
private String atCode;
private String typeName;
private Cardinality cardinality;
private List<NodeTreeEntry> children = new ArrayList<NodeTreeEntry>();
}
private String source;
private String dest;
private String config;
private String info;
private Element adl;
private Map<String, TextSet> texts = new HashMap<String, TextSet>();
private Element adlConfig;
public static void main(String[] args) throws Exception {
ADLImporter self = new ADLImporter();
self.source = getParam(args, "source");
self.dest = getParam(args, "dest");
self.config = getParam(args, "config");
self.info = getParam(args, "info");
if (self.source == null || self.dest == null || self.config == null) {
System.out.println("ADL to FHIR StructureDefinition Converter");
System.out.println("This tool takes 4 parameters:");
System.out.println("-source: ADL 1.4 XML representation of an archetype (required)");
System.out.println("-dest: filename of structure definition to produce (required)");
System.out.println("-config: filename of OpenEHR/FHIR knowlege base (required)");
System.out.println("-info: filename of additional knowlege for this adl file (optional)");
} else {
self.execute();
}
}
private static String getParam(String[] args, String name) {
for (int i = 0; i < args.length - 1; i++) {
if (args[i].equals("-"+name)) {
return args[i+1];
}
}
return null;
}
private void execute() throws Exception {
// load config
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
adlConfig = builder.parse(new FileInputStream(config)).getDocumentElement();
// load ADL
builder = factory.newDocumentBuilder();
adl = builder.parse(new FileInputStream(source)).getDocumentElement();
check("root", adl.getNamespaceURI(), "http://schemas.openehr.org/v1", "Wrong namespace for ADL XML");
check("root", adl.getNodeName(), "archetype", "Wrong XML for ADL XML");
check("root", XMLUtil.getNamedChild(adl, "adl_version").getTextContent(), "1.4", "unsupported ADL version");
String id = XMLUtil.getFirstChild(XMLUtil.getNamedChild(adl, "archetype_id")).getTextContent().split("\\.")[1];
// create structure definition
StructureDefinition sd = new StructureDefinition();
sd.setId(id);
// populate metadata
Element description = XMLUtil.getNamedChild(adl, "description");
Element details = XMLUtil.getNamedChild(description, "details");
sd.setDescription(XMLUtil.getNamedChild(details, "purpose").getTextContent());
sd.setCopyright(XMLUtil.getNamedChild(details, "copyright").getTextContent());
sd.setPurpose("Use:\r\n"+XMLUtil.getNamedChild(details, "use").getTextContent()+"\r\n\r\nMisuse:\r\n"+XMLUtil.getNamedChild(details, "misuse").getTextContent());
List<Element> set = new ArrayList<Element>();
XMLUtil.getNamedChildren(details, "keywords", set);
for (Element e : set)
sd.addKeyword().setDisplay(e.getTextContent());
String status = XMLUtil.getNamedChild(description, "lifecycle_state").getTextContent();
if ("CommitteeDraft".equals(status) || "AuthorDraft".equals(status))
sd.setStatus(PublicationStatus.DRAFT);
else
throw new Exception("Unknown life cycle state "+XMLUtil.getNamedChild(description, "lifecycle_state").getTextContent());
// load texts from ontology
Element ontology = XMLUtil.getNamedChild(adl, "ontology");
Element term_definitions = XMLUtil.getNamedChild(ontology, "term_definitions");
set.clear();
XMLUtil.getNamedChildren(term_definitions, "items", set);
for (Element item : set) {
processTextItem(item);
}
// load data and protocol
Element definition = XMLUtil.getNamedChild(adl, "definition");
NodeTreeEntry root = new NodeTreeEntry();
root.typeName = XMLUtil.getNamedChild(definition, "rm_type_name").getTextContent();
root.atCode = XMLUtil.getNamedChild(definition, "node_id").getTextContent();
root.name = generateToken(root.atCode, true);
sd.setName(root.name);
root.cardinality = readCardinality("root", XMLUtil.getNamedChild(definition, "occurrences"));
set.clear();
XMLUtil.getNamedChildren(definition, "attributes", set);
for (Element item : set) {
// we're actually skipping this level - we don't care about data protocol etc.
Element attributes = item; // XMLUtil.getNamedChild(XMLUtil.getNamedChild(item, "children"), "attributes");
loadChildren(root.atCode, root, attributes);
}
dumpChildren("", root);
genElements(sd, root.name, root);
// save
new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(dest), sd);
System.out.println("done. saved as "+dest);
}
private void genElements(StructureDefinition sd, String path, NodeTreeEntry item) throws Exception {
ElementDefinition ed = sd.getSnapshot().addElement();
ed.setPath(path);
ed.setMax(item.cardinality.max);
ed.setMin(Integer.parseInt(item.cardinality.min));
ed.setShort(texts.get(item.atCode).text);
ed.setDefinition(texts.get(item.atCode).description);
ed.setComment(texts.get(item.atCode).comment);
Element te = findTypeElement(item.typeName);
if (te.hasAttribute("profile"))
ed.addType().setCode(te.getAttribute("fhir")).setProfile(te.getAttribute("profile"));
else
ed.addType().setCode(te.getAttribute("fhir"));
ed.getBase().setPath(ed.getPath()).setMin(ed.getMin()).setMax(ed.getMax());
for (NodeTreeEntry child : item.children) {
genElements(sd, path+"."+child.name, child);
}
}
private Element findTypeElement(String typeName) throws Exception {
Element dataTypes = XMLUtil.getNamedChild(adlConfig, "dataTypes");
List<Element> set = new ArrayList<Element>();
XMLUtil.getNamedChildren(dataTypes, "dataType", set);
for (Element e : set) {
if (typeName.equals(e.getAttribute("name")))
return e;
}
throw new Exception("No FHIR equivalent found for "+typeName);
}
private void dumpChildren(String prefix, NodeTreeEntry item) throws Exception {
Element te = findTypeElement(item.typeName);
if (te.hasAttribute("profile"))
System.out.println(prefix+item.atCode+" ["+item.cardinality.min+".."+item.cardinality.max+"]:"+te.getAttribute("fhir")+"{"+te.getAttribute("profile")+"} // "+item.name +" = " +texts.get(item.atCode).text);
else
System.out.println(prefix+item.atCode+" ["+item.cardinality.min+".."+item.cardinality.max+"]:"+te.getAttribute("fhir")+" // "+item.name +" = " +texts.get(item.atCode).text);
for (NodeTreeEntry child : item.children)
dumpChildren(prefix+" ", child);
}
private void loadChildren(String path, NodeTreeEntry parent, Element attributes) throws DOMException, Exception {
List<Element> set = new ArrayList<Element>();
XMLUtil.getNamedChildren(attributes, "children", set);
for (Element e : set) {
NodeTreeEntry item = new NodeTreeEntry();
item.typeName = XMLUtil.getNamedChild(e, "rm_type_name").getTextContent();
item.atCode = XMLUtil.getNamedChild(e, "node_id").getTextContent();
item.name = generateToken(item.atCode, false);
item.cardinality = readCardinality(path+"/"+item.atCode, XMLUtil.getNamedChild(e, "occurrences"));
parent.children.add(item);
Element attr = XMLUtil.getNamedChild(e, "attributes");
String type = attr.getAttribute("xsi:type");
if ("C_SINGLE_ATTRIBUTE".equals(type)) {
check(path, item.typeName, "ELEMENT", "type for simple element: "+item.typeName);
checkCardSingle(path, XMLUtil.getNamedChild(attr, "existence"));
Element c = XMLUtil.getNamedChild(attr, "children");
checkCardSingle(path, XMLUtil.getNamedChild(c, "occurrences"));
item.typeName = XMLUtil.getNamedChild(c, "rm_type_name").getTextContent();
} else {
check(path, item.typeName, "CLUSTER", "type for complex element");
loadChildren(path+"/"+item.atCode, item, attr);
}
}
}
private String generateToken(String atCode, boolean upFirst) {
if (!texts.containsKey(atCode))
return atCode;
String text = texts.get(atCode).getText();
boolean lastText = false;
StringBuilder b = new StringBuilder();
for (char c : text.toCharArray()) {
boolean ok = CharUtils.isAscii(c);
if (ok)
if (b.length() == 0)
ok = Character.isAlphabetic(c);
else
ok = Character.isAlphabetic(c) || Character.isDigit(c);
if (!ok) {
lastText = false;
} else {
if (!lastText && (b.length() > 0 || upFirst))
b.append(Character.toUpperCase(c));
else
b.append(Character.toLowerCase(c));
lastText = true;
}
}
return b.toString();
}
private void checkCardSingle(String path, Element element) throws DOMException, Exception {
check(path, XMLUtil.getNamedChild(element, "lower_included").getTextContent(), "true", "Cardinality check");
check(path, XMLUtil.getNamedChild(element, "upper_included").getTextContent(), "true", "Cardinality check");
check(path, XMLUtil.getNamedChild(element, "lower_unbounded").getTextContent(), "false", "Cardinality check");
check(path, XMLUtil.getNamedChild(element, "upper_unbounded").getTextContent(), "false", "Cardinality check");
check(path, XMLUtil.getNamedChild(element, "lower").getTextContent(), "1", "Cardinality check");
check(path, XMLUtil.getNamedChild(element, "upper").getTextContent(), "1", "Cardinality check");
}
private Cardinality readCardinality(String path, Element element) throws DOMException, Exception {
check(path, XMLUtil.getNamedChild(element, "lower_included").getTextContent(), "true", "Cardinality check");
if (XMLUtil.getNamedChild(element, "upper_included") != null)
check(path, XMLUtil.getNamedChild(element, "upper_included").getTextContent(), "true", "Cardinality check");
check(path, XMLUtil.getNamedChild(element, "lower_unbounded").getTextContent(), "false", "Cardinality check");
Cardinality card = new Cardinality();
card.min = XMLUtil.getNamedChild(element, "lower").getTextContent();
if ("true".equals(XMLUtil.getNamedChild(element, "upper_unbounded").getTextContent()))
card.max = "*";
else
card.max = XMLUtil.getNamedChild(element, "upper").getTextContent();
return card;
}
private void processTextItem(Element item) throws Exception {
String atcode = item.getAttribute("code");
TextSet ts = new TextSet();
List<Element> set = new ArrayList<Element>();
XMLUtil.getNamedChildren(item, "items", set);
for (Element e : set) {
String code = e.getAttribute("id");
if (code.equals("text"))
ts.setText(e.getTextContent());
else if (code.equals("description"))
ts.setDescription(e.getTextContent());
else if (code.equals("comment"))
ts.setComment(e.getTextContent());
else
throw new Exception("unknown code "+code);
}
texts.put(atcode, ts);
}
private void check(String path, String found, String expected, String message) throws Exception {
if (!expected.equals(found.trim()))
throw new Exception(message+". Expected '"+expected+"' but found '"+found.trim()+"', at "+path);
}
}

View File

@ -0,0 +1,282 @@
package org.hl7.fhir.convertors.misc;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
import org.hl7.fhir.utilities.xml.XMLUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class CDAUtilities {
private Document doc;
public CDAUtilities(InputStream stream) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
doc = builder.parse(stream);
basicChecks();
}
private void basicChecks() throws Exception {
Element e = doc.getDocumentElement();
rule(e.getNamespaceURI().equals("urn:hl7-org:v3"), "CDA namespace must be ");
rule(e.getNodeName().equals("ClinicalDocument"), "CDA root name must be ClinicalDocument");
}
private void rule(boolean test, String message) throws Exception {
if (!test)
throw new Exception(message);
}
public Element getElement() {
return doc.getDocumentElement();
}
public void checkTemplateId(Element e, String templateId) throws Exception {
rule(hasTemplateId(e, templateId), "Template Id '"+templateId+"' not found");
}
public Element getChild(Element e, String[] names) throws Exception {
for (String n : names) {
if (e == null)
return null;
e = getChild(e, n);
}
return e;
}
public Element getChild(Element element, String name) throws Exception {
if (element == null)
return null;
Element e = null;
Node n = element.getFirstChild();
while (n != null) {
if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals(name)) {
if (e == null) {
e = (Element) n;
} else {
throw new Exception("multiple matches found for "+name);
}
}
n = n.getNextSibling();
}
return e;
}
public Element getChildByAttribute(Element element, String name, String attrname, String value) throws Exception {
if (element == null)
return null;
Element e = null;
Node n = element.getFirstChild();
while (n != null) {
if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals(name) && value.equals(((Element) n).getAttribute(attrname))) {
if (e == null) {
e = (Element) n;
} else {
throw new Exception("multiple matches found for "+name);
}
}
n = n.getNextSibling();
}
return e;
}
public List<Element> getChildren(Element element, String name) {
List<Element> l = new ArrayList<Element>();
if (element != null) {
Node n = element.getFirstChild();
while (n != null) {
if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals(name)) {
l.add((Element) n);
}
n = n.getNextSibling();
}
}
return l;
}
public Element getDescendent(Element element, String path) throws Exception {
String[] p = path.split("\\/");
return getDescendent(element, p);
}
public Element getDescendent(Element e, String[] path) throws Exception {
for (String n : path) {
if (e == null)
return e;
e = getChild(e, n);
}
return e;
}
public boolean hasTemplateId(Element e, String tid) {
if (e == null)
return false;
boolean found = false;
Node n = e.getFirstChild();
while (n != null && !found) {
if (n.getNodeType() == Node.ELEMENT_NODE && n.getNodeName().equals("templateId") && tid.equals(((Element) n).getAttribute("root")))
found = true;
n = n.getNextSibling();
}
return found;
}
public String getStatus(Element act) throws Exception {
if (act == null)
return null;
Element sc = getChild(act, "statusCode");
if (sc == null)
return null;
else
return sc.getAttribute("code");
}
public String getSeverity(Element observation) throws Exception {
for (Element e : getChildren(observation, "entryRelationship")) {
Element child = getChild(e, "observation");
if (hasTemplateId(child, "2.16.840.1.113883.10.20.22.4.8"))
return getChild(child, "value").getAttribute("code");
}
return null;
}
public String showTemplateIds(Element element) {
List<Element> list = getChildren(element, "templateId");
CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
for (Element e : list) {
if (e.hasAttribute("extension"))
b.append(e.getAttribute("root")+"::"+e.getAttribute("extension"));
else
b.append(e.getAttribute("root"));
}
return b.toString();
}
public Element getlastChild(Element e) {
Node n = e.getLastChild();
while (n != null && n.getNodeType() != Node.ELEMENT_NODE)
n = n.getPreviousSibling();
return n == null ? null : (Element) n;
}
/**
* This method looks up an object by it's id, and only returns it if has a child by the given name
* (resolving identifier based cross references)
*
* @param id
* @param childName
* @return
* @throws Exception
*/
public Element getById(Element id, String childName) throws Exception {
return getById(doc.getDocumentElement(), id, childName);
}
private Element getById(Element e, Element id, String childName) throws Exception {
Element c = XMLUtil.getFirstChild(e);
while (c != null) {
Element i = getChild(c, "id");
if (i != null && matchesAsId(i, id) && getChild(c, childName) != null)
return c;
Element m = getById(c, id, childName);
if (m != null)
return m;
c = XMLUtil.getNextSibling(c);
}
return null;
}
private boolean matchesAsId(Element i1, Element i2) {
String r1 = i1.getAttribute("root");
String r2 = i2.getAttribute("root");
String e1 = i1.getAttribute("extension");
String e2 = i2.getAttribute("extension");
return (r1 != null && r1.equals(r2)) && ((e1 == null && e2 == null) || (e1 != null && e1.equals(e2)));
}
public Element getByXmlId(String id) {
return getByXmlId(doc.getDocumentElement(), id);
}
private Element getByXmlId(Element e, String value) {
Element c = XMLUtil.getFirstChild(e);
while (c != null) {
String id = c.getAttribute("ID");
if (id != null && id.equals(value))
return c;
Element m = getByXmlId(c, value);
if (m != null)
return m;
c = XMLUtil.getNextSibling(c);
}
return null;
}
}

View File

@ -0,0 +1,128 @@
package org.hl7.fhir.convertors.misc;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.xml.XMLUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class CKMImporter {
private String ckm;
private String dest;
private String config;
private String info;
public static void main(String[] args) throws Exception {
CKMImporter self = new CKMImporter();
self.ckm = getParam(args, "ckm");
self.dest = getParam(args, "dest");
self.config = getParam(args, "config");
self.info = getParam(args, "info");
if (self.ckm == null || self.dest == null || self.config == null) {
System.out.println("ADL to FHIR StructureDefinition Converter");
System.out.println("This tool takes 4 parameters:");
System.out.println("-ckm: Baase URL of CKM");
System.out.println("-dest: folder for output");
System.out.println("-config: filename of OpenEHR/FHIR knowlege base (required)");
System.out.println("-info: folder for additional knowlege of archetypes");
} else {
self.execute();
}
}
private static String getParam(String[] args, String name) {
for (int i = 0; i < args.length - 1; i++) {
if (args[i].equals("-"+name)) {
return args[i+1];
}
}
return null;
}
private void execute() throws Exception {
List<String> ids = new ArrayList<String>();
Document xml = loadXml(ckm + "/services/ArchetypeFinderBean/getAllArchetypeIds");
Element e = XMLUtil.getFirstChild(xml.getDocumentElement());
while (e != null) {
ids.add(e.getTextContent());
e = XMLUtil.getNextSibling(e);
}
// for (String id : ids) {
// downloadArchetype(id);
// }
for (String id : ids) {
processArchetype(id);
}
}
private void downloadArchetype(String id) throws Exception {
System.out.println("Fetch "+id);
Document sxml = loadXml(ckm+"/services/ArchetypeFinderBean/getArchetypeInXML?archetypeId="+id);
Element e = XMLUtil.getFirstChild(sxml.getDocumentElement());
String src = Utilities.path("c:\\temp", id+".xml");
TextFile.stringToFile(e.getTextContent(), src);
}
private void processArchetype(String id) throws Exception {
System.out.println("Process "+id);
String cfg = info == null ? null : Utilities.path(info, id+".config");
String src = Utilities.path("c:\\temp", id+".xml");
String dst = Utilities.path(dest, id+".xml");
if (!new File(src).exists())
downloadArchetype(id);
if (cfg != null && new File(cfg).exists())
ADLImporter.main(new String[] {"-source", src, "-dest", dst, "-config", config, "-info", cfg});
else
ADLImporter.main(new String[] {"-source", src, "-dest", dst, "-config", config});
}
private Document loadXml(String address) throws Exception {
URL url = new URL(address);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
InputStream xml = connection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
return db.parse(xml);
}
}

View File

@ -0,0 +1,34 @@
package org.hl7.fhir.convertors.misc;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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 class CcdaExtensions {
public final static String DAF_NAME_RACE = "http://hl7.org/fhir/StructureDefinition/us-core-race";
public final static String DAF_NAME_ETHNICITY = "http://hl7.org/fhir/StructureDefinition/us-core-ethnicity";
public final static String BASE = "http://hl7.org/ccda";
public final static String NAME_RELIGION = BASE+"/religious-affiliation";
public final static String NAME_BIRTHPLACE = BASE+"birthplace";
public final static String NAME_LANG_PROF = BASE+"proficiency-level";
}

View File

@ -0,0 +1,648 @@
package org.hl7.fhir.convertors.misc;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.fhir.ucum.UcumService;
import org.hl7.fhir.dstu3.model.Address;
import org.hl7.fhir.dstu3.model.Address.AddressUse;
import org.hl7.fhir.dstu3.model.CodeableConcept;
import org.hl7.fhir.dstu3.model.Coding;
import org.hl7.fhir.dstu3.model.ContactPoint;
import org.hl7.fhir.dstu3.model.ContactPoint.ContactPointSystem;
import org.hl7.fhir.dstu3.model.ContactPoint.ContactPointUse;
import org.hl7.fhir.dstu3.model.DateTimeType;
import org.hl7.fhir.dstu3.model.DateType;
import org.hl7.fhir.dstu3.model.Enumerations.AdministrativeGender;
import org.hl7.fhir.dstu3.model.Factory;
import org.hl7.fhir.dstu3.model.HumanName;
import org.hl7.fhir.dstu3.model.HumanName.NameUse;
import org.hl7.fhir.dstu3.model.Identifier;
import org.hl7.fhir.dstu3.model.InstantType;
import org.hl7.fhir.dstu3.model.Period;
import org.hl7.fhir.dstu3.model.Quantity;
import org.hl7.fhir.dstu3.model.Range;
import org.hl7.fhir.dstu3.model.SimpleQuantity;
import org.hl7.fhir.dstu3.model.StringType;
import org.hl7.fhir.dstu3.model.Timing;
import org.hl7.fhir.dstu3.model.Timing.EventTiming;
import org.hl7.fhir.dstu3.model.Timing.TimingRepeatComponent;
import org.hl7.fhir.dstu3.model.Timing.UnitsOfTime;
import org.hl7.fhir.dstu3.model.Type;
import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
import org.hl7.fhir.utilities.OIDUtils;
import org.hl7.fhir.utilities.Utilities;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class Convert {
private CDAUtilities cda;
private UcumService ucumSvc;
private Set<String> oids = new HashSet<String>();
private String defaultTimezone;
private boolean generateMissingExtensions;
public Convert(CDAUtilities cda, UcumService ucumSvc, String defaultTimezone) {
super();
this.cda = cda;
this.ucumSvc = ucumSvc;
this.defaultTimezone = defaultTimezone;
}
public Identifier makeIdentifierFromII(Element e) throws Exception {
Identifier id = new Identifier();
String r = e.getAttribute("root");
String ex;
if (e.hasAttribute("extension") && Utilities.noString(e.getAttribute("extension"))) {
if (generateMissingExtensions)
ex = UUID.randomUUID().toString();
else
throw new Exception("Broken identifier - extension is blank");
} else
ex = e.getAttribute("extension");
if (Utilities.noString(ex)) {
id.setSystem("urn:ietf:rfc:3986");
if (isGuid(r))
id.setValue("urn:uuid:"+r);
else if (UriForOid(r) != null)
id.setValue(UriForOid(r));
else
id.setValue(UriForOid(r));
} else {
if (isGuid(r))
id.setSystem("urn:uuid:"+r);
else if (UriForOid(r) != null)
id.setSystem(UriForOid(r));
else
id.setSystem("urn:oid:"+r);
id.setValue(ex);
}
return id;
}
public String makeURIfromII(Element e) {
String r = e.getAttribute("root");
if (Utilities.noString(e.getAttribute("extension"))) {
if (isGuid(r))
return "urn:uuid:"+r;
else if (UriForOid(r) != null)
return UriForOid(r);
else
return UriForOid(r);
} else {
if (isGuid(r))
return "urn:uuid:"+r+"::"+e.getAttribute("extension");
else if (UriForOid(r) != null)
return UriForOid(r)+"::"+e.getAttribute("extension");
else
return "urn:oid:"+r+"::"+e.getAttribute("extension");
}
}
private String UriForOid(String r) {
String uri = OIDUtils.getUriForOid(r);
if (uri != null)
return uri;
else {
oids.add(r);
return "urn:oid:"+r;
}
}
public boolean isGuid(String r) {
return r.matches("[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}");
}
public InstantType makeInstantFromTS(Element child) throws Exception {
InstantType i = InstantType.parseV3(child.getAttribute("value"));
return i;
}
public CodeableConcept makeCodeableConceptFromCD(Element cv) throws Exception {
if (cv == null)
return null;
CodeableConcept cc = new CodeableConcept();
cc.addCoding(makeCodingFromCV(cv));
for (Element e : cda.getChildren(cv, "translation"))
cc.addCoding(makeCodingFromCV(e));
if (cda.getChild(cv, "originalText") != null) {
Element ote = cda.getChild(cv, "originalText");
// if (cda.getChild(ote, "reference") != null) {
// if (cda.getChild(ote, "reference").getAttribute("value").startsWith("#")) {
// Element t = cda.getByXmlId(cda.getChild(ote, "reference").getAttribute("value").substring(1));
// String ot = t.getTextContent().trim();
// cc.setText(Utilities.noString(ot) ? null : ot);
// } else
// throw new Exception("external references not handled yet "+cda.getChild(ote, "reference").getAttribute("value"));
// } else {
String ot = ote.getTextContent().trim();
cc.setText(Utilities.noString(ot) ? null : ot);
//}
}
return cc;
}
public Coding makeCodingFromCV(Element cd) throws Exception {
if (cd == null || Utilities.noString(cd.getAttribute("code")))
return null;
Coding c = new Coding();
c.setCode(cd.getAttribute("code"));
c.setDisplay(cd.getAttribute("displayName"));
String r = cd.getAttribute("codeSystem");
String uri = getUriForOID(r);
if (uri != null)
c.setSystem(uri);
else if (isGuid(r))
c.setSystem("urn:uuid:"+r);
else if (UriForOid(r) != null)
c.setSystem(UriForOid(r));
else
c.setSystem("urn:oid:"+r);
return c;
}
private String getUriForOID(String r) {
if (r.equals("2.16.840.1.113883.6.1"))
return "http://loinc.org";
if (r.equals("2.16.840.1.113883.6.96"))
return "http://snomed.info/sct";
return null;
}
public Address makeAddressFromAD(Element e) {
if (e == null)
return null;
Address a = new Address();
String use = e.getAttribute("use");
if (use != null) {
if (use.equals("H") || use.equals("HP") || use.equals("HV"))
a.setUse(AddressUse.HOME);
else if (use.equals("WP") || use.equals("DIR") || use.equals("PUB"))
a.setUse(AddressUse.WORK);
else if (use.equals("TMP"))
a.setUse(AddressUse.TEMP);
else if (use.equals("BAD"))
a.setUse(AddressUse.OLD);
}
Node n = e.getFirstChild();
while (n != null) {
if (n.getNodeType() == Node.ELEMENT_NODE) {
String v = n.getTextContent();
if (n.getLocalName().equals("additionalLocator"))
a.getLine().add(makeString(v));
// else if (e.getLocalName().equals("unitID"))
// else if (e.getLocalName().equals("unitType"))
else if (n.getLocalName().equals("deliveryAddressLine"))
a.getLine().add(makeString(v));
// else if (e.getLocalName().equals("deliveryInstallationType"))
// else if (e.getLocalName().equals("deliveryInstallationArea"))
// else if (e.getLocalName().equals("deliveryInstallationQualifier"))
// else if (e.getLocalName().equals("deliveryMode"))
// else if (e.getLocalName().equals("deliveryModeIdentifier"))
else if (n.getLocalName().equals("streetAddressLine"))
a.getLine().add(makeString(v));
// else if (e.getLocalName().equals("houseNumber"))
// else if (e.getLocalName().equals("buildingNumberSuffix"))
// else if (e.getLocalName().equals("postBox"))
// else if (e.getLocalName().equals("houseNumberNumeric"))
// else if (e.getLocalName().equals("streetName"))
// else if (e.getLocalName().equals("streetNameBase"))
// else if (e.getLocalName().equals("streetNameType"))
else if (n.getLocalName().equals("direction"))
a.getLine().add(makeString(v));
else if (n.getLocalName().equals("careOf"))
a.getLine().add(makeString(v));
// else if (e.getLocalName().equals("censusTract"))
else if (n.getLocalName().equals("country"))
a.setCountry(v);
//else if (e.getLocalName().equals("county"))
else if (n.getLocalName().equals("city"))
a.setCity(v);
// else if (e.getLocalName().equals("delimiter"))
// else if (e.getLocalName().equals("precinct"))
else if (n.getLocalName().equals("state"))
a.setState(v);
else if (n.getLocalName().equals("postalCode"))
a.setPostalCode(v);
}
n = n.getNextSibling();
}
return a;
}
public StringType makeString(String v) {
StringType s = new StringType();
s.setValue(v);
return s;
}
public ContactPoint makeContactFromTEL(Element e) throws Exception {
if (e == null)
return null;
if (e.hasAttribute("nullFlavor"))
return null;
ContactPoint c = new ContactPoint();
String use = e.getAttribute("use");
if (use != null) {
if (use.equals("H") || use.equals("HP") || use.equals("HV"))
c.setUse(ContactPointUse.HOME);
else if (use.equals("WP") || use.equals("DIR") || use.equals("PUB"))
c.setUse(ContactPointUse.WORK);
else if (use.equals("TMP"))
c.setUse(ContactPointUse.TEMP);
else if (use.equals("BAD"))
c.setUse(ContactPointUse.OLD);
}
if (e.getAttribute("value") != null) {
String[] url = e.getAttribute("value").split(":");
if (url.length == 1) {
c.setValue(url[0].trim());
c.setSystem(ContactPointSystem.PHONE);
} else {
if (url[0].equals("tel"))
c.setSystem(ContactPointSystem.PHONE);
else if (url[0].equals("mailto"))
c.setSystem(ContactPointSystem.EMAIL);
else if (e.getAttribute("value").contains(":"))
c.setSystem(ContactPointSystem.OTHER);
else
c.setSystem(ContactPointSystem.PHONE);
c.setValue(url[1].trim());
}
}
return c;
}
public HumanName makeNameFromEN(Element e) {
if (e == null)
return null;
HumanName hn = new HumanName();
String use = e.getAttribute("use");
if (use != null) {
if (use.equals("L"))
hn.setUse(NameUse.USUAL);
else if (use.equals("C"))
hn.setUse(NameUse.OFFICIAL);
else if (use.equals("P") || use.equals("A"))
hn.setUse(NameUse.ANONYMOUS);
else if (use.equals("TMP"))
hn.setUse(NameUse.TEMP);
else if (use.equals("BAD"))
hn.setUse(NameUse.OLD);
}
Node n = e.getFirstChild();
while (n != null) {
if (n.getNodeType() == Node.ELEMENT_NODE) {
String v = n.getTextContent();
if (n.getLocalName().equals("family"))
hn.setFamilyElement(makeString(v));
else if (n.getLocalName().equals("given"))
hn.getGiven().add(makeString(v));
else if (n.getLocalName().equals("prefix"))
hn.getPrefix().add(makeString(v));
else if (n.getLocalName().equals("suffix"))
hn.getSuffix().add(makeString(v));
}
n = n.getNextSibling();
}
return hn;
}
public DateTimeType makeDateTimeFromTS(Element ts) throws Exception {
if (ts == null)
return null;
String v = ts.getAttribute("value");
if (Utilities.noString(v))
return null;
if (v.length() > 8 && !hasTimezone(v))
v += defaultTimezone;
DateTimeType d = DateTimeType.parseV3(v);
return d;
}
private boolean hasTimezone(String v) {
return v.contains("+") || v.contains("-") || v.endsWith("Z");
}
public DateType makeDateFromTS(Element ts) throws Exception {
if (ts == null)
return null;
String v = ts.getAttribute("value");
if (Utilities.noString(v))
return null;
DateType d = DateType.parseV3(v);
return d;
}
public Period makePeriodFromIVL(Element ivl) throws Exception {
if (ivl == null)
return null;
Period p = new Period();
Element low = cda.getChild(ivl, "low");
if (low != null)
p.setStartElement(makeDateTimeFromTS(low));
Element high = cda.getChild(ivl, "high");
if (high != null)
p.setEndElement(makeDateTimeFromTS(high));
if (p.getStartElement() != null || p.getEndElement() != null)
return p;
else
return null;
}
// this is a weird one - where CDA has an IVL, and FHIR has a date
public DateTimeType makeDateTimeFromIVL(Element ivl) throws Exception {
if (ivl == null)
return null;
if (ivl.hasAttribute("value"))
return makeDateTimeFromTS(ivl);
Element high = cda.getChild(ivl, "high");
if (high != null)
return makeDateTimeFromTS(high);
Element low = cda.getChild(ivl, "low");
if (low != null)
return makeDateTimeFromTS(low);
return null;
}
public Type makeStringFromED(Element e) throws Exception {
if (e == null)
return null;
if (cda.getChild(e, "reference") != null) {
if (cda.getChild(e, "reference").getAttribute("value").startsWith("#")) {
Element t = cda.getByXmlId(cda.getChild(e, "reference").getAttribute("value").substring(1));
String ot = t.getTextContent().trim();
return Utilities.noString(ot) ? null : Factory.newString_(ot);
} else
throw new Exception("external references not handled yet "+cda.getChild(e, "reference").getAttribute("value"));
}
return Factory.newString_(e.getTextContent());
}
public Type makeTypeFromANY(Element e) throws Exception {
if (e == null)
return null;
String t = e.getAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
if (Utilities.noString(t))
throw new Exception("Missing type on RIM attribute with type any");
if (t.equals("CD") || t.equals("CE"))
return makeCodeableConceptFromCD(e);
else if (t.equals("ST"))
return makeStringFromED(e);
else
throw new Exception("Not done yet (type = "+t+")");
}
public Type makeMatchingTypeFromIVL(Element ivl) throws Exception {
if (ivl == null)
return null;
if (ivl.getAttribute("value") != null)
return makeDateTimeFromIVL(ivl);
if (cda.getChild(ivl, "low") != null || cda.getChild(ivl, "high") != null )
return makePeriodFromIVL(ivl);
throw new Exception("not handled yet");
}
public Type makeCodeableConceptFromNullFlavor(String nf) throws Exception {
// Some nullFlavors have explicit values in value sets. This can only be called where there aren't.
if (nf == null || "".equals(nf))
return null;
if ("NI".equals(nf))
return null; // there's no code for this
if ("NA".equals(nf))
return Factory.newCodeableConcept("unsupported", "http://hl7.org/fhir/data-absent-reason", "Unsupported"); // todo: is this reasonable? Why else would you use N/A?
if ("UNK".equals(nf))
return Factory.newCodeableConcept("unknown", "http://hl7.org/fhir/data-absent-reason", "Unknown");
if ("ASKU".equals(nf))
return Factory.newCodeableConcept("asked", "http://hl7.org/fhir/data-absent-reason", "Asked/Unknown");
if ("NAV".equals(nf))
return Factory.newCodeableConcept("temp", "http://hl7.org/fhir/data-absent-reason", "Temporarily Unavailable");
if ("NASK".equals(nf))
return Factory.newCodeableConcept("notasked", "http://hl7.org/fhir/data-absent-reason", "Not Asked");
if ("MSK".equals(nf))
return Factory.newCodeableConcept("masked", "http://hl7.org/fhir/data-absent-reason", "Masked");
if ("OTH".equals(nf))
return null; // well, what should be done?
return null; // well, what should be done?
}
public Range makeRangeFromIVLPQ(Element ivlpq) throws Exception {
if (ivlpq == null)
return null;
Element low = cda.getChild(ivlpq, "low");
Element high = cda.getChild(ivlpq, "high");
if (low == null && high == null)
return null;
Range r = new Range();
r.setLow(makeSimpleQuantityFromPQ(low, ivlpq.getAttribute("unit")));
r.setHigh(makeSimpleQuantityFromPQ(high, ivlpq.getAttribute("unit")));
return r;
}
public Quantity makeQuantityFromPQ(Element pq) throws Exception {
return makeQuantityFromPQ(pq, null);
}
public Quantity makeQuantityFromPQ(Element pq, String units) throws Exception {
if (pq == null)
return null;
Quantity qty = new Quantity();
String n = pq.getAttribute("value").replace(",", "").trim();
try {
qty.setValue(new BigDecimal(n));
} catch (Exception e) {
throw new Exception("Unable to process value '"+n+"'", e);
}
units = Utilities.noString(pq.getAttribute("unit")) ? units : pq.getAttribute("unit");
if (!Utilities.noString(units)) {
if (ucumSvc == null || ucumSvc.validate(units) != null)
qty.setUnit(units);
else {
qty.setCode(units);
qty.setSystem("http://unitsofmeasure.org");
qty.setUnit(ucumSvc.getCommonDisplay(units));
}
}
return qty;
}
public SimpleQuantity makeSimpleQuantityFromPQ(Element pq, String units) throws Exception {
if (pq == null)
return null;
SimpleQuantity qty = new SimpleQuantity();
String n = pq.getAttribute("value").replace(",", "").trim();
try {
qty.setValue(new BigDecimal(n));
} catch (Exception e) {
throw new Exception("Unable to process value '"+n+"'", e);
}
units = Utilities.noString(pq.getAttribute("unit")) ? units : pq.getAttribute("unit");
if (!Utilities.noString(units)) {
if (ucumSvc == null || ucumSvc.validate(units) != null)
qty.setUnit(units);
else {
qty.setCode(units);
qty.setSystem("http://unitsofmeasure.org");
qty.setUnit(ucumSvc.getCommonDisplay(units));
}
}
return qty;
}
public AdministrativeGender makeGenderFromCD(Element cd) throws Exception {
String code = cd.getAttribute("code");
String system = cd.getAttribute("codeSystem");
if ("2.16.840.1.113883.5.1".equals(system)) {
if ("F".equals(code))
return AdministrativeGender.FEMALE;
if ("M".equals(code))
return AdministrativeGender.MALE;
}
throw new Exception("Unable to read Gender "+system+"::"+code);
}
/*
/entry[COMP]/substanceAdministration[SBADM,EVN]/effectiveTime[type:EIVL_TS]: 389
/entry[COMP]/substanceAdministration[SBADM,EVN]/effectiveTime[type:EIVL_TS]/event: 389
/entry[COMP]/substanceAdministration[SBADM,EVN]/effectiveTime[type:IVL_TS]: 33470
/entry[COMP]/substanceAdministration[SBADM,EVN]/effectiveTime[type:IVL_TS]/high: 20566
/entry[COMP]/substanceAdministration[SBADM,EVN]/effectiveTime[type:IVL_TS]/high[nullFlavor:NA]: 9581
/entry[COMP]/substanceAdministration[SBADM,EVN]/effectiveTime[type:IVL_TS]/low: 32501
/entry[COMP]/substanceAdministration[SBADM,EVN]/effectiveTime[type:IVL_TS]/low[nullFlavor:UNK]: 969
/entry[COMP]/substanceAdministration[SBADM,EVN]/effectiveTime[type:PIVL_TS]: 17911
/entry[COMP]/substanceAdministration[SBADM,EVN]/effectiveTime[type:PIVL_TS]/period: 17911
*/
public Type makeSomethingFromGTS(List<Element> children) throws Exception {
if (children.isEmpty())
return null;
if (children.size() == 1) {
String type = children.get(0).getAttribute("xsi:type");
if (type.equals("IVL_TS"))
return makePeriodFromIVL(children.get(0));
else
throw new Exception("Unknown GTS type '"+type+"'");
}
CommaSeparatedStringBuilder t = new CommaSeparatedStringBuilder();
for (Element c : children)
t.append(c.getAttribute("xsi:type"));
if (t.toString().equals("IVL_TS, PIVL_TS"))
return makeTimingFromBoundedPIVL(children.get(0), children.get(1));
if (t.toString().equals("IVL_TS, EIVL_TS"))
return makeTimingFromBoundedEIVL(children.get(0), children.get(1));
throw new Exception("Unknown GTS pattern '"+t.toString()+"'");
}
private Type makeTimingFromBoundedEIVL(Element ivl, Element eivl) throws Exception {
Timing t = new Timing();
t.setRepeat(new TimingRepeatComponent());
Element e = cda.getChild(eivl, "event");
t.getRepeat().setBounds(makePeriodFromIVL(ivl));
t.getRepeat().addWhen(convertEventTiming(e.getAttribute("code")));
return t;
}
private EventTiming convertEventTiming(String e) throws Exception {
if ("HS".equals(e))
return EventTiming.HS;
throw new Exception("Unknown event "+e);
}
private Timing makeTimingFromBoundedPIVL(Element ivl, Element pivl) throws Exception {
Timing t = new Timing();
t.setRepeat(new TimingRepeatComponent());
Element p = cda.getChild(pivl, "period");
t.getRepeat().setBounds(makePeriodFromIVL(ivl));
t.getRepeat().setPeriod(new BigDecimal(p.getAttribute("value")));
t.getRepeat().setPeriodUnit(convertTimeUnit(p.getAttribute("unit")));
return t;
}
private UnitsOfTime convertTimeUnit(String u) throws Exception {
if ("h".equals(u))
return UnitsOfTime.H;
if ("d".equals(u))
return UnitsOfTime.D;
if ("w".equals(u))
return UnitsOfTime.WK;
throw new Exception("Unknown unit of time "+u);
}
public Set<String> getOids() {
return oids;
}
public boolean isGenerateMissingExtensions() {
return generateMissingExtensions;
}
public void setGenerateMissingExtensions(boolean generateMissingExtensions) {
this.generateMissingExtensions = generateMissingExtensions;
}
}

View File

@ -0,0 +1,26 @@
package org.hl7.fhir.convertors.misc;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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 class ConverterBase {
}

View File

@ -0,0 +1,364 @@
package org.hl7.fhir.convertors.misc;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.hl7.fhir.r4.model.CodeType;
import org.hl7.fhir.r4.model.ContactPoint.ContactPointSystem;
import org.hl7.fhir.r4.formats.IParser.OutputStyle;
import org.hl7.fhir.r4.formats.JsonParser;
import org.hl7.fhir.r4.model.CodeSystem;
import org.hl7.fhir.r4.model.CodeSystem.CodeSystemContentMode;
import org.hl7.fhir.r4.model.CodeSystem.ConceptDefinitionComponent;
import org.hl7.fhir.r4.model.CodeSystem.PropertyType;
import org.hl7.fhir.r4.model.DateTimeType;
import org.hl7.fhir.r4.model.Enumerations.PublicationStatus;
import org.hl7.fhir.r4.terminologies.CodeSystemUtilities;
import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.xml.XMLUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class CountryCodesConverter {
public static void main(String[] args) throws Exception {
CountryCodesConverter self = new CountryCodesConverter();
self.source = args[0];
self.dest = args[1];
self.execute();
}
private String source;
private String dest;
private void execute() throws FileNotFoundException, ParserConfigurationException, SAXException, IOException {
Document src = load();
CodeSystem cs1 = new CodeSystem();
CodeSystem cs2 = new CodeSystem();
CodeSystem cs3 = new CodeSystem();
setMetadata(src, cs1, "iso3166", "urn:iso:std:iso:3166", "", "");
setMetadata(src, cs2, "iso3166-2", "urn:iso:std:iso:3166:-2", "Part2", " Part 2");
cs1.addProperty().setCode("canonical").setDescription("The 2 letter code that identifies the same country (so 2/3/numeric codes can be aligned)").setType(PropertyType.CODE);
cs2.addProperty().setCode("country").setDescription("The 2 letter code that identifies the country for the subdivision").setType(PropertyType.CODE);
for (Element e : XMLUtil.getNamedChildren(src.getDocumentElement(), "country")) {
System.out.println(e.getAttribute("id"));
String c2 = XMLUtil.getNamedChildText(e, "alpha-2-code");
String c3 = XMLUtil.getNamedChildText(e, "alpha-3-code");
String cN = XMLUtil.getNamedChildText(e, "numeric-code");
Element n = XMLUtil.getNamedChildByAttribute(e, "short-name", "lang3code", "eng");
if (n == null)
n = XMLUtil.getNamedChildByAttribute(e, "short-name-upper-case", "lang3code", "eng");
if (n == null)
continue;
String name = n.getTextContent();
n = XMLUtil.getNamedChildByAttribute(e, "full-name", "lang3code", "eng");
if (n == null)
n = XMLUtil.getNamedChildByAttribute(e, "full-name-upper-case", "lang3code", "eng");
if (n == null)
n = XMLUtil.getNamedChildByAttribute(e, "short-name", "lang3code", "eng");
if (n == null)
n = XMLUtil.getNamedChildByAttribute(e, "short-name-upper-case", "lang3code", "eng");
String desc = n.getTextContent();
ConceptDefinitionComponent cc = cs1.addConcept();
cc.setCode(c2);
cc.setDisplay(name);
cc.setDefinition(desc);
poplang(e, cc);
if (c3 != null) {
cc = cs1.addConcept();
cc.setCode(c3);
cc.setDisplay(name);
cc.setDefinition(desc);
cc.addProperty().setCode("canonical").setValue(new CodeType(c2));
poplang(e, cc);
}
if (cN != null) {
cc = cs1.addConcept();
cc.setCode(cN);
cc.setDisplay(name);
cc.setDefinition(desc);
cc.addProperty().setCode("canonical").setValue(new CodeType(c2));
poplang(e, cc);
}
for (Element sd : XMLUtil.getNamedChildren(e, "subdivision")) {
cc = cs2.addConcept();
cc.setCode(XMLUtil.getNamedChildText(sd, "subdivision-code"));
Element l = XMLUtil.getNamedChild(sd, "subdivision-locale");
cc.setDisplay(XMLUtil.getNamedChildText(l, "subdivision-locale-name"));
cc.addProperty().setCode("country").setValue(new CodeType(c2));
}
}
cs1.setCount(cs1.getConcept().size());
cs2.setCount(cs2.getConcept().size());
new JsonParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(Utilities.path(dest, "4.0.0", "package", "CodeSstem-iso3166.json")), cs1);
new JsonParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(Utilities.path(dest, "3.0.1", "package", "CodeSstem-iso3166.json")), cs1); // format hasn't changed
new JsonParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(Utilities.path(dest, "4.0.0", "package", "CodeSstem-iso3166-2.json")), cs2);
new JsonParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(Utilities.path(dest, "3.0.1", "package", "CodeSstem-iso3166-2.json")), cs2); // format hasn't changed
}
public void setMetadata(Document src, CodeSystem cs, String id, String url, String partName, String partTitle) {
cs.setId(id);
cs.setUrl(url);
cs.setName("ISOCountryCodes"+partName);
cs.setTitle("ISO Country Codes (ISO-3166)"+partTitle);
cs.setVersion(XMLUtil.getFirstChild(src.getDocumentElement()).getAttribute("version"));
cs.setStatus(PublicationStatus.ACTIVE);
cs.setExperimental(false);
cs.addContact().setName("FHIR Project Team").addTelecom().setSystem(ContactPointSystem.URL).setValue("http://hl7.org/fhir");
cs.setDateElement(new DateTimeType(src.getDocumentElement().getAttribute("generated")));
cs.setCopyright("Copyright ISO. See https://www.iso.org/obp/ui/#search/code/");
cs.setCaseSensitive(true);
cs.setContent(CodeSystemContentMode.COMPLETE);
cs.setLanguage("en");
}
public void poplang(Element e, ConceptDefinitionComponent cc) {
for (Element el : XMLUtil.getNamedChildren(e, "short-name")) {
if (!el.getAttribute("lang3code").equals("eng")) {
String l2 = lang3To2(el.getAttribute("lang3code"));
if (l2 != null)
cc.addDesignation().setLanguage(l2).setValue(el.getTextContent());
}
}
}
private String lang3To2(String lang) {
if ("abk".equals(lang)) return "ab";
if ("aar".equals(lang)) return "aa";
if ("afr".equals(lang)) return "af";
if ("aka".equals(lang)) return "ak";
if ("sqi".equals(lang)) return "sq";
if ("amh".equals(lang)) return "am";
if ("ara".equals(lang)) return "ar";
if ("arg".equals(lang)) return "an";
if ("hye".equals(lang)) return "hy";
if ("asm".equals(lang)) return "as";
if ("ava".equals(lang)) return "av";
if ("ave".equals(lang)) return "ae";
if ("aym".equals(lang)) return "ay";
if ("aze".equals(lang)) return "az";
if ("bam".equals(lang)) return "bm";
if ("bak".equals(lang)) return "ba";
if ("eus".equals(lang)) return "eu";
if ("bel".equals(lang)) return "be";
if ("ben".equals(lang)) return "bn";
if ("bih".equals(lang)) return "bh";
if ("bis".equals(lang)) return "bi";
if ("bos".equals(lang)) return "bs";
if ("bre".equals(lang)) return "br";
if ("bul".equals(lang)) return "bg";
if ("mya".equals(lang)) return "my";
if ("cat".equals(lang)) return "ca";
if ("khm".equals(lang)) return "km";
if ("cha".equals(lang)) return "ch";
if ("che".equals(lang)) return "ce";
if ("nya".equals(lang)) return "ny";
if ("zho".equals(lang)) return "zh";
if ("chu".equals(lang)) return "cu";
if ("chv".equals(lang)) return "cv";
if ("cor".equals(lang)) return "kw";
if ("cos".equals(lang)) return "co";
if ("cre".equals(lang)) return "cr";
if ("hrv".equals(lang)) return "hr";
if ("ces".equals(lang)) return "cs";
if ("dan".equals(lang)) return "da";
if ("div".equals(lang)) return "dv";
if ("nld".equals(lang)) return "nl";
if ("dzo".equals(lang)) return "dz";
if ("eng".equals(lang)) return "en";
if ("epo".equals(lang)) return "eo";
if ("est".equals(lang)) return "et";
if ("ewe".equals(lang)) return "ee";
if ("fao".equals(lang)) return "fo";
if ("fij".equals(lang)) return "fj";
if ("fin".equals(lang)) return "fi";
if ("fra".equals(lang)) return "fr";
if ("ful".equals(lang)) return "ff";
if ("gla".equals(lang)) return "gd";
if ("glg".equals(lang)) return "gl";
if ("lug".equals(lang)) return "lg";
if ("kat".equals(lang)) return "ka";
if ("deu".equals(lang)) return "de";
if ("ell".equals(lang)) return "el";
if ("grn".equals(lang)) return "gn";
if ("guj".equals(lang)) return "gu";
if ("hat".equals(lang)) return "ht";
if ("hau".equals(lang)) return "ha";
if ("heb".equals(lang)) return "he";
if ("her".equals(lang)) return "hz";
if ("hin".equals(lang)) return "hi";
if ("hmo".equals(lang)) return "ho";
if ("hun".equals(lang)) return "hu";
if ("isl".equals(lang)) return "is";
if ("ido".equals(lang)) return "io";
if ("ibo".equals(lang)) return "ig";
if ("ind".equals(lang)) return "id";
if ("ina".equals(lang)) return "ia";
if ("ile".equals(lang)) return "ie";
if ("iku".equals(lang)) return "iu";
if ("ipk".equals(lang)) return "ik";
if ("gle".equals(lang)) return "ga";
if ("ita".equals(lang)) return "it";
if ("jpn".equals(lang)) return "ja";
if ("jav".equals(lang)) return "jv";
if ("kal".equals(lang)) return "kl";
if ("kan".equals(lang)) return "kn";
if ("kau".equals(lang)) return "kr";
if ("kas".equals(lang)) return "ks";
if ("kaz".equals(lang)) return "kk";
if ("kik".equals(lang)) return "ki";
if ("kin".equals(lang)) return "rw";
if ("kir".equals(lang)) return "ky";
if ("kom".equals(lang)) return "kv";
if ("kon".equals(lang)) return "kg";
if ("kor".equals(lang)) return "ko";
if ("kua".equals(lang)) return "kj";
if ("kur".equals(lang)) return "ku";
if ("lao".equals(lang)) return "lo";
if ("lat".equals(lang)) return "la";
if ("lav".equals(lang)) return "lv";
if ("lim".equals(lang)) return "li";
if ("lin".equals(lang)) return "ln";
if ("lit".equals(lang)) return "lt";
if ("lub".equals(lang)) return "lu";
if ("ltz".equals(lang)) return "lb";
if ("mkd".equals(lang)) return "mk";
if ("mlg".equals(lang)) return "mg";
if ("msa".equals(lang)) return "ms";
if ("mal".equals(lang)) return "ml";
if ("mlt".equals(lang)) return "mt";
if ("glv".equals(lang)) return "gv";
if ("mri".equals(lang)) return "mi";
if ("mar".equals(lang)) return "mr";
if ("mah".equals(lang)) return "mh";
if ("mon".equals(lang)) return "mn";
if ("nau".equals(lang)) return "na";
if ("nav".equals(lang)) return "nv";
if ("ndo".equals(lang)) return "ng";
if ("nep".equals(lang)) return "ne";
if ("nde".equals(lang)) return "nd";
if ("sme".equals(lang)) return "se";
if ("nor".equals(lang)) return "no";
if ("nob".equals(lang)) return "nb";
if ("nno".equals(lang)) return "nn";
if ("oci".equals(lang)) return "oc";
if ("oji".equals(lang)) return "oj";
if ("ori".equals(lang)) return "or";
if ("orm".equals(lang)) return "om";
if ("oss".equals(lang)) return "os";
if ("pli".equals(lang)) return "pi";
if ("pan".equals(lang)) return "pa";
if ("pus".equals(lang)) return "ps";
if ("fas".equals(lang)) return "fa";
if ("pol".equals(lang)) return "pl";
if ("por".equals(lang)) return "pt";
if ("que".equals(lang)) return "qu";
if ("ron".equals(lang)) return "ro";
if ("roh".equals(lang)) return "rm";
if ("run".equals(lang)) return "rn";
if ("rus".equals(lang)) return "ru";
if ("smo".equals(lang)) return "sm";
if ("sag".equals(lang)) return "sg";
if ("san".equals(lang)) return "sa";
if ("srd".equals(lang)) return "sc";
if ("srp".equals(lang)) return "sr";
if ("sna".equals(lang)) return "sn";
if ("iii".equals(lang)) return "ii";
if ("snd".equals(lang)) return "sd";
if ("sin".equals(lang)) return "si";
if ("slk".equals(lang)) return "sk";
if ("slv".equals(lang)) return "sl";
if ("som".equals(lang)) return "so";
if ("nbl".equals(lang)) return "nr";
if ("sot".equals(lang)) return "st";
if ("spa".equals(lang)) return "es";
if ("sun".equals(lang)) return "su";
if ("swa".equals(lang)) return "sw";
if ("ssw".equals(lang)) return "ss";
if ("swe".equals(lang)) return "sv";
if ("tgl".equals(lang)) return "tl";
if ("tah".equals(lang)) return "ty";
if ("tgk".equals(lang)) return "tg";
if ("tam".equals(lang)) return "ta";
if ("tat".equals(lang)) return "tt";
if ("tel".equals(lang)) return "te";
if ("tha".equals(lang)) return "th";
if ("bod".equals(lang)) return "bo";
if ("tir".equals(lang)) return "ti";
if ("ton".equals(lang)) return "to";
if ("tso".equals(lang)) return "ts";
if ("tsn".equals(lang)) return "tn";
if ("tur".equals(lang)) return "tr";
if ("tuk".equals(lang)) return "tk";
if ("twi".equals(lang)) return "tw";
if ("uig".equals(lang)) return "ug";
if ("ukr".equals(lang)) return "uk";
if ("urd".equals(lang)) return "ur";
if ("uzb".equals(lang)) return "uz";
if ("ven".equals(lang)) return "ve";
if ("vie".equals(lang)) return "vi";
if ("vol".equals(lang)) return "vo";
if ("wln".equals(lang)) return "wa";
if ("cym".equals(lang)) return "cy";
if ("fry".equals(lang)) return "fy";
if ("wol".equals(lang)) return "wo";
if ("xho".equals(lang)) return "xh";
if ("yid".equals(lang)) return "yi";
if ("yor".equals(lang)) return "yo";
if ("zha".equals(lang)) return "za";
if ("zul".equals(lang)) return "zu";
if ("pap".equals(lang)) return "pap";
if ("gil".equals(lang)) return "gil";
if ("002".equals(lang)) return null;
if ("cnr".equals(lang)) return "cnr";
if ("niu".equals(lang)) return "niu";
if ("tpi".equals(lang)) return "tpi";
if ("pau".equals(lang)) return "pau";
if ("crs".equals(lang)) return null;
if ("tkl".equals(lang)) return "tkl";
if ("tet".equals(lang)) return "tet";
if ("tvl".equals(lang)) return "tvl";
if ("nso".equals(lang)) return "nso";
throw new Error("unknown 3 letter lang code "+lang);
}
private Document load() throws ParserConfigurationException, FileNotFoundException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
DocumentBuilder builder = factory.newDocumentBuilder();
return builder.parse(new FileInputStream(source));
}
}

View File

@ -0,0 +1,210 @@
package org.hl7.fhir.convertors.misc;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.hl7.fhir.dstu3.formats.IParser.OutputStyle;
import org.hl7.fhir.dstu3.formats.XmlParser;
import org.hl7.fhir.dstu3.model.CodeSystem;
import org.hl7.fhir.dstu3.model.CodeSystem.CodeSystemHierarchyMeaning;
import org.hl7.fhir.dstu3.model.CodeSystem.ConceptDefinitionComponent;
import org.hl7.fhir.dstu3.model.Coding;
import org.hl7.fhir.dstu3.model.DateTimeType;
import org.hl7.fhir.dstu3.model.Enumerations.PublicationStatus;
import org.hl7.fhir.dstu3.model.Identifier;
import org.hl7.fhir.dstu3.model.ValueSet;
import org.hl7.fhir.dstu3.terminologies.CodeSystemUtilities;
import org.hl7.fhir.exceptions.FHIRFormatError;
import org.hl7.fhir.utilities.xml.XMLUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* This is defined as a prototype ClaML importer
*
* @author Grahame
*
*/
public class ICPC2Importer {
public static void main(String[] args) {
try {
ICPC2Importer r = new ICPC2Importer();
r.setSourceFileName("c:\\temp\\ICPC-2e-v5.0.xml");
r.setTargetFileNameCS("C:\\temp\\icpc2.xml");
r.setTargetFileNameVS("C:\\temp\\icpc2-vs.xml");
r.go();
System.out.println("Completed OK");
} catch (Exception e) {
e.printStackTrace();
}
}
private String sourceFileName; // the ICPC2 ClaML file
private String targetFileNameVS; // the value set to produce
private String targetFileNameCS; // the value set to produce
public ICPC2Importer() {
super();
}
public ICPC2Importer(String sourceFileName, String targetFileNameCS, String targetFileNameVS) {
super();
this.sourceFileName = sourceFileName;
this.targetFileNameCS = targetFileNameCS;
this.targetFileNameVS = targetFileNameVS;
}
public String getSourceFileName() {
return sourceFileName;
}
public void setSourceFileName(String sourceFileName) {
this.sourceFileName = sourceFileName;
}
public String getTargetFileNameCS() {
return targetFileNameCS;
}
public void setTargetFileNameCS(String targetFileName) {
this.targetFileNameCS = targetFileName;
}
public String getTargetFileNameVS() {
return targetFileNameVS;
}
public void setTargetFileNameVS(String targetFileName) {
this.targetFileNameVS = targetFileName;
}
public void go() throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new FileInputStream(sourceFileName));
ValueSet vs = new ValueSet();
vs.setUrl("http://hl7.org/fhir/sid/icpc2/vs");
Element title = XMLUtil.getNamedChild(doc.getDocumentElement(), "Title");
vs.setVersion(title.getAttribute("version"));
vs.setName(title.getAttribute("name"));
vs.setImmutable(true);
Element identifier = XMLUtil.getNamedChild(doc.getDocumentElement(), "Identifier");
vs.setPublisher(identifier.getAttribute("authority"));
vs.addIdentifier(new Identifier().setValue(identifier.getAttribute("uid")));
List<Element> authors = new ArrayList<Element>();
XMLUtil.getNamedChildren(XMLUtil.getNamedChild(doc.getDocumentElement(), "Authors"), "Author", authors);
for (Element a : authors)
if (!a.getAttribute("name").contains("+"))
vs.addContact().setName(a.getTextContent());
vs.setCopyright("The copyright of ICPC, both in hard copy and in electronic form, is owned by Wonca. See http://www.kith.no/templates/kith_WebPage____1110.aspx");
vs.setStatus(PublicationStatus.ACTIVE);
vs.setDateElement(new DateTimeType(title.getAttribute("date")));
vs.getCompose().addInclude().setSystem("http://hl7.org/fhir/sid/icpc2");
CodeSystem cs = new CodeSystem();
cs.setUrl("http://hl7.org/fhir/sid/icpc2");
cs.setVersion(title.getAttribute("version"));
cs.setName(title.getAttribute("name"));
identifier = XMLUtil.getNamedChild(doc.getDocumentElement(), "Identifier");
cs.setPublisher(identifier.getAttribute("authority"));
cs.setIdentifier(new Identifier().setValue(identifier.getAttribute("uid")));
cs.setHierarchyMeaning(CodeSystemHierarchyMeaning.CLASSIFIEDWITH);
authors = new ArrayList<Element>();
XMLUtil.getNamedChildren(XMLUtil.getNamedChild(doc.getDocumentElement(), "Authors"), "Author", authors);
for (Element a : authors)
if (!a.getAttribute("name").contains("+"))
cs.addContact().setName(a.getTextContent());
cs.setCopyright("The copyright of ICPC, both in hard copy and in electronic form, is owned by Wonca. See http://www.kith.no/templates/kith_WebPage____1110.aspx");
cs.setStatus(PublicationStatus.ACTIVE);
cs.setDateElement(new DateTimeType(title.getAttribute("date")));
cs.setValueSet(vs.getUrl());
Map<String, ConceptDefinitionComponent> concepts = new HashMap<String, ConceptDefinitionComponent>();
List<Element> classes = new ArrayList<Element>();
XMLUtil.getNamedChildren(doc.getDocumentElement(), "Class", classes);
for (Element cls : classes) {
processClass(cls, concepts, cs);
}
XmlParser xml = new XmlParser();
xml.setOutputStyle(OutputStyle.PRETTY);
xml.compose(new FileOutputStream(targetFileNameVS), vs);
xml.compose(new FileOutputStream(targetFileNameCS), cs);
}
private void processClass(Element cls, Map<String, ConceptDefinitionComponent> concepts, CodeSystem define) throws FHIRFormatError {
ConceptDefinitionComponent concept = new ConceptDefinitionComponent();
concept.setCode(cls.getAttribute("code"));
concept.setDefinition(getRubric(cls, "preferred"));
String s = getRubric(cls, "shortTitle");
if (s != null && !s.equals(concept.getDefinition()))
concept.addDesignation().setUse(new Coding().setSystem("http://hl7.org/fhir/sid/icpc2/rubrics").setCode("shortTitle")).setValue(s);
s = getRubric(cls, "inclusion");
if (s != null)
concept.addDesignation().setUse(new Coding().setSystem("http://hl7.org/fhir/sid/icpc2/rubrics").setCode("inclusion")).setValue(s);
s = getRubric(cls, "exclusion");
if (s != null)
concept.addDesignation().setUse(new Coding().setSystem("http://hl7.org/fhir/sid/icpc2/rubrics").setCode("exclusion")).setValue(s);
s = getRubric(cls, "criteria");
if (s != null)
concept.addDesignation().setUse(new Coding().setSystem("http://hl7.org/fhir/sid/icpc2/rubrics").setCode("criteria")).setValue(s);
s = getRubric(cls, "consider");
if (s != null)
concept.addDesignation().setUse(new Coding().setSystem("http://hl7.org/fhir/sid/icpc2/rubrics").setCode("consider")).setValue(s);
s = getRubric(cls, "note");
if (s != null)
concept.addDesignation().setUse(new Coding().setSystem("http://hl7.org/fhir/sid/icpc2/rubrics").setCode("note")).setValue(s);
concepts.put(concept.getCode(), concept);
List<Element> children = new ArrayList<Element>();
XMLUtil.getNamedChildren(cls, "SubClass", children);
if (children.size() > 0)
CodeSystemUtilities.setNotSelectable(define, concept);
Element parent = XMLUtil.getNamedChild(cls, "SuperClass");
if (parent == null) {
define.addConcept(concept);
} else {
ConceptDefinitionComponent p = concepts.get(parent.getAttribute("code"));
p.getConcept().add(concept);
}
}
private String getRubric(Element cls, String kind) {
List<Element> rubrics = new ArrayList<Element>();
XMLUtil.getNamedChildren(cls, "Rubric", rubrics);
for (Element r : rubrics) {
if (r.getAttribute("kind").equals(kind))
return XMLUtil.getNamedChild(r, "Label").getTextContent();
}
return null;
}
}

View File

@ -0,0 +1,220 @@
package org.hl7.fhir.convertors.misc;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.fhir.ucum.UcumEssenceService;
import org.fhir.ucum.UcumService;
import org.hl7.fhir.dstu3.formats.IParser.OutputStyle;
import org.hl7.fhir.dstu3.formats.XmlParser;
import org.hl7.fhir.dstu3.model.CodeSystem;
import org.hl7.fhir.dstu3.model.CodeSystem.CodeSystemContentMode;
import org.hl7.fhir.dstu3.model.CodeSystem.ConceptDefinitionComponent;
import org.hl7.fhir.dstu3.model.CodeSystem.PropertyType;
import org.hl7.fhir.dstu3.model.CodeType;
import org.hl7.fhir.dstu3.model.Coding;
import org.hl7.fhir.dstu3.model.ConceptMap;
import org.hl7.fhir.dstu3.model.ConceptMap.ConceptMapGroupComponent;
import org.hl7.fhir.dstu3.model.ConceptMap.SourceElementComponent;
import org.hl7.fhir.dstu3.model.ConceptMap.TargetElementComponent;
import org.hl7.fhir.dstu3.model.ContactDetail;
import org.hl7.fhir.dstu3.model.ContactPoint;
import org.hl7.fhir.dstu3.model.ContactPoint.ContactPointSystem;
import org.hl7.fhir.dstu3.model.DateTimeType;
import org.hl7.fhir.dstu3.model.Enumerations.ConceptMapEquivalence;
import org.hl7.fhir.dstu3.model.Enumerations.PublicationStatus;
import org.hl7.fhir.dstu3.model.Identifier;
import org.hl7.fhir.dstu3.model.StringType;
import org.hl7.fhir.dstu3.model.UriType;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.utilities.CSVReader;
import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
import org.hl7.fhir.utilities.Utilities;
public class IEEE11073Convertor {
public static final String UCUM_PATH = "c:\\work\\org.hl7.fhir\\build\\implementations\\java\\org.hl7.fhir.convertors\\samples\\ucum-essence.xml";
private static final String MDC_ALL_VALUES = "http://????";
/**
* argument 1: path to the rosetta csv file
* argument 2: basePath to produce files to
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
UcumService ucum = new UcumEssenceService(UCUM_PATH);
CodeSystem mdc = generateMDC(args[0], args[1], ucum);
ConceptMap loinc = generateLoincMdcMap(mdc, args[1], args[2]);
}
private static ConceptMap generateLoincMdcMap(CodeSystem mdc, String dst, String src) throws IOException, FHIRException {
ConceptMap cm = new ConceptMap();
cm.setId("loinc-mdc");
cm.setUrl("http:/???/fhir/ConceptMap/loinc-mdc");
cm.setVersion("[todo]");
cm.setName("LoincMdcCrossMap");
cm.setTitle("Cross Map between LOINC and MDC");
cm.setStatus(PublicationStatus.DRAFT);
cm.setExperimental(true);
cm.setDateElement(new DateTimeType());
cm.setPublisher("HL7, Inc");
ContactDetail cd = cm.addContact();
cd.setName("LOINC + IEEE");
ContactPoint cp = cd.addTelecom();
cp.setSystem(ContactPointSystem.URL);
cp.setValue("http://loinc.org");
cm.setDescription("A Cross Map between the LOINC and MDC Code systems");
cm.setPurpose("To implementers map between medical device codes and LOINC codes");
cm.setCopyright("This content LOINC \u00ae is copyright \u00a9 1995 Regenstrief Institute, Inc. and the LOINC Committee, and available at no cost under the license at http://loinc.org/terms-of-use");
cm.setSource(new UriType("http://loinc.org/vs"));
cm.setTarget(new UriType(MDC_ALL_VALUES));
ConceptMapGroupComponent g = cm.addGroup();
g.setSource("urn:iso:std:iso:11073:10101");
g.setTarget("http://loinc.org");
CSVReader csv = new CSVReader(new FileInputStream(src));
csv.readHeaders();
while (csv.line()) {
SourceElementComponent e = g.addElement();
e.setCode(csv.cell("IEEE_CF_CODE10"));
e.setDisplay(csv.cell("IEEE_DESCRIPTION"));
TargetElementComponent t = e.addTarget();
t.setEquivalence(ConceptMapEquivalence.EQUIVALENT);
t.setCode(csv.cell("LOINC_NUM"));
t.setDisplay(csv.cell("LOINC_LONG_COMMON_NAME"));
}
new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(Utilities.path(dst, "conceptmap-"+cm.getId()+".xml")), cm);
System.out.println("Done");
return cm;
}
public static CodeSystem generateMDC(String src, String dst, UcumService ucum) throws UnsupportedEncodingException, FileNotFoundException, IOException, FHIRException {
CSVReader csv = new CSVReader(new FileInputStream(src));
csv.readHeaders();
CodeSystem cs = new CodeSystem();
Map<String, String> ucumIssues = new HashMap<String, String>();
int errorCount = 0;
cs.setId("MDC");
cs.setUrl("urn:iso:std:iso:11073:10101");
cs.setVersion("[todo]");
cs.setName("11073:10101 codes for the FHIR community");
cs.setStatus(PublicationStatus.ACTIVE);
cs.setExperimental(false);
cs.setDateElement(new DateTimeType());
cs.setPublisher("HL7 (FHIR Project)");
ContactDetail cd = cs.addContact();
ContactPoint cp = cd.addTelecom();
cp.setSystem(ContactPointSystem.URL);
cp.setValue("http://ieee?");
cs.setDescription("1073 Codes for the FHIR community (generated from the Rosetta data");
Identifier i = new Identifier();
cs.setIdentifier(i);
i.setSystem("urn:ietf:rfc:3986");
i.setValue("urn:oid:2.16.840.1.113883.6.24");
cs.setCaseSensitive(false);
cs.setContent(CodeSystemContentMode.COMPLETE);
cs.addProperty().setCode("ucum").setDescription("UCUM units associated with Concept").setType(PropertyType.STRING);
cs.addProperty().setCode("unit").setDescription("MDC units associated with Concept").setType(PropertyType.STRING);
cs.addProperty().setCode("refid").setDescription("MDC Reference Id for Concept").setType(PropertyType.CODE);
Set<String> codes = new HashSet<String>();
while (csv.line()) {
if (csv.has("CF_CODE10")) {
String code = csv.cell("CF_CODE10");
if (codes.contains(code))
System.out.println("Duplicate Code "+code);
else {
codes.add(code);
ConceptDefinitionComponent c = cs.addConcept();
c.setCode(code);
c.setDisplay(csv.cell("Common Term"));
c.setDefinition(csv.cell("Term Description"));
String vd = csv.cell("Vendor_Description");
if (!c.hasDefinition())
c.setDefinition(vd);
if (!c.hasDisplay())
c.setDisplay(vd);
String refid = csv.cell("REFID");
c.addProperty().setCode("refid").setValue(new CodeType().setValue(refid));
if (csv.has("Synonym"))
c.addDesignation().setValue(csv.cell("Synonym")).setUse(new Coding().setSystem("http://hl7.org/fhir/designation-use").setCode("synonym"));
if (csv.has("Acronym"))
c.addDesignation().setValue(csv.cell("Acronym")).setUse(new Coding().setSystem("http://hl7.org/fhir/designation-use").setDisplay("acronym"));
if (csv.has("Systematic Name")) {
String sysName = csv.cell("Systematic Name");
if (!c.hasDefinition())
c.setDefinition(sysName);
c.addDesignation().setValue(sysName).setUse(new Coding().setSystem("http://hl7.org/fhir/designation-use").setCode("structured-name"));
}
if (csv.has("UOM_MDC"))
c.addProperty().setCode("unit").setValue(new StringType().setValue(csv.cell("UOM_MDC")));
if (csv.has("UOM_UCUM")) {
CommaSeparatedStringBuilder ul = new CommaSeparatedStringBuilder();
for (String u : csv.cell("UOM_UCUM").split(" ")) {
String msg = ucum.validate(u);
if (msg != null) {
errorCount++;
ucumIssues.put(u, msg);
} else
ul.append(u);
}
if (ul.length() > 0)
c.addProperty().setCode("ucum").setValue(new StringType().setValue(ul.toString()));
}
}
}
}
csv.close();
new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream(Utilities.path(dst, "codesystem-"+cs.getId()+".xml")), cs);
System.out.println(Integer.toString(errorCount)+"UCUM errors");
for (String u : sorted(ucumIssues.keySet()))
System.out.println("Invalid UCUM code: "+u+" because "+ucumIssues.get(u));
return cs;
}
private static List<String> sorted(Set<String> keySet) {
List<String> names = new ArrayList<>();
names.addAll(keySet);
Collections.sort(names);
return names;
}
}

View File

@ -0,0 +1,346 @@
package org.hl7.fhir.convertors.misc;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.hl7.fhir.dstu3.context.IWorkerContext;
import org.hl7.fhir.dstu3.context.SimpleWorkerContext;
import org.hl7.fhir.dstu3.formats.IParser.OutputStyle;
import org.hl7.fhir.dstu3.formats.XmlParser;
import org.hl7.fhir.dstu3.model.ElementDefinition;
import org.hl7.fhir.dstu3.model.ElementDefinition.PropertyRepresentation;
import org.hl7.fhir.dstu3.model.Enumerations.BindingStrength;
import org.hl7.fhir.dstu3.model.Enumerations.PublicationStatus;
import org.hl7.fhir.dstu3.model.StructureDefinition;
import org.hl7.fhir.dstu3.model.StructureDefinition.StructureDefinitionKind;
import org.hl7.fhir.dstu3.model.StructureDefinition.TypeDerivationRule;
import org.hl7.fhir.dstu3.model.UriType;
import org.hl7.fhir.dstu3.model.ValueSet;
import org.hl7.fhir.dstu3.model.ValueSet.ConceptSetComponent;
import org.hl7.fhir.dstu3.utils.ToolingExtensions;
import org.hl7.fhir.exceptions.FHIRFormatError;
import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.xml.XMLUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
public class ISO21090Importer {
private class Property {
private boolean isattr;
private String name;
private int min;
private int max;
private String type;
private String doco;
private String binding;
}
private class DataType {
private boolean isAbstract;
private String name;
private String doco;
private String parent;
private List<Property> properties = new ArrayList<Property>();
}
public class EnumValueSet {
private String name;
private String template;
private String system;
private List<String> codes = new ArrayList<String>();
private Map<String, String> members = new HashMap<String, String>();
}
public static void main(String[] args) throws Exception {
new ISO21090Importer().process();
}
private IWorkerContext ctxt;
private Element schema;
private Map<String, EnumValueSet> bindings = new HashMap<String, EnumValueSet>();
private Map<String, DataType> types = new HashMap<String, DataType>();
private void process() throws Exception {
ctxt = SimpleWorkerContext.fromPack("C:\\work\\org.hl7.fhir\\build\\publish\\igpack.zip");
load();
processEnums();
processDataTypes();
generate();
System.out.print("done");
}
private void generate() throws Exception {
for (EnumValueSet evs : bindings.values()) {
generateValueSet(evs);
}
for (DataType dt : types.values()) {
generateType(dt);
}
}
private void generateType(DataType dt) throws Exception {
StructureDefinition sd = new StructureDefinition();
sd.setId(dt.name);
sd.setUrl("http://hl7.org/fhir/iso21090/StructureDefinition/"+sd.getId());
sd.setName(dt.name+" data type");
sd.setStatus(PublicationStatus.ACTIVE);
sd.setExperimental(false);
sd.setPublisher("HL7 / ISO");
sd.setDate(new Date());
sd.setDescription(dt.doco);
sd.setKind(StructureDefinitionKind.LOGICAL);
sd.setAbstract(Utilities.existsInList(dt.name, "HXIT", "QTY"));
sd.setType("Element");
if (dt.parent == null)
sd.setBaseDefinition("http://hl7.org/fhir/StructureDefinition/Element");
else
sd.setBaseDefinition("http://hl7.org/fhir/iso21090/StructureDefinition/"+dt.parent);
sd.setDerivation(TypeDerivationRule.SPECIALIZATION);
ElementDefinition ed = sd.getDifferential().addElement();
ed.setPath(dt.name);
produceProperties(sd.getDifferential().getElement(), dt.name, dt.properties, true, false);
produceProperties(sd.getDifferential().getElement(), dt.name, dt.properties, false, false);
ed = sd.getSnapshot().addElement();
ed.setPath(dt.name);
if (dt.parent != null)
addParentProperties(sd.getSnapshot().getElement(), dt.name, dt.parent, true, true);
produceProperties(sd.getSnapshot().getElement(), dt.name, dt.properties, true, true);
if (dt.parent != null)
addParentProperties(sd.getSnapshot().getElement(), dt.name, dt.parent, false, true);
produceProperties(sd.getSnapshot().getElement(), dt.name, dt.properties, false, true);
ed.getBase().setPath(ed.getPath()).setMin(ed.getMin()).setMax(ed.getMax());
new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream("c:\\temp\\iso21090\\StructureDefinition-"+dt.name+".xml"), sd);
}
private void addParentProperties(List<ElementDefinition> elements, String name, String parent, boolean attrMode, boolean snapshot) throws FHIRFormatError {
DataType dt = types.get(parent);
if (dt == null)
throw new Error("No find "+parent);
if (dt.parent != null)
addParentProperties(elements, name, dt.parent, attrMode, snapshot);
produceProperties(elements, name, dt.properties, attrMode, snapshot);
}
private void produceProperties(List<ElementDefinition> elements, String name, List<Property> properties, boolean attrMode, boolean snapshot) throws FHIRFormatError {
for (Property p : properties) {
if (p.isattr == attrMode) {
ElementDefinition ed = new ElementDefinition();
elements.add(ed);
ed.setPath(name+"."+p.name);
if (p.type.startsWith("xsd:"))
ToolingExtensions.addStringExtension(ed.addType(), ToolingExtensions.EXT_XML_TYPE, p.type);
else
ed.addType().setCode(p.type);
ed.setMin(p.min);
ed.setMax(p.max == Integer.MAX_VALUE ? "*" : Integer.toString(p.max));
ed.setDefinition(p.doco);
if (p.isattr)
ed.addRepresentation(PropertyRepresentation.XMLATTR);
if (p.binding != null)
ed.getBinding().setStrength(BindingStrength.REQUIRED).setValueSet(new UriType("http://hl7.org/fhir/iso21090/ValueSet/"+p.binding));
if (snapshot)
ed.getBase().setPath(ed.getPath()).setMin(ed.getMin()).setMax(ed.getMax());
}
}
}
private void generateValueSet(EnumValueSet evs) throws Exception {
ValueSet bvs = ctxt.fetchResource(ValueSet.class, evs.template);
if (bvs == null)
throw new Exception("Did not find template value set "+evs.template);
ValueSet vs = bvs.copy();
vs.getCompose().getInclude().clear();
vs.getIdentifier().clear();
vs.setName("ISO 20190 "+evs.name+" Enumeration");
vs.setId(evs.name);
vs.setUrl("http://hl7.org/fhir/iso21090/ValueSet/"+vs.getId());
vs.setDate(new Date());
vs.setExperimental(false);
ConceptSetComponent inc = vs.getCompose().addInclude().setSystem(evs.system);
for (String code : evs.codes) {
inc.addConcept().setCode(code);
}
new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream("c:\\temp\\iso21090\\ValueSet-"+evs.name+".xml"), vs);
}
private void processDataTypes() {
Element type = XMLUtil.getFirstChild(schema);
while (type != null) {
if (type.getTagName().equals("xsd:complexType")) {
String n = type.getAttribute("name");
if (!(n.contains(".") || n.contains("_") || n.equals("XReference")))
processDataType(n, type);
}
type = XMLUtil.getNextSibling(type);
}
}
private void processDataType(String n, Element type) {
DataType dt = new DataType();
types.put(n, dt);
dt.name = n;
dt.doco = getDoco(type);
Element cnt;
Element ext = XMLUtil.getNamedChild(XMLUtil.getNamedChild(type, "xsd:complexContent"), "xsd:extension");
if (ext != null) {
dt.parent = ext.getAttribute("base");
cnt = XMLUtil.getFirstChild(ext);
} else {
cnt = XMLUtil.getFirstChild(type);
}
if (cnt.getTagName().equals("xsd:annotation"))
cnt = XMLUtil.getNextSibling(cnt);
System.out.println(n+" ("+dt.parent+")");
while (cnt != null) {
if (cnt.getTagName().equals("xsd:attribute")) {
processAttribute(dt, cnt);
} else if (cnt.getTagName().equals("xsd:sequence")) {
Element e = XMLUtil.getFirstChild(cnt);
while (e != null) {
if (e.getTagName().equals("xsd:element")) {
processElement(dt, e);
} else
System.out.println("2. ignore "+e.getTagName());
e = XMLUtil.getNextSibling(e);
}
} else
System.out.println("ignore "+cnt.getTagName());
cnt = XMLUtil.getNextSibling(cnt);
}
}
private void processElement(DataType dt, Element elem) {
Property prop = new Property();
prop.name = elem.getAttribute("name");
prop.min = Integer.parseInt(elem.getAttribute("minOccurs"));
prop.max = "unbounded".equals(elem.getAttribute("maxOccurs")) ? Integer.MAX_VALUE : Integer.parseInt(elem.getAttribute("maxOccurs"));
prop.type = elem.getAttribute("type");
prop.doco = getDoco(elem);
dt.properties.add(prop);
System.out.println(" "+prop.name+" : "+prop.type+" ["+Integer.toString(prop.min)+".."+Integer.toString(prop.max)+"]");
}
private void processAttribute(DataType dt, Element attr) {
Property prop = new Property();
prop.name = attr.getAttribute("name");
prop.type = attr.getAttribute("type");
if (!prop.type.startsWith("xsd:")) {
if (Utilities.noString(prop.type))
prop.type = "xsd:string";
else if (bindings.containsKey(prop.type)) {
prop.binding = prop.type;
prop.type = "xsd:string";
} else if (prop.type.startsWith("set_") && bindings.containsKey(prop.type.substring(4))) {
prop.binding = prop.type.substring(4);
prop.type = "xsd:string";
prop.max = Integer.MAX_VALUE;
} else if ("Uid".equals(prop.type))
prop.type = "xsd:string";
else if ("Code".equals(prop.type))
prop.type = "xsd:token";
else if ("Decimal".equals(prop.type))
prop.type = "xsd:decimal";
else
throw new Error("Unknown type "+prop.type+" on "+dt.name+"."+prop.name);
}
prop.min = "optional".equals(attr.getAttribute("use")) ? 0 : 1;
prop.max = 1;
prop.doco = getDoco(attr);
prop.isattr = true;
dt.properties.add(prop);
System.out.println(" "+prop.name+" : "+prop.type+" ["+Integer.toString(prop.min)+".."+Integer.toString(prop.max)+"]");
}
private void processEnums() {
Element type = XMLUtil.getFirstChild(schema);
while (type != null) {
if (type.getTagName().equals("xsd:simpleType")) {
Element res = XMLUtil.getFirstChild(type);
Element en = XMLUtil.getFirstChild(res);
if (en != null && en.getTagName().equals("xsd:enumeration") && !type.getAttribute("name").contains("."))
processEnum(type.getAttribute("name"), en);
}
type = XMLUtil.getNextSibling(type);
}
}
private void processEnum(String n, Element en) {
EnumValueSet vs = new EnumValueSet();
bindings.put(n, vs);
vs.name = n;
String v3n;
if (n.contains("EntityName"))
v3n = n+"R2";
else if (n.equals("Compression"))
v3n = "CompressionAlgorithm";
else if (n.equals("UpdateMode"))
v3n = "HL7UpdateMode";
else if (n.equals("UncertaintyType"))
v3n = "ProbabilityDistributionType";
else if (n.equals("TelecommunicationAddressUse") || n.equals("PostalAddressUse"))
v3n = "AddressUse";
else if (n.equals("TelecommunicationCapability"))
v3n = "TelecommunicationCapabilities";
else
v3n = n;
vs.system = "http://hl7.org/fhir/v3-"+v3n;
vs.template = "http://hl7.org/fhir/ValueSet/v3-"+v3n;
System.out.println("Enum: "+n+" == "+vs.system);
while (en != null) {
vs.codes.add(en.getAttribute("value"));
vs.members.put(en.getAttribute("value"), getDoco(en));
en = XMLUtil.getNextSibling(en);
}
}
private String getDoco(Element en) {
Element doco = XMLUtil.getNamedChild(XMLUtil.getNamedChild(en, "xsd:annotation"), "xsd:documentation");
return doco == null ? null : doco.getTextContent();
}
private void load() throws ParserConfigurationException, FileNotFoundException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(new FileInputStream("C:\\work\\projects\\org.hl7.v3.dt\\iso\\iso-21090-datatypes.xsd"));
schema = doc.getDocumentElement();
}
}

View File

@ -0,0 +1,105 @@
package org.hl7.fhir.convertors.misc;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.hl7.fhir.dstu3.formats.IParser.OutputStyle;
import org.hl7.fhir.dstu3.formats.XmlParser;
import org.hl7.fhir.dstu3.model.CodeSystem;
import org.hl7.fhir.dstu3.model.CodeSystem.CodeSystemContentMode;
import org.hl7.fhir.dstu3.model.CodeSystem.CodeSystemHierarchyMeaning;
import org.hl7.fhir.dstu3.model.CodeSystem.ConceptDefinitionComponent;
import org.hl7.fhir.dstu3.model.DateTimeType;
import org.hl7.fhir.dstu3.model.Enumerations.PublicationStatus;
import org.hl7.fhir.dstu3.terminologies.CodeSystemUtilities;
import org.hl7.fhir.dstu3.utils.ToolingExtensions;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.exceptions.FHIRFormatError;
import org.hl7.fhir.utilities.CSVReader;
import org.hl7.fhir.utilities.Utilities;
public class NUCCConvertor {
private String[] last = new String[2];
private ConceptDefinitionComponent[] concepts = new ConceptDefinitionComponent[2];
public static void main(String[] args) throws Exception {
new NUCCConvertor().execute();
}
public void execute() throws IOException, FHIRException {
CSVReader csv = new CSVReader(new FileInputStream("c:\\temp\\nucc.csv"));
CodeSystem cs = new CodeSystem();
cs.setId("nucc-provider-taxonomy");
cs.setUrl("http://nucc.org/provider-taxonomy");
cs.setName("NUCC Provider Taxonomy");
cs.setDateElement(new DateTimeType());
cs.setDescription("The Health Care Provider Taxonomy code is a unique alphanumeric code, ten characters in length. The code set is structured into three distinct 'Levels' including Provider Type, Classification, and Area of Specialization");
cs.setCopyright("See NUCC copyright statement");
cs.setStatus(PublicationStatus.ACTIVE);
cs.setContent(CodeSystemContentMode.COMPLETE);
cs.setExperimental(false);
cs.setValueSet("http://hl7.org/fhir/ValueSet/nucc-provider-taxonomy");
cs.setHierarchyMeaning(CodeSystemHierarchyMeaning.CLASSIFIEDWITH);
csv.parseLine();
while (csv.ready())
{
String[] values = csv.parseLine();
processLine(cs, values);
}
csv.close();
new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream("c:\\temp\\nucc.xml"), cs);
}
private void processLine(CodeSystem cs, String[] values) throws FHIRFormatError {
if (!values[1].equals(last[0])) {
last[1] = "";
last[0] = values[1];
concepts[0] = new ConceptDefinitionComponent();
cs.getConcept().add(concepts[0]);
concepts[0].setDisplay(values[1]);
concepts[0].setCode("base-"+Integer.toString(cs.getConcept().size()));
CodeSystemUtilities.setNotSelectable(cs, concepts[0]);
}
if (!values[2].equals(last[1])) {
last[1] = values[2];
concepts[1] = new ConceptDefinitionComponent();
concepts[0].getConcept().add(concepts[1]);
concepts[1].setCode(values[0]);
concepts[1].setDisplay(values[2]);
concepts[1].setDefinition(values[4]);
if (values.length > 5 && !Utilities.noString(values[5]))
ToolingExtensions.addCSComment(concepts[1], values[5]);
} else if (!Utilities.noString(values[3])) {
ConceptDefinitionComponent cc = new ConceptDefinitionComponent();
concepts[1].getConcept().add(cc);
cc.setCode(values[0]);
cc.setDisplay(values[3]);
cc.setDefinition(values[4]);
if (values.length > 5 && !Utilities.noString(values[5]))
ToolingExtensions.addCSComment(cc, values[5]);
}
}
}

View File

@ -0,0 +1,217 @@
package org.hl7.fhir.convertors.misc;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.UUID;
import org.hl7.fhir.dstu3.formats.IParser.OutputStyle;
import org.hl7.fhir.dstu3.formats.XmlParser;
import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.dstu3.model.Bundle.BundleType;
import org.hl7.fhir.dstu3.model.DateTimeType;
import org.hl7.fhir.dstu3.model.Observation;
import org.hl7.fhir.dstu3.model.Observation.ObservationComponentComponent;
import org.hl7.fhir.dstu3.model.Observation.ObservationStatus;
import org.hl7.fhir.dstu3.model.Quantity;
import org.hl7.fhir.dstu3.model.Reference;
import org.hl7.fhir.dstu3.model.Type;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.exceptions.FHIRFormatError;
public class ObservationStatsBuilder {
public static void main(String[] args) throws FileNotFoundException, IOException, FHIRException {
buildVitalSignsSet();
buildStatsSeries();
}
private static void buildVitalSignsSet() throws FileNotFoundException, IOException, FHIRFormatError {
Calendar base = Calendar.getInstance();
base.add(Calendar.DAY_OF_MONTH, -1);
Bundle b = new Bundle();
b.setType(BundleType.COLLECTION);
b.setId(UUID.randomUUID().toString().toLowerCase());
vitals(b, base, 0, 80, 120, 95, 37.1);
vitals(b, base, 35, 85, 140, 98, 36.9);
vitals(b, base, 53, 75, 110, 96, 36.2);
vitals(b, base, 59, 65, 100, 94, 35.5);
vitals(b, base, 104, 60, 90, 90, 35.9);
vitals(b, base, 109, 65, 100, 92, 36.5);
vitals(b, base, 114, 70, 130, 94, 37.5);
vitals(b, base, 120, 90, 150, 97, 37.3);
vitals(b, base, 130, 95, 133, 97, 37.2);
vitals(b, base, 150, 85, 125, 98, 37.1);
new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream("c:\\temp\\vitals.xml"), b);
}
private static void vitals(Bundle b, Calendar base, int minutes, int diastolic, int systolic, int sat, double temp) throws FHIRFormatError {
Calendar when = (Calendar) base.clone();
when.add(Calendar.MINUTE, minutes);
baseVitals(b, when, minutes, "sat", "59408-5", "O2 Saturation").setValue(makeQty(sat, "%", "%"));
baseVitals(b, when, minutes, "temp", "8310-5", "Body temperature").setValue(makeQty(temp, "\u00b0C", "Cel"));
Observation obs = baseVitals(b, when, minutes, "bp", "85354-9", "Blood pressure");
component(obs, "8480-6", "Systolic").setValue(makeQty(systolic, "mmhg", "mm[Hg]"));
component(obs, "8462-4", "Diastolic").setValue(makeQty(diastolic, "mmhg", "mm[Hg]"));
}
private static ObservationComponentComponent component(Observation obs, String lCode, String text) {
ObservationComponentComponent comp = obs.addComponent();
comp.getCode().setText(text).addCoding().setCode(lCode).setSystem("http://loinc.org");
return comp;
}
private static Type makeQty(int sat, String human, String ucum) {
Quantity q = new Quantity();
q.setCode(ucum);
q.setSystem("http://unitsofmeasure.org");
q.setUnit(human);
q.setValue(new BigDecimal(sat));
return q;
}
private static Type makeQty(double val, String human, String ucum) {
Quantity q = new Quantity();
q.setCode(ucum);
q.setSystem("http://unitsofmeasure.org");
q.setUnit(human);
q.setValue(new BigDecimal(val));
return q;
}
private static Observation baseVitals(Bundle b, Calendar when, int min, String name, String lCode, String text) throws FHIRFormatError {
Observation obs = new Observation();
obs.setId("obs-vitals-"+name+"-"+Integer.toString(min));
obs.setSubject(new Reference().setReference("Patient/123"));
obs.setStatus(ObservationStatus.FINAL);
obs.setEffective(new DateTimeType(when));
obs.addCategory().setText("Vital Signs").addCoding().setSystem("http://hl7.org/fhir/observation-category").setCode("vital-signs").setDisplay("Vital Signs");
obs.getCode().setText(text).addCoding().setCode(lCode).setSystem("http://loinc.org");
b.addEntry().setFullUrl("http://hl7.org/fhir/Observation/"+obs.getId()).setResource(obs);
return obs;
}
/**
*
* @throws FHIRException
* @throws IOException
* @throws FileNotFoundException
*/
public static void buildStatsSeries() throws FHIRException, IOException, FileNotFoundException {
Bundle b = new Bundle();
b.setType(BundleType.COLLECTION);
b.setId(UUID.randomUUID().toString().toLowerCase());
addAge(b, 5, 1, "18.3");
addAge(b, 5, 2, "18.4");
addAge(b, 5, 3, "18.6");
addAge(b, 5, 4, "18.8");
addAge(b, 5, 5, "19.0");
addAge(b, 5, 6, "19.1");
addAge(b, 5, 7, "19.3");
addAge(b, 5, 8, "19.5");
addAge(b, 5, 9, "19.6");
addAge(b, 5,10, "19.8");
addAge(b, 5,11, "20.0");
addAge(b, 6, 0, "20.2");
addAge(b, 6, 1, "20.3");
addAge(b, 6, 2, "20.5");
addAge(b, 6, 3, "20.7");
addAge(b, 6, 4, "20.9");
addAge(b, 6, 5, "21.0");
addAge(b, 6, 6, "21.2");
addAge(b, 6, 7, "21.4");
addAge(b, 6, 8, "21.6");
addAge(b, 6, 9, "21.8");
addAge(b, 6,10, "22.0");
addAge(b, 6,11, "22.2");
addAge(b, 7, 0, "22.4");
addAge(b, 7, 1, "22.6");
addAge(b, 7, 2, "22.8");
addAge(b, 7, 3, "23.0");
addAge(b, 7, 4, "23.2");
addAge(b, 7, 5, "23.4");
addAge(b, 7, 6, "23.6");
addAge(b, 7, 7, "23.9");
addAge(b, 7, 8, "24.1");
addAge(b, 7, 9, "24.3");
addAge(b, 7,10, "24.5");
addAge(b, 7,11, "24.8");
addAge(b, 8, 0, "25.0");
addAge(b, 8, 1, "25.3");
addAge(b, 8, 2, "25.5");
addAge(b, 8, 3, "25.8");
addAge(b, 8, 4, "26.0");
addAge(b, 8, 5, "26.3");
addAge(b, 8, 6, "26.6");
addAge(b, 8, 7, "26.8");
addAge(b, 8, 8, "27.1");
addAge(b, 8, 9, "27.4");
addAge(b, 8,10, "27.6");
addAge(b, 8,11, "27.9");
addAge(b, 9, 0, "28.2");
addAge(b, 9, 1, "28.5");
addAge(b, 9, 2, "28.8");
addAge(b, 9, 3, "29.1");
addAge(b, 9, 4, "29.4");
addAge(b, 9, 5, "29.7");
addAge(b, 9, 6, "30.0");
addAge(b, 9, 7, "30.3");
addAge(b, 9, 8, "30.6");
addAge(b, 9, 9, "30.9");
addAge(b, 9, 10, "31.2");
addAge(b, 9, 11, "31.5");
addAge(b, 10, 0, "31.9");
new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream("c:\\temp\\obs.xml"), b);
}
private static void addAge(Bundle b, int y, int m, String v) throws FHIRException {
Observation obs = new Observation();
obs.setId("obs-example-age-weight-"+Integer.toString(y)+"-"+Integer.toString(m));
obs.setSubject(new Reference().setReference("Patient/123"));
obs.setStatus(ObservationStatus.FINAL);
Calendar when = Calendar.getInstance();
when.add(Calendar.YEAR, -y);
when.add(Calendar.MONTH, m);
obs.setEffective(new DateTimeType(when));
obs.getCode().addCoding().setCode("29463-7").setSystem("http://loinc.org");
obs.setValue(new Quantity());
obs.getValueQuantity().setCode("kg");
obs.getValueQuantity().setSystem("http://unitsofmeasure.org");
obs.getValueQuantity().setUnit("kg");
obs.getValueQuantity().setValue(new BigDecimal(v));
b.addEntry().setFullUrl("http://hl7.org/fhir/Observation/"+obs.getId()).setResource(obs);
}
}

View File

@ -0,0 +1,74 @@
package org.hl7.fhir.convertors.misc;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.hl7.fhir.convertors.VersionConvertor_30_40;
import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent;
import org.hl7.fhir.utilities.Utilities;
/*
* load reosurces in xml format, and sve them in package format (json, with correct name
*
* C:\work\fhirserver\resources\resources\dicom
*
*/
public class PackagePreparer {
public static void main(String[] args) {
for (File f : new File("C:\\work\\fhirserver\\resources\\mihin").listFiles()) {
try {
org.hl7.fhir.dstu3.model.Resource r = new org.hl7.fhir.dstu3.formats.JsonParser().parse(new FileInputStream(f));
if (r instanceof Bundle) {
Bundle b = (Bundle) r;
for (BundleEntryComponent be : b.getEntry()) {
try {
org.hl7.fhir.r4.model.Resource r4 = VersionConvertor_30_40.convertResource(be.getResource(), false);
if (r4.getId().startsWith(r4.fhirType()+"-"))
be.getResource().setId(r4.getId().substring(r4.fhirType().length()+1));
if (be.getResource().hasId())
new org.hl7.fhir.r4.formats.JsonParser().compose(new FileOutputStream(Utilities.path("C:\\work\\fhirserver\\resources\\fhir.test.data\\3.5.0\\package", be.getResource().fhirType()+"-"+be.getResource().getId()+".json")), r4);
else
System.out.println(f.getName()+" bundle entry has no id");
} catch (Exception e) {
System.out.println(f.getName()+": "+e.getMessage());
}
}
} else if (r.hasId())
new org.hl7.fhir.r4.formats.JsonParser().compose(new FileOutputStream(Utilities.path(Utilities.getDirectoryForFile(f.getAbsolutePath()), r.fhirType()+"-"+r.getId()+".json")), VersionConvertor_30_40.convertResource(r, false));
else
System.out.println(f.getName()+" has no id");
} catch (Exception e) {
System.out.println(f.getName()+": "+e.getMessage());
e.printStackTrace();
}
}
System.out.println("Completed OK");
}
}

View File

@ -0,0 +1,93 @@
package org.hl7.fhir.convertors.misc;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.fhir.ucum.UcumEssenceService;
import org.hl7.fhir.dstu3.context.SimpleWorkerContext;
import org.hl7.fhir.dstu3.formats.IParser;
import org.hl7.fhir.dstu3.formats.IParser.OutputStyle;
import org.hl7.fhir.dstu3.formats.JsonParser;
import org.hl7.fhir.dstu3.formats.XmlParser;
import org.hl7.fhir.dstu3.model.Bundle;
import org.hl7.fhir.utilities.Utilities;
public class Test {
public final static String DEF_TS_SERVER = "http://fhir-dev.healthintersections.com.au/open";
public final static String DEV_TS_SERVER = "http://local.fhir.org:960/open";
public static final String DEF_PATH = "c:\\work\\org.hl7.fhir\\build\\implementations\\java\\org.hl7.fhir.convertors\\samples\\";
public static final String UCUM_PATH = "c:\\work\\org.hl7.fhir\\build\\implementations\\java\\org.hl7.fhir.convertors\\samples\\ucum-essence.xml";
public static final String SRC_PATH = "c:\\work\\org.hl7.fhir\\build\\publish\\";
public static void main(String[] args) {
try {
CCDAConverter c = new CCDAConverter(new UcumEssenceService(UCUM_PATH), SimpleWorkerContext.fromPack(Utilities.path(SRC_PATH, "validation.zip")));
Bundle a = c.convert(new FileInputStream(DEF_PATH + "ccda.xml"));
String fx = DEF_PATH + "output.xml";
IParser x = new XmlParser().setOutputStyle(OutputStyle.PRETTY);
x.compose(new FileOutputStream(fx), a);
String fj = DEF_PATH + "output.json";
IParser j = new JsonParser().setOutputStyle(OutputStyle.PRETTY);
j.compose(new FileOutputStream(fj), a);
System.out.println("done. save as "+fx+" and "+fj);
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,941 @@
package org.hl7.fhir.convertors.misc;
/*-
* #%L
* org.hl7.fhir.convertors
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hl7.fhir.convertors.R3ToR4Loader;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.r4.conformance.ProfileUtilities;
import org.hl7.fhir.r4.context.SimpleWorkerContext;
import org.hl7.fhir.r4.model.ElementDefinition;
import org.hl7.fhir.r4.model.ElementDefinition.TypeRefComponent;
import org.hl7.fhir.r4.model.Parameters;
import org.hl7.fhir.r4.model.StructureDefinition;
import org.hl7.fhir.r4.model.StructureDefinition.StructureDefinitionKind;
import org.hl7.fhir.r4.model.StructureDefinition.TypeDerivationRule;
import org.hl7.fhir.r4.model.ValueSet;
import org.hl7.fhir.r4.model.ValueSet.ValueSetExpansionContainsComponent;
import org.hl7.fhir.r4.terminologies.ValueSetExpander.ValueSetExpansionOutcome;
import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.Utilities;
import japa.parser.JavaParser;
import japa.parser.ast.CompilationUnit;
import japa.parser.ast.Node;
import japa.parser.ast.body.MethodDeclaration;
import japa.parser.ast.comments.LineComment;
import japa.parser.ast.expr.Expression;
import japa.parser.ast.expr.MethodCallExpr;
import japa.parser.ast.expr.NameExpr;
import japa.parser.ast.expr.VariableDeclarationExpr;
import japa.parser.ast.stmt.ExpressionStmt;
import japa.parser.ast.stmt.ForeachStmt;
import japa.parser.ast.stmt.IfStmt;
import japa.parser.ast.stmt.ReturnStmt;
import japa.parser.ast.stmt.SwitchEntryStmt;
import japa.parser.ast.stmt.SwitchStmt;
import japa.parser.ast.visitor.VoidVisitorAdapter;
public class VersionTransformMapBuilder {
public class ElementTask {
private ElementDefinition element;
private String grpName;
public ElementTask(ElementDefinition element, String grpName) {
this.element = element;
this.grpName = grpName;
}
public ElementDefinition getElement() {
return element;
}
public String getGrpName() {
return grpName;
}
}
public VersionTransformMapBuilder() {
super();
}
public class IterContext {
private String iterVariable;
private String iterExpression;
public IterContext() {
}
public IterContext(String var, String expr) {
this.iterVariable = var;
this.iterExpression = expr;
}
public String patch(String expr) {
if (iterVariable == null)
return expr;
if (expr.equals(iterVariable))
return iterExpression;
if (expr.startsWith(iterVariable+".")) {
String s = iterExpression+expr.substring(iterVariable.length());
if (s.endsWith(".getValue()"))
s = s.substring(0, s.length()-10);
return s;
}
return expr;
}
public boolean scopeIs(String scopeName, String expression) {
if (iterVariable == null)
return scopeName.equals(expression);
else
return scopeName.equals(expression) || iterVariable.equals(expression);
}
public String patch(String scope, String expr) {
if (iterVariable == null)
return expr;
if (scope.equals(iterVariable)) {
String s = iterExpression+"."+expr;
if (s.endsWith(".getValue"))
s = s.substring(0, s.length()-9);
if (s.endsWith("()"))
s = s.substring(0, s.length()-2);
return tail(s);
}
return null;
}
}
public class CodeMap {
private ValueSetExpansionContainsComponent src;
private ValueSetExpansionContainsComponent tgt;
public CodeMap(ValueSetExpansionContainsComponent src, ValueSetExpansionContainsComponent tgt) {
this.src = src;
this.tgt = tgt;
}
}
public class MapContext {
public SimpleWorkerContext sourceContext;
public String sourcePath;
public String sourceType;
public SimpleWorkerContext targetContext;
public String targetType;
public String targetPath;
private boolean forwards;
public MapContext(boolean forwards, SimpleWorkerContext sourceContext, String sourcePath, SimpleWorkerContext targetContext, String targetPath) {
this.forwards = forwards;
this.sourceContext = sourceContext;
this.sourcePath = sourcePath;
this.sourceType = sourcePath;
this.targetContext = targetContext;
this.targetPath = targetPath;
this.targetType = targetPath;
}
public MapContext(boolean forwards, SimpleWorkerContext sourceContext, String sourceType, String sourcePath, SimpleWorkerContext targetContext, String targetType, String targetPath) {
this.forwards = forwards;
this.sourceContext = sourceContext;
this.sourcePath = sourcePath;
this.sourceType = sourceType;
this.targetContext = targetContext;
this.targetPath = targetPath;
this.targetType = targetType;
}
public MapContext(MapContext context, String sourceElement, String targetElement) {
this.forwards = context.forwards;
this.sourceContext = context.sourceContext;
this.sourcePath = context.sourcePath+'.'+sourceElement;
this.sourceType = context.sourceType;
this.targetContext = context.targetContext;
this.targetPath = context.targetPath+'.'+targetElement;
this.targetType = context.targetType;
}
}
private class MapRoutines {
private MethodDeclaration forwards;
private MethodDeclaration backwards;
private String type;
private String oldType;
}
private List<MapRoutines> transforms = new ArrayList<MapRoutines>();
private Map<String, MethodDeclaration> methodsFwds = new HashMap<String, MethodDeclaration>();
private Map<String, MethodDeclaration> methodsBack = new HashMap<String, MethodDeclaration>();
private SimpleWorkerContext contextR3;
private SimpleWorkerContext contextR4;
private String maps;
public static void main(String[] args) throws Exception {
new VersionTransformMapBuilder().execute();
}
private void execute() throws Exception {
System.out.println("loading R3");
R3ToR4Loader ldr = new R3ToR4Loader();
contextR3 = new SimpleWorkerContext();
contextR3.setAllowLoadingDuplicates(true);
contextR3.loadFromFile("C:\\work\\org.hl7.fhir\\build\\source\\release3\\profiles-types.xml", ldr);
contextR3.loadFromFile("C:\\work\\org.hl7.fhir\\build\\source\\release3\\profiles-resources.xml", ldr);
contextR3.loadFromFile("C:\\work\\org.hl7.fhir\\build\\source\\release3\\valuesets.xml", ldr);
contextR3.loadFromFile("C:\\work\\org.hl7.fhir\\build\\source\\release3\\expansions.xml", ldr);
System.out.println("loading R4");
contextR4 = new SimpleWorkerContext();
contextR4.setAllowLoadingDuplicates(true);
contextR4.loadFromFile("C:\\work\\org.hl7.fhir\\build\\publish\\profiles-types.xml", null);
contextR4.loadFromFile("C:\\work\\org.hl7.fhir\\build\\publish\\profiles-resources.xml", null);
contextR4.loadFromFile("C:\\work\\org.hl7.fhir\\build\\publish\\valuesets.xml", null);
contextR4.loadFromFile("C:\\work\\org.hl7.fhir\\build\\publish\\expansions.xml", null);
contextR3.setExpansionProfile(new Parameters());
contextR4.setExpansionProfile(new Parameters());
contextR3.setName("R3");
contextR4.setName("R4");
System.out.println("parsing transform.java");
// creates an input stream for the file to be parsed
FileInputStream in = new FileInputStream("C:\\work\\org.hl7.fhir\\build\\implementations\\java\\org.hl7.fhir.convertors\\src\\org\\hl7\\fhir\\convertors\\VersionConvertor_30_40.java");
CompilationUnit cu;
try {
// parse the file
cu = JavaParser.parse(in);
} finally {
in.close();
}
new MethodVisitor().visit(cu, null);
checkConversions();
System.out.println("Primitive Types");
processSimpleTypes();
System.out.println("Complex Types");
for (StructureDefinition sd : contextR4.allStructures()) {
if (sd.getKind() == StructureDefinitionKind.COMPLEXTYPE && sd.getDerivation() == TypeDerivationRule.SPECIALIZATION) {
processComplexType(sd);
}
}
System.out.println("Resources");
for (StructureDefinition sd : contextR4.allStructures()) {
if (sd.getKind() == StructureDefinitionKind.RESOURCE && sd.getDerivation() == TypeDerivationRule.SPECIALIZATION) {
processComplexType(sd);
}
}
String rt = "StructureDefinition";
System.out.println(rt);
StructureDefinition sd = contextR4.fetchTypeDefinition(rt);
processComplexType(sd);
System.out.println("All Done");
}
private void checkConversions() {
for (MapRoutines mr : transforms) {
if (mr.backwards == null)
System.out.println("no backwards transform for "+mr.oldType+" --> " +mr.type);
if (mr.forwards == null)
System.out.println("no forwards transform for "+mr.oldType+" --> " +mr.type);
}
}
private class MethodVisitor extends VoidVisitorAdapter {
@Override
public void visit(MethodDeclaration meth, Object arg) {
String rt = meth.getType().toString();
if (meth.getParameters().size() != 1)
; // System.out.println(rt+" "+meth.getName());
else {
String pt = meth.getParameters().get(0).getType().toString();
if (pt.startsWith("org.hl7.fhir.dstu3.model.") && rt.startsWith("org.hl7.fhir.r4.model.")) {
registerForwards(meth, pt.substring(25), rt.substring(22));
methodsFwds.put(meth.getName(), meth);
} else if (pt.startsWith("org.hl7.fhir.r4.model.") && rt.startsWith("org.hl7.fhir.dstu3.model.")) {
registerBackwards(meth, pt.substring(22), rt.substring(25));
methodsBack.put(meth.getName(), meth);
} else
; // System.out.println(rt+" "+meth.getName()+"("+pt+")");
}
super.visit(meth, arg);
}
}
private void registerForwards(MethodDeclaration meth, String oldType, String type) {
MapRoutines mr = null;
for (MapRoutines t : transforms) {
if (t.type.equals(type) && t.oldType.equals(oldType))
mr = t;
}
if (mr == null) {
mr = new MapRoutines();
mr.type = type;
mr.oldType = oldType;
transforms.add(mr);
}
if (mr.forwards != null)
throw new Error("Duplicate forward method for "+type+"/"+oldType+": "+meth.getName()+" (found "+mr.forwards.getName()+")");
mr.forwards = meth;
}
public void registerBackwards(MethodDeclaration meth, String type, String oldType) {
MapRoutines mr = null;
for (MapRoutines t : transforms) {
if (t.type.equals(type) && t.oldType.equals(oldType))
mr = t;
}
if (mr == null) {
mr = new MapRoutines();
mr.type = type;
mr.oldType = oldType;
transforms.add(mr);
}
if (mr.backwards != null)
throw new Error("Duplicate backward method for "+type+"/"+oldType+": "+meth.getName()+" (found "+mr.backwards.getName()+")");
mr.backwards = meth;
}
private List<MapRoutines> findRoutinesForType(String type) {
List<MapRoutines> res = new ArrayList<MapRoutines>();
for (MapRoutines t : transforms)
if (t.type.equals(type))
res.add(t);
return res;
}
private void processSimpleTypes() throws IOException {
StringBuilder f = new StringBuilder();
f.append("map \"http://hl7.org/fhir/StructureMap/primitives3to4\" = \"R3 to R4 Primitive Conversions\"\r\n\r\n");
StringBuilder b = new StringBuilder();
b.append("map \"http://hl7.org/fhir/StructureMap/primitives4to3\" = \"R4 to R3 Primitive Conversions\"\r\n\r\n");
List<String> types = new ArrayList<String>();
for (StructureDefinition sd : contextR4.allStructures()) {
if (sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE)
if (!types.contains(sd.getUrl()))
types.add(sd.getUrl());
}
Collections.sort(types);
for (String n : types) {
StructureDefinition sd = contextR4.fetchResource(StructureDefinition.class, n);
b.append("uses \"http://hl7.org/fhir/StructureDefinition/"+sd.getType()+"\" as source\r\n");
b.append("uses \"http://hl7.org/fhir/3.0/StructureDefinition/"+sd.getType()+"\" as target\r\n");
f.append("uses \"http://hl7.org/fhir/3.0/StructureDefinition/"+sd.getType()+"\" as source\r\n");
f.append("uses \"http://hl7.org/fhir/StructureDefinition/"+sd.getType()+"\" as target\r\n");
}
f.append("\r\n");
b.append("\r\n");
f.append("imports \"http://hl7.org/fhir/StructureMap/Element3to4\"\r\n");
b.append("imports \"http://hl7.org/fhir/StructureMap/Element4to3\"\r\n");
f.append("\r\n");
b.append("\r\n");
for (String n : types) {
StructureDefinition sd = contextR4.fetchResource(StructureDefinition.class, n);
f.append("group "+sd.getType()+" extends Element\r\n");
f.append(" input src : "+sd.getType()+"R3 as source\r\n");
f.append(" input tgt : "+sd.getType()+" as target\r\n\r\n");
f.append(" \""+sd.getType()+"-value\" : for src.value as v make tgt.value = v\r\n");
f.append("endgroup\r\n\r\n");
b.append("group "+sd.getType()+" extends Element\r\n");
b.append(" input src : "+sd.getType()+" as source\r\n");
b.append(" input tgt : "+sd.getType()+"R3 as target\r\n\r\n");
b.append(" \""+sd.getType()+"-value\" : for src.value as v make tgt.value = v\r\n");
b.append("endgroup\r\n\r\n");
}
TextFile.stringToFile(f.toString(), "C:\\work\\org.hl7.fhir\\build\\implementations\\r3maps\\R3toR4\\primitives.map");
TextFile.stringToFile(b.toString(), "C:\\work\\org.hl7.fhir\\build\\implementations\\r3maps\\R4toR3\\primitives.map");
}
private void processComplexType(StructureDefinition sd) throws IOException, FHIRException {
boolean doneF = false;
boolean doneR = false;
try {
List<MapRoutines> mrs = findRoutinesForType(sd.getType());
MapRoutines mr = null;
for (MapRoutines t : mrs) {
if (t.oldType != null && t.oldType.equals(sd.getType())) {
if (mr != null)
reportError("multiple transforms for "+sd.getType());
mr = t;
}
}
if (mr != null) {
System.out.println(" ..."+sd.getType());
StringBuilder f = new StringBuilder();
f.append("map \"http://hl7.org/fhir/StructureMap/"+sd.getType()+"3to4\" = \"R3 to R4 Conversions for "+sd.getType()+"\"\r\n\r\n");
StringBuilder b = new StringBuilder();
b.append("map \"http://hl7.org/fhir/StructureMap/"+sd.getType()+"4to3\" = \"R4 to R3 Conversion for "+sd.getType()+"\"\r\n\r\n");
f.append("$maps$\r\n");
b.append("$maps$\r\n");
b.append("uses \"http://hl7.org/fhir/StructureDefinition/"+sd.getType()+"\" alias "+sd.getType()+" as source\r\n");
b.append("uses \"http://hl7.org/fhir/3.0/StructureDefinition/"+sd.getType()+"\" alias "+sd.getType()+"R3 as target\r\n");
f.append("uses \"http://hl7.org/fhir/3.0/StructureDefinition/"+sd.getType()+"\" alias "+sd.getType()+"R3 as source\r\n");
f.append("uses \"http://hl7.org/fhir/StructureDefinition/"+sd.getType()+"\" alias "+sd.getType()+" as target\r\n");
String base = contextR4.fetchResource(StructureDefinition.class, sd.getBaseDefinition()).getType();
f.append("\r\nimports \"http://hl7.org/fhir/StructureMap/*3to4\"\r\n");
f.append("$imports$\r\n\r\n");
b.append("\r\nimports \"http://hl7.org/fhir/StructureMap/*4to3\"\r\n");
b.append("$imports$\r\n\r\n");
f.append("\r\n");
b.append("\r\n");
f.append("group "+sd.getType()+" extends "+base+"\r\n");
f.append(" input src : "+sd.getType()+"R3 as source\r\n");
f.append(" input tgt : "+sd.getType()+" as target\r\n\r\n");
maps = "";
MapContext context = new MapContext(true, contextR3, mr.oldType, contextR4, mr.type);
processMethod(0, "src", "tgt", f, mr.forwards, context);
f.append("endgroup\r\n\r\n");
TextFile.stringToFile(f.toString().replace("$maps$", maps).replace("$imports$", imports(false)), "C:\\work\\org.hl7.fhir\\build\\implementations\\r3maps\\R3toR4\\"+sd.getType()+".map");
doneF = true;
maps = "";
b.append("group "+sd.getType()+" extends "+base+"\r\n");
b.append(" input src : "+sd.getType()+" as source\r\n");
b.append(" input tgt : "+sd.getType()+"R3 as target\r\n\r\n");
context = new MapContext(false, contextR4, mr.type, contextR3, mr.oldType);
processMethod(0, "src", "tgt", b, mr.backwards, context);
b.append("endgroup\r\n\r\n");
TextFile.stringToFile(b.toString().replace("$maps$", maps).replace("$imports$", imports(true)), "C:\\work\\org.hl7.fhir\\build\\implementations\\r3maps\\R4toR3\\"+sd.getType()+".map");
doneR = true;
}
} catch (Throwable e) {
e.printStackTrace();
}
generateNative(sd, !doneR, !doneF);
}
private void generateNative(StructureDefinition sd, boolean doR, boolean doF) throws IOException {
System.out.println(" ... native "+sd.getType());
StringBuilder f = new StringBuilder();
f.append("map \"http://hl7.org/fhir/StructureMap/"+sd.getType()+"2to3\" = \"R3 to R4 Conversions for "+sd.getType()+"\"\r\n\r\n");
StringBuilder b = new StringBuilder();
b.append("map \"http://hl7.org/fhir/StructureMap/"+sd.getType()+"3to2\" = \"R4 to R3 Conversion for "+sd.getType()+"\"\r\n\r\n");
f.append("$maps$\r\n");
b.append("$maps$\r\n");
b.append("uses \"http://hl7.org/fhir/StructureDefinition/"+sd.getType()+"\" alias "+sd.getType()+" as source\r\n");
b.append("uses \"http://hl7.org/fhir/3.0/StructureDefinition/"+sd.getType()+"\" alias "+sd.getType()+"R3 as target\r\n");
f.append("uses \"http://hl7.org/fhir/3.0/StructureDefinition/"+sd.getType()+"\" alias "+sd.getType()+"R3 as source\r\n");
f.append("uses \"http://hl7.org/fhir/StructureDefinition/"+sd.getType()+"\" alias "+sd.getType()+" as target\r\n");
String base = contextR4.fetchResource(StructureDefinition.class, sd.getBaseDefinition()).getType();
f.append("\r\nimports \"http://hl7.org/fhir/StructureMap/*3to4\"\r\n");
f.append("$imports$\r\n\r\n");
b.append("\r\nimports \"http://hl7.org/fhir/StructureMap/*4to3\"\r\n");
b.append("$imports$\r\n\r\n");
MapContext context = new MapContext(true, contextR3, sd.getType(), contextR4, sd.getType());
processElement("src", "tgt", sd.getType(), sd.getBaseDefinition().substring(40), f, b, sd, sd.getSnapshot().getElementFirstRep(), context);
if (doF)
TextFile.stringToFile(f.toString().replace("$maps$", maps).replace("$imports$", imports(false)), "C:\\work\\org.hl7.fhir\\build\\implementations\\r3maps\\R3toR4\\"+sd.getType()+".map");
if (doR)
TextFile.stringToFile(b.toString().replace("$maps$", maps).replace("$imports$", imports(false)), "C:\\work\\org.hl7.fhir\\build\\implementations\\r3maps\\R4toR3\\"+sd.getType()+".map");
}
private void processElement(String src, String tgt, String grpName, String parent, StringBuilder f, StringBuilder b, StructureDefinition sd, ElementDefinition ed, MapContext context) {
f.append("\r\n");
f.append("group "+grpName+" extends "+parent+"\r\n");
f.append(" input src : "+sd.getType()+"R3 as source\r\n");
f.append(" input tgt : "+sd.getType()+" as target\r\n\r\n");
b.append("\r\n");
b.append("group "+grpName+" extends "+parent+"\r\n");
b.append(" input src : "+sd.getType()+"R3 as source\r\n");
b.append(" input tgt : "+sd.getType()+" as target\r\n\r\n");
maps = "";
List<ElementTask> tasks = new ArrayList<ElementTask>();
List<ElementDefinition> children = ProfileUtilities.getChildList(sd, ed);
for (ElementDefinition child : children) {
if (!isInherited(child)) {
String n = tail(child.getPath());
if (!isAbstractType(child)) {
String s = " \""+child.getPath()+"\": for "+src+"."+n+" make "+tgt+"."+n+"\r\n";
b.append(s);
f.append(s);
} else {
grpName = normalise(child.getPath());
String s = " \""+child.getPath()+"\": for "+src+"."+n+" as s make "+tgt+"."+n+" as t then "+grpName+"(s,t)\r\n";
b.append(s);
f.append(s);
tasks.add(new ElementTask(child, grpName));
}
}
}
f.append("endgroup\r\n\r\n");
for (ElementTask task : tasks) {
processElement("src", "tgt", task.getGrpName(), task.getElement().getTypeFirstRep().getCode(), f, b, sd, task.getElement(), context);
}
}
private boolean isInherited(ElementDefinition child) {
return !child.getPath().equals(child.getBase().getPath());
}
private String normalise(String path) {
StringBuilder b = new StringBuilder();
boolean upcase = true;
for (char c : path.toCharArray()) {
if (c == '.')
upcase = true;
else if (upcase) {
upcase = false;
b.append(Character.toUpperCase(c));
} else
b.append(c);
}
return b.toString();
}
private boolean isAbstractType(ElementDefinition child) {
return child.getType().size() == 1 && Utilities.existsInList(child.getType().get(0).getCode(), "Element", "BackboneElement");
}
private CharSequence imports(boolean bck) {
StringBuilder b = new StringBuilder();
return b.toString();
}
private void processMethod(int indent, String src, String tgt, StringBuilder f, MethodDeclaration meth, MapContext context) throws FHIRException {
if (meth.getBody() == null)
reportError("no body on method: "+meth.toString());
else
for (Node n : meth.getBody().getChildrenNodes()) {
processExpression(indent, new IterContext(), src, tgt, f, context, n);
}
}
private void processExpression(int indent, IterContext iter, String src, String tgt, StringBuilder f, MapContext context, Node n) throws FHIRException {
if (n instanceof ExpressionStmt) {
processExpressionStmt(indent, iter, src, tgt, f, (ExpressionStmt) n, context);
} else if (n instanceof IfStmt && ns(n.toString()).equals("if (src == null || src.isEmpty()) return null;")) {
// these we ignore
} else if (n instanceof IfStmt && ns(n.toString()).startsWith("if (src.has")) {
// ignore the .has and process the follow up
IfStmt ifs = (IfStmt) n;
for (Node t : ifs.getThenStmt().getChildrenNodes())
processExpression(indent, iter, src, tgt, f, context, t);
} else if (n instanceof VariableDeclarationExpr) {
VariableDeclarationExpr v = (VariableDeclarationExpr) n;
if (v.getVars().get(0).toString().equals("tgt")) {
// these we ignore
} else
reportError("Unhandled Variable Declaration: "+n.toString());
} else if (n instanceof ReturnStmt) {
// these we ignore
} else if (n instanceof MethodCallExpr) {
processMethodCallExpr(indent, iter, src, tgt, f, context, (MethodCallExpr) n);
} else if (n instanceof ForeachStmt) {
ForeachStmt fe = (ForeachStmt) n;
if (fe.getIterable().toString().startsWith("src.") && fe.getBody().getChildrenNodes().size() == 1) {
String var = fe.getVariable().getVars().get(0).getId().toString();
processExpression(indent, new IterContext(var, fe.getIterable().toString()), src, tgt, f, context, fe.getBody().getChildrenNodes().get(0));
} else
reportError("Unhandled ForeachStmt of type "+n.getClass().getName()+": "+n.toString());
} else if (!(n instanceof LineComment))
reportError("Unhandled Node of type "+n.getClass().getName()+": "+n.toString());
}
private String ns(String s) {
s = s.replace("\r", " ");
s = s.replace("\n", " ");
s = s.replace("\t", " ");
while (s.contains(" "))
s = s.replace(" ", " ");
return s;
}
private void processExpressionStmt(int indent, IterContext iter, String src, String tgt, StringBuilder f, ExpressionStmt n, MapContext context) throws FHIRException {
Expression expr = n.getExpression();
if (expr instanceof VariableDeclarationExpr) {
VariableDeclarationExpr v = (VariableDeclarationExpr) expr;
if (v.getVars().get(0).getId().toString().equals("tgt")) {
// these we ignore
} else
reportError("Unhandled VariableDeclarationExpr: "+n.toString());
} else if (expr instanceof MethodCallExpr) {
MethodCallExpr me = (MethodCallExpr) expr;
processMethodCallExpr(indent, iter, src, tgt, f, context, me);
} else
reportError("Unhandled Expression Node "+expr.getClass().getName()+": "+n.toString());
}
private void processMethodCallExpr(int indent, IterContext iter, String src, String tgt, StringBuilder f, MapContext context, MethodCallExpr me) throws FHIRException {
if (me.getScope() == null && me.getName().startsWith("copy"))
return;
if (me.getScope() == null)
reportError("Unhandled MethodCallExpr (no scope): "+me.toString());
else if ("tgt".equals(me.getScope().toString()))
processAssignment(indent, iter, src, tgt, f, me, context);
else
reportError("Unhandled MethodCallExpr "+me.getScope()+": "+me.toString());
}
private void processAssignment(int indent, IterContext iter, String src, String tgt, StringBuilder b, MethodCallExpr expr, MapContext context) throws FHIRException {
String tv = expr.getName();
if ((tv.startsWith("set") || tv.startsWith("add")) && expr.getArgs().size() == 1) {
Expression p1 = expr.getArgs().get(0);
if (p1 instanceof MethodCallExpr) {
MethodCallExpr pm1 = (MethodCallExpr) p1;
if (pm1.getScope() != null && iter.scopeIs("src", pm1.getScope().toString())) {
String sv = iter.patch(pm1.getScope().toString(), pm1.getName());
if (sv.startsWith("get")) {
String srcType = getSpecifiedType(context.sourceContext, context.sourceType, context.sourcePath +"."+unPropertyise(sv), expr);
String tgtType = getSpecifiedType(context.targetContext, context.targetType, context.targetPath +"."+unPropertyise(tv), expr);
if (srcType.equals(tgtType)) {
b.append(Utilities.padLeft("", ' ', indent*2)+" \""+context.targetPath+"."+unPropertyise(tv)+"\" : for "+src+"."+unPropertyise(sv)+" as vs make "+tgt+"."+unPropertyise(tv)+" as vt\r\n");
} else if (comboIsOk(srcType, tgtType)) {
b.append(Utilities.padLeft("", ' ', indent*2)+" \""+context.targetPath+"."+unPropertyise(tv)+"\" : for "+src+"."+unPropertyise(sv)+" as vs make "+tgt+"."+unPropertyise(tv)+" as vt then "+srcType+"To"+Utilities.capitalize(tgtType)+"(vs, vt)\r\n");
} else
reportError("type mismatch: "+srcType+" != "+tgtType);
return;
}
}
if (pm1.getScope() == null && pm1.getName().startsWith("convert")) {
if (pm1.getName().equals("convertType")) {
String sv = findSrcGet(pm1.getArgs().get(0), iter);
if (sv == null) {
reportError("Unhandled source for assignment: "+expr.toString());
} else {
boolean fr = sv.endsWith("FirstRep");
if (fr) sv = sv.substring(0, sv.length()-8);
List<String> srcTypes = getPossibleTypes(context.sourceContext, context.sourceType, context.sourcePath +"."+unPropertyise(sv), expr);
List<String> tgtTypes = getPossibleTypes(context.targetContext, context.targetType, context.targetPath +"."+unPropertyise(tv), expr);
for (String s : srcTypes) {
if (tgtTypes.contains(s)) {
b.append(Utilities.padLeft("", ' ', indent*2)+" \""+context.targetPath+"."+unPropertyise(tv)+"-"+s+"\" : for "+src+"."+unPropertyise(sv)+" "+(fr ? "first " : "")+" : "+s+" as vs make "+tgt+"."+unPropertyise(tv)+" = create(\""+s+"\") as vt then "+s+"(vs,vt)\r\n");
}
}
}
return;
} else if (isDataType(pm1.getName().substring(7)) && pm1.getArgs().size() == 1) {
String type = pm1.getName().substring(7);
String sv = findSrcGet(pm1.getArgs().get(0), iter);
if (sv != null && sv.startsWith("get")) {
b.append(Utilities.padLeft("", ' ', indent*2)+" \""+context.targetPath+"."+unPropertyise(tv)+"\" : for "+src+"."+unPropertyise(sv)+" as vs make "+tgt+"."+unPropertyise(tv)+" as vt\r\n");
return;
}
reportError("Unhandled Assignment of other type: "+expr.toString());
return;
} else if (pm1.getName().equals("convertSimpleQuantity")) {
String type = "Quantity";
String sv = findSrcGet(pm1.getArgs().get(0), iter);
if (sv != null && sv.startsWith("get")) {
b.append(Utilities.padLeft("", ' ', indent*2)+" \""+context.targetPath+"."+unPropertyise(tv)+"\" : for "+src+"."+unPropertyise(sv)+" as vs make "+tgt+"."+unPropertyise(tv)+" as vt\r\n");
return;
}
reportError("Unhandled Assignment of other type: "+expr.toString());
return;
} else if (pm1.getName().startsWith("convert"+context.targetPath)) {
if (isEnumConversion(pm1.getName(), context)) {
String sv = findSrcGet(pm1.getArgs().get(0), iter);
if (sv != null && sv.startsWith("get")) {
String url = processConceptMap(pm1.getName(), context, unPropertyise(sv), unPropertyise(tv), expr);
if (url == null)
b.append(Utilities.padLeft("", ' ', indent*2)+" \""+context.targetPath+"."+unPropertyise(tv)+"\" : for "+src+"."+unPropertyise(sv)+" as vs make "+tgt+"."+unPropertyise(tv)+" as vt\r\n");
else
b.append(Utilities.padLeft("", ' ', indent*2)+" \""+context.targetPath+"."+unPropertyise(tv)+"\" : for "+src+"."+unPropertyise(sv)+" as v make "+tgt+"."+unPropertyise(tv)+" = translate(v, \""+url+"\", \"code\")\r\n");
return;
}
reportError("Unhandled Assignment of enum : "+expr.toString());
} else {
String type = pm1.getName().substring(7);
String sv = findSrcGet(pm1.getArgs().get(0), iter);
if (sv != null && sv.startsWith("get")) {
String vs = "vs"+Integer.toString(indent);
String vt = "vt"+Integer.toString(indent);
b.append(Utilities.padLeft("", ' ', indent*2)+" \""+context.targetPath+"."+unPropertyise(tv)+"\" : for "+src+"."+unPropertyise(sv)+" as "+vs+" make "+tgt+"."+unPropertyise(tv)+" as "+vt+" then {\r\n"+processAnonymous(indent, vs, vt, pm1.getName(),
makeMapContext(context, unPropertyise(sv), unPropertyise(tv)))+Utilities.padLeft("", ' ', indent*2)+" }\r\n");
return;
}
reportError("Unhandled Assignment of contained type: "+expr.toString());
}
return;
} else {
if (isEnumConversion(pm1.getName(), context)) {
String sv = findSrcGet(pm1.getArgs().get(0), iter);
if (sv != null && sv.startsWith("get")) {
String url = processConceptMap(pm1.getName(), context, unPropertyise(sv), unPropertyise(tv), expr);
if (url == null)
b.append(Utilities.padLeft("", ' ', indent*2)+" \""+context.targetPath+"."+unPropertyise(tv)+"\" : for "+src+"."+unPropertyise(sv)+" as vs make "+tgt+"."+unPropertyise(tv)+" as vt\r\n");
else
b.append(Utilities.padLeft("", ' ', indent*2)+" \""+context.targetPath+"."+unPropertyise(tv)+"\" : for "+src+"."+unPropertyise(sv)+" as v make "+tgt+"."+unPropertyise(tv)+" = translate(v, \""+url+"\", \"code\")\r\n");
return;
}
} else
reportError("Unhandled Assignment of something : "+expr.toString());
return;
}
}
}
}
reportError("Unhandled Assignment: "+expr.toString());
}
private boolean comboIsOk(String srcType, String tgtType) {
if (srcType.equals("markdown") && tgtType.equals("string"))
return true;
if (srcType.equals("string") && tgtType.equals("markdown"))
return true;
return false;
}
private void reportError(String msg) {
System.out.println(msg);
}
private String unPropertyise(String t) {
String s = Utilities.uncapitalize(t.substring(3));
if (s.equals("class_"))
return "class";
return s;
}
private MapContext makeMapContext(MapContext context, String sourceName, String targetName) {
ElementDefinition eds = getDefinition(context.sourceContext, context.sourceType, context.sourcePath+"."+sourceName, false, null);
String stype = getType(eds);
String sp = stype == null ? context.sourcePath+"."+sourceName : stype;
ElementDefinition edt = getDefinition(context.targetContext, context.targetType, context.targetPath+"."+targetName, false, null);
String ttype = getType(edt);
String tp = ttype == null ? context.targetPath+"."+targetName : ttype;
return new MapContext(context.forwards, context.sourceContext, stype == null ? context.sourceType : stype, sp, context.targetContext, ttype == null ? context.targetType : ttype, tp);
}
private String getType(ElementDefinition edt) {
if (edt.getType().size() != 1)
return null;
String t = edt.getType().get(0).getCode();
if (Utilities.existsInList(t, "Element", "BackboneElement"))
return null;
return t;
}
private List<String> getPossibleTypes(SimpleWorkerContext context, String type, String path, Node n) {
ElementDefinition eds = getDefinition(context, type, path, true, n);
List<String> res = new ArrayList<String>();
for (TypeRefComponent tr : eds.getType()) {
if (!res.contains(tr.getCode()))
res.add(tr.getCode());
}
return res;
}
private String getSpecifiedType(SimpleWorkerContext context, String type, String path, Node n) {
ElementDefinition eds = getDefinition(context, type, path, true, n);
List<String> res = new ArrayList<String>();
for (TypeRefComponent tr : eds.getType()) {
if (!res.contains(tr.getCode()))
res.add(tr.getCode());
}
if (res.size() > 1)
throw new Error("Multiple types");
return res.get(0);
}
private String processConceptMap(String name, MapContext context, String srcProp, String tgtProp, Node ne) throws FHIRException {
ElementDefinition eds = getDefinition(context.sourceContext, context.sourceType, context.sourcePath+"."+srcProp, false, ne);
ElementDefinition edt = getDefinition(context.targetContext, context.targetType, context.targetPath+"."+tgtProp, false, ne);
List<CodeMap> translations = new ArrayList<CodeMap>();
ValueSet src = getValueSet(context.sourceContext, eds);
ValueSet tgt = getValueSet(context.targetContext, edt);
boolean exact = true;
MethodDeclaration meth = context.forwards ? methodsFwds.get(name) : methodsBack.get(name);
for (Node n : meth.getBody().getChildrenNodes()) {
if (n instanceof SwitchStmt) {
SwitchStmt ss = (SwitchStmt) n;
for (SwitchEntryStmt cs : ss.getEntries()) {
if (cs.getStmts().size() == 1 && cs.getLabel() != null && cs.getStmts().get(0) instanceof ReturnStmt) {
String lblSrc = cs.getLabel().toString();
String lblTgt = tail(cs.getStmts().get(0).toString());
ValueSetExpansionContainsComponent ccSrc = findLabel(lblSrc, src, context.sourceContext.getName());
ValueSetExpansionContainsComponent ccTgt = findLabel(lblTgt, tgt, context.targetContext.getName());
translations.add(new CodeMap(ccSrc, ccTgt));
if (!ccSrc.getCode().equals(ccTgt.getCode()))
exact = false;
}
}
}
}
if (exact)
return null;
Set<String> mapPairs = new HashSet<String>();
for (CodeMap cm : translations)
mapPairs.add(cm.src.getSystem()+"|"+cm.tgt.getSystem());
StringBuilder b = new StringBuilder();
b.append("conceptmap \""+tgt.getName()+"\" {\r\n");
for (String pair : mapPairs) {
String[] urls = pair.split("\\|");
b.append(" prefix s = \""+urls[0]+"\"\r\n");
b.append(" prefix t = \""+urls[1]+"\"\r\n");
b.append("\r\n");
for (CodeMap cm : translations) {
if (cm.src.getSystem().equals(urls[0]) && cm.tgt.getSystem().equals(urls[1])) {
b.append(" s:"+cm.src.getCode()+" - t:"+cm.tgt.getCode()+"\r\n");
}
}
}
b.append("}\r\n");
maps = maps + b.toString();
return "#"+tgt.getName();
}
private ValueSetExpansionContainsComponent findLabel(String label, ValueSet vs, String cn) {
CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
for (ValueSetExpansionContainsComponent cc : vs.getExpansion().getContains()) {
b.append(cc.getCode());
if (matches(cc.getCode(), label))
return cc;
}
throw new Error("no match for "+label+" in "+b.toString()+" in "+cn);
}
private boolean matches(String code, String label) {
if (code.equalsIgnoreCase(label))
return true;
if (code.replace("-", "").equalsIgnoreCase(label))
return true;
if (code.equals("<") && label.equals("LESS_THAN"))
return true;
if (code.equals("<=") && label.equals("LESS_OR_EQUAL"))
return true;
if (code.equals(">=") && label.equals("GREATER_OR_EQUAL"))
return true;
if (code.equals(">") && label.equals("GREATER_THAN"))
return true;
return false;
}
private String tail(String string) {
if (string.endsWith(";"))
string = string.substring(0, string.length()-1);
return string.substring(string.lastIndexOf(".")+1);
}
private String utail(String string) {
return string.substring(string.lastIndexOf("/")+1);
}
private ValueSet getValueSet(SimpleWorkerContext ctxt, ElementDefinition ed) throws FHIRException {
if (!ed.hasBinding())
throw new Error("Attempt to get value set for element with no binding "+ed.getPath());
ValueSet vs = ctxt.fetchResource(ValueSet.class, ed.getBinding().getValueSet());
if (vs == null)
throw new Error("Unable to get value set for element "+ed.getPath()+" for "+ed.getBinding().getValueSet());
ValueSetExpansionOutcome vse = ctxt.expandVS(vs, true, false);
if (vse.getValueset() == null)
throw new Error("Unable to expand value set for element "+ed.getPath()+", url = "+vs.getUrl()+" in ctxt "+ctxt.getName());
return vse.getValueset();
}
private ElementDefinition getDefinition(SimpleWorkerContext ctxt, String type, String path, boolean canBePolyMorphic, Node n) {
StructureDefinition sd = ctxt.fetchTypeDefinition(type);
if (sd == null)
throw new Error("Unable to find type "+type);
if (sd.getDerivation() == TypeDerivationRule.CONSTRAINT) {
path = utail(sd.getBaseDefinition())+path.substring(type.length());
}
for (ElementDefinition ed : sd.getSnapshot().getElement()) {
if (ed.getPath().equals(path) || (canBePolyMorphic && ed.getPath().equals(path+"[x]")))
return ed;
}
throw new Error("Unable to find path "+path+" in "+sd.getType()+" in context "+ctxt.getName()+", called from "+n.toString());
}
private String processAnonymous(int indent, String src, String tgt, String name, MapContext context) throws FHIRException {
StringBuilder b = new StringBuilder();
MethodDeclaration meth = context.forwards ? methodsFwds.get(name) : methodsBack.get(name);
if (meth != null)
processMethod(indent+1, src, tgt, b, meth, context);
return b.toString();
}
private String findSrcGet(Expression pp1, IterContext iter) {
if (pp1 instanceof MethodCallExpr) {
MethodCallExpr ppm1 = (MethodCallExpr) pp1;
if (ppm1.getScope() != null && "src".equals(iter.patch(ppm1.getScope().toString()))) {
return ppm1.getName();
}
}
if (pp1 instanceof NameExpr && iter.iterVariable != null) {
NameExpr ne = (NameExpr) pp1;
if (ne.toString().equals(iter.iterVariable)) {
String s = iter.iterExpression.substring(4);
if (s.endsWith("()"))
s = s.substring(0, s.length()-2);
return s;
}
}
return null;
}
private boolean isEnumConversion(String name, MapContext context) {
MethodDeclaration meth = context.forwards ? methodsFwds.get(name) : methodsBack.get(name);
if (meth == null)
return false;
for (Node n : meth.getBody().getChildrenNodes()) {
if (n instanceof SwitchStmt)
return true;
}
return false;
}
private boolean isDataType(String type) {
for (StructureDefinition sd : contextR4.allStructures()) {
if (sd.getType().equals(type) && sd.getKind() == StructureDefinitionKind.COMPLEXTYPE && sd.getDerivation() == TypeDerivationRule.SPECIALIZATION)
return true;
}
return false;
}
}

103
org.hl7.fhir.dstu2/pom.xml Normal file
View File

@ -0,0 +1,103 @@
<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>org.hl7.fhir</groupId>
<artifactId>org.hl7.fhir.core</artifactId>
<version>3.7.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>org.hl7.fhir.dstu2</artifactId>
<packaging>jar</packaging>
<dependencies>
<!-- HAPI Dependencies -->
<dependency>
<groupId>ca.uhn.hapi.fhir</groupId>
<artifactId>hapi-fhir-base</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.hl7.fhir</groupId>
<artifactId>org.hl7.fhir.utilities</artifactId>
<version>${project.version}</version>
</dependency>
<!-- UCUM -->
<dependency>
<groupId>org.fhir</groupId>
<artifactId>ucum</artifactId>
<version>1.0.2</version>
<optional>true</optional>
</dependency>
<!-- XML Parsers -->
<dependency>
<groupId>xpp3</groupId>
<artifactId>xpp3</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>xpp3</groupId>
<artifactId>xpp3_xpath</artifactId>
<optional>true</optional>
</dependency>
<!-- Apache POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.1</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.0.1</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.4</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>ST4</artifactId>
<version>4.1</version>
<optional>true</optional>
</dependency>
<!-- HTTP Client -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<optional>true</optional>
</dependency>
<!-- Test dependencies -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.sf.saxon</groupId>
<artifactId>Saxon-HE</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>

View File

@ -0,0 +1,43 @@
package org.hl7.fhir.dstu2.formats;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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 enum FhirFormat {
XML, JSON, TURTLE, TEXT, VBAR;
public String getExtension() {
switch (this) {
case JSON:
return "json";
case TURTLE:
return "ttl";
case XML:
return "xml";
case TEXT:
return "txt";
case VBAR:
return "hl7";
}
return null;
}
}

View File

@ -0,0 +1,124 @@
package org.hl7.fhir.dstu2.formats;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import java.math.BigDecimal;
import java.net.URI;
import org.apache.commons.codec.binary.Base64;
public abstract class FormatUtilities {
public static final String ID_REGEX = "[A-Za-z0-9\\-\\.]{1,64}";
public static final String FHIR_NS = "http://hl7.org/fhir";
public static final String XHTML_NS = "http://www.w3.org/1999/xhtml";
protected String toString(String value) {
return value;
}
protected String toString(int value) {
return java.lang.Integer.toString(value);
}
protected String toString(boolean value) {
return java.lang.Boolean.toString(value);
}
protected String toString(BigDecimal value) {
return value.toString();
}
protected String toString(URI value) {
return value.toString();
}
public static String toString(byte[] value) {
byte[] encodeBase64 = Base64.encodeBase64(value);
return new String(encodeBase64);
}
public static boolean isValidId(String tail) {
return tail.matches(ID_REGEX);
}
public static String makeId(String candidate) {
StringBuilder b = new StringBuilder();
for (char c : candidate.toCharArray())
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == '-')
b.append(c);
return b.toString();
}
public static ParserBase makeParser(FhirFormat format) {
switch (format) {
case XML : return new XmlParser();
case JSON : return new JsonParser();
case TURTLE : throw new Error("unsupported Format "+format.toString()); // return new TurtleParser();
case VBAR : throw new Error("unsupported Format "+format.toString()); //
case TEXT : throw new Error("unsupported Format "+format.toString()); //
}
throw new Error("unsupported Format "+format.toString());
}
public static ParserBase makeParser(String format) {
if ("XML".equalsIgnoreCase(format)) return new XmlParser();
if ("JSON".equalsIgnoreCase(format)) return new JsonParser();
if ("TURTLE".equalsIgnoreCase(format)) throw new Error("unsupported Format "+format.toString()); // return new TurtleParser();
if ("JSONLD".equalsIgnoreCase(format)) throw new Error("unsupported Format "+format.toString()); // return new JsonLdParser();
if ("VBAR".equalsIgnoreCase(format)) throw new Error("unsupported Format "+format.toString()); //
if ("TEXT".equalsIgnoreCase(format)) throw new Error("unsupported Format "+format.toString()); //
throw new Error("unsupported Format "+format);
}
}

View File

@ -0,0 +1,242 @@
package org.hl7.fhir.dstu2.formats;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.IOException;
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import org.hl7.fhir.dstu2.model.Resource;
import org.hl7.fhir.dstu2.model.Type;
import org.hl7.fhir.exceptions.FHIRFormatError;
import org.xmlpull.v1.XmlPullParserException;
/**
* General interface - either an XML or JSON parser: read or write instances
*
* Defined to allow a factory to create a parser of the right type
*/
public interface IParser {
/**
* check what kind of parser this is
*
* @return what kind of parser this is
*/
public ParserType getType();
// -- Parser Configuration ----------------------------------
/**
* Whether to parse or ignore comments - either reading or writing
*/
public boolean getHandleComments();
public IParser setHandleComments(boolean value);
/**
* @param allowUnknownContent Whether to throw an exception if unknown content is found (or just skip it) when parsing
*/
public boolean isAllowUnknownContent();
public IParser setAllowUnknownContent(boolean value);
public enum OutputStyle {
/**
* Produce normal output - no whitespace, except in HTML where whitespace is untouched
*/
NORMAL,
/**
* Produce pretty output - human readable whitespace, HTML whitespace untouched
*/
PRETTY,
/**
* Produce canonical output - no comments, no whitspace, HTML whitespace normlised, JSON attributes sorted alphabetically (slightly slower)
*/
CANONICAL,
}
/**
* Writing:
*/
public OutputStyle getOutputStyle();
public IParser setOutputStyle(OutputStyle value);
/**
* This method is used by the publication tooling to stop the xhrtml narrative being generated.
* It is not valid to use in production use. The tooling uses it to generate json/xml representations in html that are not cluttered by escaped html representations of the html representation
*/
public IParser setSuppressXhtml(String message);
// -- Reading methods ----------------------------------------
/**
* parse content that is known to be a resource
* @throws XmlPullParserException
* @throws FHIRFormatError
* @throws IOException
*/
public Resource parse(InputStream input) throws IOException, FHIRFormatError;
/**
* parse content that is known to be a resource
* @throws UnsupportedEncodingException
* @throws IOException
* @throws FHIRFormatError
*/
public Resource parse(String input) throws UnsupportedEncodingException, FHIRFormatError, IOException;
/**
* parse content that is known to be a resource
* @throws IOException
* @throws FHIRFormatError
*/
public Resource parse(byte[] bytes) throws FHIRFormatError, IOException;
/**
* This is used to parse a type - a fragment of a resource.
* There's no reason to use this in production - it's used
* in the build tools
*
* Not supported by all implementations
*
* @param input
* @param knownType. if this is blank, the parser may try to infer the type (xml only)
* @return
* @throws XmlPullParserException
* @throws FHIRFormatError
* @throws IOException
*/
public Type parseType(InputStream input, String knownType) throws IOException, FHIRFormatError;
/**
* This is used to parse a type - a fragment of a resource.
* There's no reason to use this in production - it's used
* in the build tools
*
* Not supported by all implementations
*
* @param input
* @param knownType. if this is blank, the parser may try to infer the type (xml only)
* @return
* @throws UnsupportedEncodingException
* @throws IOException
* @throws FHIRFormatError
*/
public Type parseType(String input, String knownType) throws UnsupportedEncodingException, FHIRFormatError, IOException;
/**
* This is used to parse a type - a fragment of a resource.
* There's no reason to use this in production - it's used
* in the build tools
*
* Not supported by all implementations
*
* @param input
* @param knownType. if this is blank, the parser may try to infer the type (xml only)
* @return
* @throws IOException
* @throws FHIRFormatError
*/
public Type parseType(byte[] bytes, String knownType) throws FHIRFormatError, IOException;
// -- Writing methods ----------------------------------------
/**
* Compose a resource to a stream, possibly using pretty presentation for a human reader (used in the spec, for example, but not normally in production)
* @throws IOException
*/
public void compose(OutputStream stream, Resource resource) throws IOException;
/**
* Compose a resource to a stream, possibly using pretty presentation for a human reader (used in the spec, for example, but not normally in production)
* @throws IOException
*/
public String composeString(Resource resource) throws IOException;
/**
* Compose a resource to a stream, possibly using pretty presentation for a human reader (used in the spec, for example, but not normally in production)
* @throws IOException
*/
public byte[] composeBytes(Resource resource) throws IOException;
/**
* Compose a type to a stream, possibly using pretty presentation for a human reader (used in the spec, for example, but not normally in production)
*
* Not supported by all implementations. rootName is ignored in the JSON format
* @throws XmlPullParserException
* @throws FHIRFormatError
* @throws IOException
*/
public void compose(OutputStream stream, Type type, String rootName) throws IOException;
/**
* Compose a type to a stream, possibly using pretty presentation for a human reader (used in the spec, for example, but not normally in production)
*
* Not supported by all implementations. rootName is ignored in the JSON format
* @throws IOException
*/
public String composeString(Type type, String rootName) throws IOException;
/**
* Compose a type to a stream, possibly using pretty presentation for a human reader (used in the spec, for example, but not normally in production)
*
* Not supported by all implementations. rootName is ignored in the JSON format
* @throws IOException
*/
public byte[] composeBytes(Type type, String rootName) throws IOException;
}

View File

@ -0,0 +1,59 @@
package org.hl7.fhir.dstu2.formats;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.IOException;
import java.math.BigDecimal;
/**
* Facade to GSON writer, or something that imposes property ordering first
*
* @author Grahame
*
*/
public interface JsonCreator {
void setIndent(String string);
void beginObject() throws IOException;
void endObject() throws IOException;
void nullValue() throws IOException;
void name(String name) throws IOException;
void value(String value) throws IOException;
void value(Boolean value) throws IOException;
void value(BigDecimal value) throws IOException;
void value(Integer value) throws IOException;
void beginArray() throws IOException;
void endArray() throws IOException;
void finish() throws IOException;
}

View File

@ -0,0 +1,248 @@
package org.hl7.fhir.dstu2.formats;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
import com.google.gson.stream.JsonWriter;
public class JsonCreatorCanonical implements JsonCreator {
public class JsonCanValue {
String name;
private JsonCanValue(String name) {
this.name = name;
}
}
private class JsonCanNumberValue extends JsonCanValue {
private BigDecimal value;
private JsonCanNumberValue(String name, BigDecimal value) {
super(name);
this.value = value;
}
}
private class JsonCanIntegerValue extends JsonCanValue {
private Integer value;
private JsonCanIntegerValue(String name, Integer value) {
super(name);
this.value = value;
}
}
private class JsonCanBooleanValue extends JsonCanValue {
private Boolean value;
private JsonCanBooleanValue(String name, Boolean value) {
super(name);
this.value = value;
}
}
private class JsonCanStringValue extends JsonCanValue {
private String value;
private JsonCanStringValue(String name, String value) {
super(name);
this.value = value;
}
}
private class JsonCanNullValue extends JsonCanValue {
private JsonCanNullValue(String name) {
super(name);
}
}
public class JsonCanObject extends JsonCanValue {
boolean array;
List<JsonCanValue> children = new ArrayList<JsonCanValue>();
public JsonCanObject(String name, boolean array) {
super(name);
this.array = array;
}
public void addProp(JsonCanValue obj) {
children.add(obj);
}
}
Stack<JsonCanObject> stack;
JsonCanObject root;
JsonWriter gson;
String name;
public JsonCreatorCanonical(OutputStreamWriter osw) {
stack = new Stack<JsonCreatorCanonical.JsonCanObject>();
gson = new JsonWriter(osw);
name = null;
}
private String takeName() {
String res = name;
name = null;
return res;
}
@Override
public void setIndent(String indent) {
if (!indent.equals(""))
throw new Error("do not use pretty when canonical is set");
gson.setIndent(indent);
}
@Override
public void beginObject() throws IOException {
JsonCanObject obj = new JsonCanObject(takeName(), false);
if (stack.isEmpty())
root = obj;
else
stack.peek().addProp(obj);
stack.push(obj);
}
@Override
public void endObject() throws IOException {
stack.pop();
}
@Override
public void nullValue() throws IOException {
stack.peek().addProp(new JsonCanNullValue(takeName()));
}
@Override
public void name(String name) throws IOException {
this.name = name;
}
@Override
public void value(String value) throws IOException {
stack.peek().addProp(new JsonCanStringValue(takeName(), value));
}
@Override
public void value(Boolean value) throws IOException {
stack.peek().addProp(new JsonCanBooleanValue(takeName(), value));
}
@Override
public void value(BigDecimal value) throws IOException {
stack.peek().addProp(new JsonCanNumberValue(takeName(), value));
}
@Override
public void value(Integer value) throws IOException {
stack.peek().addProp(new JsonCanIntegerValue(takeName(), value));
}
@Override
public void beginArray() throws IOException {
JsonCanObject obj = new JsonCanObject(takeName(), true);
if (!stack.isEmpty())
stack.peek().addProp(obj);
stack.push(obj);
}
@Override
public void endArray() throws IOException {
stack.pop();
}
@Override
public void finish() throws IOException {
writeObject(root);
}
private void writeObject(JsonCanObject obj) throws IOException {
gson.beginObject();
List<String> names = new ArrayList<String>();
for (JsonCanValue v : obj.children)
names.add(v.name);
Collections.sort(names);
for (String n : names) {
gson.name(n);
JsonCanValue v = getPropForName(n, obj.children);
if (v instanceof JsonCanNumberValue)
gson.value(((JsonCanNumberValue) v).value);
else if (v instanceof JsonCanIntegerValue)
gson.value(((JsonCanIntegerValue) v).value);
else if (v instanceof JsonCanBooleanValue)
gson.value(((JsonCanBooleanValue) v).value);
else if (v instanceof JsonCanStringValue)
gson.value(((JsonCanStringValue) v).value);
else if (v instanceof JsonCanNullValue)
gson.nullValue();
else if (v instanceof JsonCanObject) {
JsonCanObject o = (JsonCanObject) v;
if (o.array)
writeArray(o);
else
writeObject(o);
} else
throw new Error("not possible");
}
gson.endObject();
}
private JsonCanValue getPropForName(String name, List<JsonCanValue> children) {
for (JsonCanValue child : children)
if (child.name.equals(name))
return child;
return null;
}
private void writeArray(JsonCanObject arr) throws IOException {
gson.beginArray();
for (JsonCanValue v : arr.children) {
if (v instanceof JsonCanNumberValue)
gson.value(((JsonCanNumberValue) v).value);
else if (v instanceof JsonCanIntegerValue)
gson.value(((JsonCanIntegerValue) v).value);
else if (v instanceof JsonCanBooleanValue)
gson.value(((JsonCanBooleanValue) v).value);
else if (v instanceof JsonCanStringValue)
gson.value(((JsonCanStringValue) v).value);
else if (v instanceof JsonCanNullValue)
gson.nullValue();
else if (v instanceof JsonCanObject) {
JsonCanObject o = (JsonCanObject) v;
if (o.array)
writeArray(o);
else
writeObject(o);
} else
throw new Error("not possible");
}
gson.endArray();
}
}

View File

@ -0,0 +1,99 @@
package org.hl7.fhir.dstu2.formats;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import com.google.gson.stream.JsonWriter;
public class JsonCreatorGson implements JsonCreator {
JsonWriter gson;
public JsonCreatorGson(OutputStreamWriter osw) {
gson = new JsonWriter(osw);
}
@Override
public void setIndent(String indent) {
gson.setIndent(indent);
}
@Override
public void beginObject() throws IOException {
gson.beginObject();
}
@Override
public void endObject() throws IOException {
gson.endObject();
}
@Override
public void nullValue() throws IOException {
gson.nullValue();
}
@Override
public void name(String name) throws IOException {
gson.name(name);
}
@Override
public void value(String value) throws IOException {
gson.value(value);
}
@Override
public void value(Boolean value) throws IOException {
gson.value(value);
}
@Override
public void value(BigDecimal value) throws IOException {
gson.value(value);
}
@Override
public void value(Integer value) throws IOException {
gson.value(value);
}
@Override
public void beginArray() throws IOException {
gson.beginArray();
}
@Override
public void endArray() throws IOException {
gson.endArray();
}
@Override
public void finish() {
// nothing to do here
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,328 @@
package org.hl7.fhir.dstu2.formats;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.util.List;
import org.hl7.fhir.dstu2.model.DomainResource;
import org.hl7.fhir.dstu2.model.Element;
import org.hl7.fhir.dstu2.model.IdType;
import org.hl7.fhir.dstu2.model.Resource;
import org.hl7.fhir.dstu2.model.StringType;
import org.hl7.fhir.dstu2.model.Type;
import org.hl7.fhir.dstu2.model.api.IIdType;
import org.hl7.fhir.exceptions.FHIRFormatError;
import org.hl7.fhir.utilities.TextFile;
import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.xhtml.XhtmlComposer;
import org.hl7.fhir.utilities.xhtml.XhtmlNode;
import org.hl7.fhir.utilities.xhtml.XhtmlParser;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
/**
* General parser for JSON content. You instantiate an JsonParser of these, but you
* actually use parse or parseGeneral defined on this class
*
* The two classes are separated to keep generated and manually maintained code apart.
*/
public abstract class JsonParserBase extends ParserBase implements IParser {
@Override
public ParserType getType() {
return ParserType.JSON;
}
private static com.google.gson.JsonParser parser = new com.google.gson.JsonParser();
// -- in descendent generated code --------------------------------------
abstract protected Resource parseResource(JsonObject json) throws IOException, FHIRFormatError;
abstract protected Type parseType(JsonObject json, String type) throws IOException, FHIRFormatError;
abstract protected Type parseType(String prefix, JsonObject json) throws IOException, FHIRFormatError;
abstract protected boolean hasTypeName(JsonObject json, String prefix);
abstract protected void composeResource(Resource resource) throws IOException;
abstract protected void composeTypeInner(Type type) throws IOException;
/* -- entry points --------------------------------------------------- */
/**
* @throws FHIRFormatError
* Parse content that is known to be a resource
* @throws IOException
* @throws
*/
@Override
public Resource parse(InputStream input) throws IOException, FHIRFormatError {
JsonObject json = loadJson(input);
return parseResource(json);
}
/**
* parse xml that is known to be a resource, and that has already been read into a JSON object
* @throws IOException
* @throws FHIRFormatError
*/
public Resource parse(JsonObject json) throws FHIRFormatError, IOException {
return parseResource(json);
}
@Override
public Type parseType(InputStream input, String type) throws IOException, FHIRFormatError {
JsonObject json = loadJson(input);
return parseType(json, type);
}
/**
* Compose a resource to a stream, possibly using pretty presentation for a human reader (used in the spec, for example, but not normally in production)
* @throws IOException
*/
@Override
public void compose(OutputStream stream, Resource resource) throws IOException {
OutputStreamWriter osw = new OutputStreamWriter(stream, "UTF-8");
if (style == OutputStyle.CANONICAL)
json = new JsonCreatorCanonical(osw);
else
json = new JsonCreatorGson(osw);
json.setIndent(style == OutputStyle.PRETTY ? " " : "");
json.beginObject();
composeResource(resource);
json.endObject();
json.finish();
osw.flush();
}
/**
* Compose a resource using a pre-existing JsonWriter
* @throws IOException
*/
public void compose(JsonCreator writer, Resource resource) throws IOException {
json = writer;
composeResource(resource);
}
@Override
public void compose(OutputStream stream, Type type, String rootName) throws IOException {
OutputStreamWriter osw = new OutputStreamWriter(stream, "UTF-8");
if (style == OutputStyle.CANONICAL)
json = new JsonCreatorCanonical(osw);
else
json = new JsonCreatorGson(osw);
json.setIndent(style == OutputStyle.PRETTY ? " " : "");
json.beginObject();
composeTypeInner(type);
json.endObject();
json.finish();
osw.flush();
}
/* -- json routines --------------------------------------------------- */
protected JsonCreator json;
private boolean htmlPretty;
private JsonObject loadJson(InputStream input) throws JsonSyntaxException, IOException {
return parser.parse(TextFile.streamToString(input)).getAsJsonObject();
}
// private JsonObject loadJson(String input) {
// return parser.parse(input).getAsJsonObject();
// }
//
protected void parseElementProperties(JsonObject json, Element e) throws IOException, FHIRFormatError {
if (json != null && json.has("id"))
e.setId(json.get("id").getAsString());
if (!Utilities.noString(e.getId()))
idMap.put(e.getId(), e);
if (json.has("fhir_comments") && handleComments) {
JsonArray array = json.getAsJsonArray("fhir_comments");
for (int i = 0; i < array.size(); i++) {
e.getFormatCommentsPre().add(array.get(i).getAsString());
}
}
}
protected XhtmlNode parseXhtml(String value) throws IOException, FHIRFormatError {
XhtmlParser prsr = new XhtmlParser();
return prsr.parse(value, "div").getChildNodes().get(0);
}
protected DomainResource parseDomainResource(JsonObject json) throws FHIRFormatError, IOException {
return (DomainResource) parseResource(json);
}
protected void writeNull(String name) throws IOException {
json.nullValue();
}
protected void prop(String name, String value) throws IOException {
if (name != null)
json.name(name);
json.value(value);
}
protected void prop(String name, java.lang.Boolean value) throws IOException {
if (name != null)
json.name(name);
json.value(value);
}
protected void prop(String name, BigDecimal value) throws IOException {
if (name != null)
json.name(name);
json.value(value);
}
protected void prop(String name, java.lang.Integer value) throws IOException {
if (name != null)
json.name(name);
json.value(value);
}
protected void composeXhtml(String name, XhtmlNode html) throws IOException {
if (!Utilities.noString(xhtmlMessage)) {
prop(name, "<div>!-- "+xhtmlMessage+" --></div>");
} else {
XhtmlComposer comp = new XhtmlComposer(true, htmlPretty);
prop(name, comp.compose(html));
}
}
protected void open(String name) throws IOException {
if (name != null)
json.name(name);
json.beginObject();
}
protected void close() throws IOException {
json.endObject();
}
protected void openArray(String name) throws IOException {
if (name != null)
json.name(name);
json.beginArray();
}
protected void closeArray() throws IOException {
json.endArray();
}
protected void openObject(String name) throws IOException {
if (name != null)
json.name(name);
json.beginObject();
}
protected void closeObject() throws IOException {
json.endObject();
}
// protected void composeBinary(String name, Binary element) {
// if (element != null) {
// prop("resourceType", "Binary");
// if (element.getXmlId() != null)
// prop("id", element.getXmlId());
// prop("contentType", element.getContentType());
// prop("content", toString(element.getContent()));
// }
//
// }
protected boolean anyHasExtras(List<? extends Element> list) {
for (Element e : list) {
if (e.hasExtension() || !Utilities.noString(e.getId()))
return true;
}
return false;
}
protected boolean makeComments(Element element) {
return handleComments && (style != OutputStyle.CANONICAL) && !(element.getFormatCommentsPre().isEmpty() && element.getFormatCommentsPost().isEmpty());
}
protected void composeDomainResource(String name, DomainResource e) throws IOException {
openObject(name);
composeResource(e);
close();
}
protected abstract void composeType(String prefix, Type type) throws IOException;
abstract void composeStringCore(String name, StringType value, boolean inArray) throws IOException;
protected void composeStringCore(String name, IIdType value, boolean inArray) throws IOException {
composeStringCore(name, new StringType(value.getValue()), inArray);
}
abstract void composeStringExtras(String name, StringType value, boolean inArray) throws IOException;
protected void composeStringExtras(String name, IIdType value, boolean inArray) throws IOException {
composeStringExtras(name, new StringType(value.getValue()), inArray);
}
protected void parseElementProperties(JsonObject theAsJsonObject, IIdType theReferenceElement) throws FHIRFormatError, IOException {
parseElementProperties(theAsJsonObject, (Element)theReferenceElement);
}
protected void parseElementProperties(JsonObject theAsJsonObject, IdType theReferenceElement) throws FHIRFormatError, IOException {
parseElementProperties(theAsJsonObject, (Element)theReferenceElement);
}
}

View File

@ -0,0 +1,234 @@
package org.hl7.fhir.dstu2.formats;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.hl7.fhir.dstu2.model.Resource;
import org.hl7.fhir.dstu2.model.Type;
import org.hl7.fhir.exceptions.FHIRFormatError;
import org.hl7.fhir.utilities.Utilities;
public abstract class ParserBase extends FormatUtilities implements IParser {
// -- implementation of variant type methods from the interface --------------------------------
public Resource parse(String input) throws FHIRFormatError, IOException {
return parse(input.getBytes("UTF-8"));
}
public Resource parse(byte[] bytes) throws FHIRFormatError, IOException {
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
return parse(bi);
}
public Type parseType(String input, String typeName) throws FHIRFormatError, IOException {
return parseType(input.getBytes("UTF-8"), typeName);
}
public Type parseType(byte[] bytes, String typeName) throws FHIRFormatError, IOException {
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
return parseType(bi, typeName);
}
public String composeString(Resource resource) throws IOException {
return new String(composeBytes(resource));
}
public byte[] composeBytes(Resource resource) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
compose(bytes, resource);
bytes.close();
return bytes.toByteArray();
}
public String composeString(Type type, String typeName) throws IOException {
return new String(composeBytes(type, typeName));
}
public byte[] composeBytes(Type type, String typeName) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
compose(bytes, type, typeName);
bytes.close();
return bytes.toByteArray();
}
// -- Parser Configuration --------------------------------
protected String xhtmlMessage;
@Override
public IParser setSuppressXhtml(String message) {
xhtmlMessage = message;
return this;
}
protected boolean handleComments = true;
public boolean getHandleComments() {
return handleComments;
}
public IParser setHandleComments(boolean value) {
this.handleComments = value;
return this;
}
/**
* Whether to throw an exception if unknown content is found (or just skip it)
*/
protected boolean allowUnknownContent;
/**
* @return Whether to throw an exception if unknown content is found (or just skip it)
*/
public boolean isAllowUnknownContent() {
return allowUnknownContent;
}
/**
* @param allowUnknownContent Whether to throw an exception if unknown content is found (or just skip it)
*/
public IParser setAllowUnknownContent(boolean allowUnknownContent) {
this.allowUnknownContent = allowUnknownContent;
return this;
}
protected OutputStyle style = OutputStyle.NORMAL;
public OutputStyle getOutputStyle() {
return style;
}
public IParser setOutputStyle(OutputStyle style) {
this.style = style;
return this;
}
// -- Parser Utilities --------------------------------
protected Map<String, Object> idMap = new HashMap<String, Object>();
protected int parseIntegerPrimitive(String value) {
if (value.startsWith("+") && Utilities.isInteger(value.substring(1)))
value = value.substring(1);
return java.lang.Integer.parseInt(value);
}
protected int parseIntegerPrimitive(java.lang.Long value) {
if (value < java.lang.Integer.MIN_VALUE || value > java.lang.Integer.MAX_VALUE) {
throw new IllegalArgumentException
(value + " cannot be cast to int without changing its value.");
}
return value.intValue();
}
protected String parseCodePrimitive(String value) {
return value;
}
protected String parseTimePrimitive(String value) throws ParseException {
return value;
}
protected BigDecimal parseDecimalPrimitive(BigDecimal value) {
return value;
}
protected BigDecimal parseDecimalPrimitive(String value) {
return new BigDecimal(value);
}
protected String parseUriPrimitive(String value) {
return value;
}
protected byte[] parseBase64BinaryPrimitive(String value) {
return Base64.decodeBase64(value.getBytes());
}
protected String parseOidPrimitive(String value) {
return value;
}
protected Boolean parseBooleanPrimitive(String value) {
return java.lang.Boolean.valueOf(value);
}
protected Boolean parseBooleanPrimitive(Boolean value) {
return java.lang.Boolean.valueOf(value);
}
protected String parseIdPrimitive(String value) {
return value;
}
protected String parseStringPrimitive(String value) {
return value;
}
protected String parseUuidPrimitive(String value) {
return value;
}
}

View File

@ -0,0 +1,51 @@
package org.hl7.fhir.dstu2.formats;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/**
* Used in factory methods for parsers, for requesting a parser of a particular type
* (see IWorkerContext)
*
* @author Grahame
*
*/
public enum ParserType {
/**
* XML as specified in specification
*/
XML,
/**
* JSON as specified in the specification
*/
JSON,
/**
* XHTML - write narrative (generate if necessary). No read
*/
XHTML,
/**
* RDF is not supported yet
*/
RDF
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,401 @@
package org.hl7.fhir.dstu2.formats;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.hl7.fhir.dstu2.model.Base;
import org.hl7.fhir.dstu2.model.DomainResource;
import org.hl7.fhir.dstu2.model.Element;
import org.hl7.fhir.dstu2.model.Resource;
import org.hl7.fhir.dstu2.model.StringType;
import org.hl7.fhir.dstu2.model.Type;
import org.hl7.fhir.dstu2.model.api.IIdType;
import org.hl7.fhir.exceptions.FHIRFormatError;
import org.hl7.fhir.utilities.Utilities;
import org.hl7.fhir.utilities.xhtml.NodeType;
import org.hl7.fhir.utilities.xhtml.XhtmlComposer;
import org.hl7.fhir.utilities.xhtml.XhtmlNode;
import org.hl7.fhir.utilities.xhtml.XhtmlParser;
import org.hl7.fhir.utilities.xml.IXMLWriter;
import org.hl7.fhir.utilities.xml.XMLWriter;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
/**
* General parser for XML content. You instantiate an XmlParser of these, but you
* actually use parse or parseGeneral defined on this class
*
* The two classes are separated to keep generated and manually maintained code apart.
*/
public abstract class XmlParserBase extends ParserBase implements IParser {
@Override
public ParserType getType() {
return ParserType.XML;
}
// -- in descendent generated code --------------------------------------
abstract protected Resource parseResource(XmlPullParser xpp) throws XmlPullParserException, IOException, FHIRFormatError ;
abstract protected Type parseType(XmlPullParser xml, String type) throws XmlPullParserException, IOException, FHIRFormatError ;
abstract protected void composeType(String prefix, Type type) throws IOException ;
/* -- entry points --------------------------------------------------- */
/**
* Parse content that is known to be a resource
* @
*/
@Override
public Resource parse(InputStream input) throws IOException, FHIRFormatError {
try {
XmlPullParser xpp = loadXml(input);
return parse(xpp);
} catch (XmlPullParserException e) {
throw new FHIRFormatError(e.getMessage(), e);
}
}
/**
* parse xml that is known to be a resource, and that is already being read by an XML Pull Parser
* This is if a resource is in a bigger piece of XML.
* @
*/
public Resource parse(XmlPullParser xpp) throws IOException, FHIRFormatError, XmlPullParserException {
if (xpp.getNamespace() == null)
throw new FHIRFormatError("This does not appear to be a FHIR resource (no namespace '"+xpp.getNamespace()+"') (@ /) "+Integer.toString(xpp.getEventType()));
if (!xpp.getNamespace().equals(FHIR_NS))
throw new FHIRFormatError("This does not appear to be a FHIR resource (wrong namespace '"+xpp.getNamespace()+"') (@ /)");
return parseResource(xpp);
}
@Override
public Type parseType(InputStream input, String knownType) throws IOException, FHIRFormatError {
try {
XmlPullParser xml = loadXml(input);
return parseType(xml, knownType);
} catch (XmlPullParserException e) {
throw new FHIRFormatError(e.getMessage(), e);
}
}
/**
* Compose a resource to a stream, possibly using pretty presentation for a human reader (used in the spec, for example, but not normally in production)
* @
*/
@Override
public void compose(OutputStream stream, Resource resource) throws IOException {
XMLWriter writer = new XMLWriter(stream, "UTF-8");
writer.setPretty(style == OutputStyle.PRETTY);
writer.start();
compose(writer, resource, writer.isPretty());
writer.end();
}
/**
* Compose a resource to a stream, possibly using pretty presentation for a human reader, and maybe a different choice in the xhtml narrative (used in the spec in one place, but should not be used in production)
* @
*/
public void compose(OutputStream stream, Resource resource, boolean htmlPretty) throws IOException {
XMLWriter writer = new XMLWriter(stream, "UTF-8");
writer.setPretty(style == OutputStyle.PRETTY);
writer.start();
compose(writer, resource, htmlPretty);
writer.end();
}
/**
* Compose a type to a stream (used in the spec, for example, but not normally in production)
* @
*/
public void compose(OutputStream stream, String rootName, Type type) throws IOException {
xml = new XMLWriter(stream, "UTF-8");
xml.setPretty(style == OutputStyle.PRETTY);
xml.start();
xml.setDefaultNamespace(FHIR_NS);
composeType(Utilities.noString(rootName) ? "value" : rootName, type);
xml.end();
}
@Override
public void compose(OutputStream stream, Type type, String rootName) throws IOException {
xml = new XMLWriter(stream, "UTF-8");
xml.setPretty(style == OutputStyle.PRETTY);
xml.start();
xml.setDefaultNamespace(FHIR_NS);
composeType(Utilities.noString(rootName) ? "value" : rootName, type);
xml.end();
}
/* -- xml routines --------------------------------------------------- */
protected XmlPullParser loadXml(String source) throws UnsupportedEncodingException, XmlPullParserException, IOException {
return loadXml(new ByteArrayInputStream(source.getBytes("UTF-8")));
}
protected XmlPullParser loadXml(InputStream stream) throws XmlPullParserException, IOException {
BufferedInputStream input = new BufferedInputStream(stream);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance(System.getProperty(XmlPullParserFactory.PROPERTY_NAME), null);
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(input, "UTF-8");
next(xpp);
nextNoWhitespace(xpp);
return xpp;
}
protected int next(XmlPullParser xpp) throws XmlPullParserException, IOException {
if (handleComments)
return xpp.nextToken();
else
return xpp.next();
}
protected List<String> comments = new ArrayList<String>();
protected int nextNoWhitespace(XmlPullParser xpp) throws XmlPullParserException, IOException {
int eventType = xpp.getEventType();
while ((eventType == XmlPullParser.TEXT && xpp.isWhitespace()) || (eventType == XmlPullParser.COMMENT)
|| (eventType == XmlPullParser.CDSECT) || (eventType == XmlPullParser.IGNORABLE_WHITESPACE)
|| (eventType == XmlPullParser.PROCESSING_INSTRUCTION) || (eventType == XmlPullParser.DOCDECL)) {
if (eventType == XmlPullParser.COMMENT) {
comments.add(xpp.getText());
}
eventType = next(xpp);
}
return eventType;
}
protected void skipElementWithContent(XmlPullParser xpp) throws XmlPullParserException, IOException {
// when this is called, we are pointing an element that may have content
while (xpp.getEventType() != XmlPullParser.END_TAG) {
next(xpp);
if (xpp.getEventType() == XmlPullParser.START_TAG)
skipElementWithContent(xpp);
}
next(xpp);
}
protected void skipEmptyElement(XmlPullParser xpp) throws XmlPullParserException, IOException {
while (xpp.getEventType() != XmlPullParser.END_TAG)
next(xpp);
next(xpp);
}
protected IXMLWriter xml;
protected boolean htmlPretty;
/* -- worker routines --------------------------------------------------- */
protected void parseTypeAttributes(XmlPullParser xpp, Type t) {
parseElementAttributes(xpp, t);
}
protected void parseElementAttributes(XmlPullParser xpp, Element e) {
if (xpp.getAttributeValue(null, "id") != null) {
e.setId(xpp.getAttributeValue(null, "id"));
idMap.put(e.getId(), e);
}
if (!comments.isEmpty()) {
e.getFormatCommentsPre().addAll(comments);
comments.clear();
}
}
protected void parseElementClose(Base e) {
if (!comments.isEmpty()) {
e.getFormatCommentsPost().addAll(comments);
comments.clear();
}
}
protected void parseBackboneAttributes(XmlPullParser xpp, Element e) {
parseElementAttributes(xpp, e);
}
private String pathForLocation(XmlPullParser xpp) {
return xpp.getPositionDescription();
}
protected void unknownContent(XmlPullParser xpp) throws FHIRFormatError {
if (!isAllowUnknownContent())
throw new FHIRFormatError("Unknown Content "+xpp.getName()+" @ "+pathForLocation(xpp));
}
protected XhtmlNode parseXhtml(XmlPullParser xpp) throws XmlPullParserException, IOException, FHIRFormatError {
XhtmlParser prsr = new XhtmlParser();
return prsr.parseHtmlNode(xpp);
}
private String parseString(XmlPullParser xpp) throws XmlPullParserException, FHIRFormatError, IOException {
StringBuilder res = new StringBuilder();
next(xpp);
while (xpp.getEventType() == XmlPullParser.TEXT || xpp.getEventType() == XmlPullParser.IGNORABLE_WHITESPACE || xpp.getEventType() == XmlPullParser.ENTITY_REF) {
res.append(xpp.getText());
next(xpp);
}
if (xpp.getEventType() != XmlPullParser.END_TAG)
throw new FHIRFormatError("Bad String Structure - parsed "+res.toString()+" now found "+Integer.toString(xpp.getEventType()));
next(xpp);
return res.length() == 0 ? null : res.toString();
}
private int parseInt(XmlPullParser xpp) throws FHIRFormatError, XmlPullParserException, IOException {
int res = -1;
String textNode = parseString(xpp);
res = java.lang.Integer.parseInt(textNode);
return res;
}
protected DomainResource parseDomainResourceContained(XmlPullParser xpp) throws IOException, FHIRFormatError, XmlPullParserException {
next(xpp);
int eventType = nextNoWhitespace(xpp);
if (eventType == XmlPullParser.START_TAG) {
DomainResource dr = (DomainResource) parseResource(xpp);
nextNoWhitespace(xpp);
next(xpp);
return dr;
} else {
unknownContent(xpp);
return null;
}
}
protected Resource parseResourceContained(XmlPullParser xpp) throws IOException, FHIRFormatError, XmlPullParserException {
next(xpp);
int eventType = nextNoWhitespace(xpp);
if (eventType == XmlPullParser.START_TAG) {
Resource r = (Resource) parseResource(xpp);
nextNoWhitespace(xpp);
next(xpp);
return r;
} else {
unknownContent(xpp);
return null;
}
}
public void compose(IXMLWriter writer, Resource resource, boolean htmlPretty) throws IOException {
this.htmlPretty = htmlPretty;
xml = writer;
xml.setDefaultNamespace(FHIR_NS);
composeResource(resource);
}
protected abstract void composeResource(Resource resource) throws IOException ;
protected void composeElementAttributes(Element element) throws IOException {
if (style != OutputStyle.CANONICAL)
for (String comment : element.getFormatCommentsPre())
xml.comment(comment, getOutputStyle() == OutputStyle.PRETTY);
if (element.getId() != null)
xml.attribute("id", element.getId());
}
protected void composeElementClose(Base base) throws IOException {
if (style != OutputStyle.CANONICAL)
for (String comment : base.getFormatCommentsPost())
xml.comment(comment, getOutputStyle() == OutputStyle.PRETTY);
}
protected void composeTypeAttributes(Type type) throws IOException {
composeElementAttributes(type);
}
protected void composeXhtml(String name, XhtmlNode html) throws IOException {
if (!Utilities.noString(xhtmlMessage)) {
xml.enter(XhtmlComposer.XHTML_NS, name);
xml.comment(xhtmlMessage, false);
xml.exit(XhtmlComposer.XHTML_NS, name);
} else {
XhtmlComposer comp = new XhtmlComposer(true, htmlPretty);
// name is also found in the html and should the same
// ? check that
boolean oldPretty = xml.isPretty();
if (html.getNodeType() != NodeType.Text)
xml.namespace(XhtmlComposer.XHTML_NS, null);
comp.compose(xml, html);
xml.setPretty(oldPretty);
}
}
abstract protected void composeString(String name, StringType value) throws IOException ;
protected void composeString(String name, IIdType value) throws IOException {
composeString(name, new StringType(value.getValue()));
}
protected void composeDomainResource(String name, DomainResource res) throws IOException {
xml.enter(FHIR_NS, name);
composeResource(res.getResourceType().toString(), res);
xml.exit(FHIR_NS, name);
}
protected abstract void composeResource(String name, Resource res) throws IOException ;
}

View File

@ -0,0 +1,816 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Wed, Jul 13, 2016 05:32+1000 for FHIR v1.0.2
import java.util.ArrayList;
import java.util.List;
import org.hl7.fhir.dstu2.model.annotations.Child;
import org.hl7.fhir.dstu2.model.annotations.Description;
import org.hl7.fhir.dstu2.model.annotations.ResourceDef;
import org.hl7.fhir.dstu2.model.annotations.SearchParamDefinition;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.utilities.Utilities;
/**
* A financial tool for tracking value accrued for a particular purpose. In the healthcare field, used to track charges for a patient, cost centres, etc.
*/
@ResourceDef(name="Account", profile="http://hl7.org/fhir/Profile/Account")
public class Account extends DomainResource {
public enum AccountStatus {
/**
* This account is active and may be used.
*/
ACTIVE,
/**
* This account is inactive and should not be used to track financial information.
*/
INACTIVE,
/**
* added to help the parsers
*/
NULL;
public static AccountStatus fromCode(String codeString) throws FHIRException {
if (codeString == null || "".equals(codeString))
return null;
if ("active".equals(codeString))
return ACTIVE;
if ("inactive".equals(codeString))
return INACTIVE;
throw new FHIRException("Unknown AccountStatus code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case ACTIVE: return "active";
case INACTIVE: return "inactive";
default: return "?";
}
}
public String getSystem() {
switch (this) {
case ACTIVE: return "http://hl7.org/fhir/account-status";
case INACTIVE: return "http://hl7.org/fhir/account-status";
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case ACTIVE: return "This account is active and may be used.";
case INACTIVE: return "This account is inactive and should not be used to track financial information.";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case ACTIVE: return "Active";
case INACTIVE: return "Inactive";
default: return "?";
}
}
}
public static class AccountStatusEnumFactory implements EnumFactory<AccountStatus> {
public AccountStatus fromCode(String codeString) throws IllegalArgumentException {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("active".equals(codeString))
return AccountStatus.ACTIVE;
if ("inactive".equals(codeString))
return AccountStatus.INACTIVE;
throw new IllegalArgumentException("Unknown AccountStatus code '"+codeString+"'");
}
public Enumeration<AccountStatus> fromType(Base code) throws FHIRException {
if (code == null || code.isEmpty())
return null;
String codeString = ((PrimitiveType) code).asStringValue();
if (codeString == null || "".equals(codeString))
return null;
if ("active".equals(codeString))
return new Enumeration<AccountStatus>(this, AccountStatus.ACTIVE);
if ("inactive".equals(codeString))
return new Enumeration<AccountStatus>(this, AccountStatus.INACTIVE);
throw new FHIRException("Unknown AccountStatus code '"+codeString+"'");
}
public String toCode(AccountStatus code) {
if (code == AccountStatus.ACTIVE)
return "active";
if (code == AccountStatus.INACTIVE)
return "inactive";
return "?";
}
}
/**
* Unique identifier used to reference the account. May or may not be intended for human use (e.g. credit card number).
*/
@Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Account number", formalDefinition="Unique identifier used to reference the account. May or may not be intended for human use (e.g. credit card number)." )
protected List<Identifier> identifier;
/**
* Name used for the account when displaying it to humans in reports, etc.
*/
@Child(name = "name", type = {StringType.class}, order=1, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Human-readable label", formalDefinition="Name used for the account when displaying it to humans in reports, etc." )
protected StringType name;
/**
* Categorizes the account for reporting and searching purposes.
*/
@Child(name = "type", type = {CodeableConcept.class}, order=2, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="E.g. patient, expense, depreciation", formalDefinition="Categorizes the account for reporting and searching purposes." )
protected CodeableConcept type;
/**
* Indicates whether the account is presently used/useable or not.
*/
@Child(name = "status", type = {CodeType.class}, order=3, min=0, max=1, modifier=true, summary=true)
@Description(shortDefinition="active | inactive", formalDefinition="Indicates whether the account is presently used/useable or not." )
protected Enumeration<AccountStatus> status;
/**
* Indicates the period of time over which the account is allowed.
*/
@Child(name = "activePeriod", type = {Period.class}, order=4, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Valid from..to", formalDefinition="Indicates the period of time over which the account is allowed." )
protected Period activePeriod;
/**
* Identifies the currency to which transactions must be converted when crediting or debiting the account.
*/
@Child(name = "currency", type = {Coding.class}, order=5, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Base currency in which balance is tracked", formalDefinition="Identifies the currency to which transactions must be converted when crediting or debiting the account." )
protected Coding currency;
/**
* Represents the sum of all credits less all debits associated with the account. Might be positive, zero or negative.
*/
@Child(name = "balance", type = {Money.class}, order=6, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="How much is in account?", formalDefinition="Represents the sum of all credits less all debits associated with the account. Might be positive, zero or negative." )
protected Money balance;
/**
* Identifies the period of time the account applies to; e.g. accounts created per fiscal year, quarter, etc.
*/
@Child(name = "coveragePeriod", type = {Period.class}, order=7, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Transaction window", formalDefinition="Identifies the period of time the account applies to; e.g. accounts created per fiscal year, quarter, etc." )
protected Period coveragePeriod;
/**
* Identifies the patient, device, practitioner, location or other object the account is associated with.
*/
@Child(name = "subject", type = {Patient.class, Device.class, Practitioner.class, Location.class, HealthcareService.class, Organization.class}, order=8, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="What is account tied to?", formalDefinition="Identifies the patient, device, practitioner, location or other object the account is associated with." )
protected Reference subject;
/**
* The actual object that is the target of the reference (Identifies the patient, device, practitioner, location or other object the account is associated with.)
*/
protected Resource subjectTarget;
/**
* Indicates the organization, department, etc. with responsibility for the account.
*/
@Child(name = "owner", type = {Organization.class}, order=9, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Who is responsible?", formalDefinition="Indicates the organization, department, etc. with responsibility for the account." )
protected Reference owner;
/**
* The actual object that is the target of the reference (Indicates the organization, department, etc. with responsibility for the account.)
*/
protected Organization ownerTarget;
/**
* Provides additional information about what the account tracks and how it is used.
*/
@Child(name = "description", type = {StringType.class}, order=10, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Explanation of purpose/use", formalDefinition="Provides additional information about what the account tracks and how it is used." )
protected StringType description;
private static final long serialVersionUID = -1926153194L;
/*
* Constructor
*/
public Account() {
super();
}
/**
* @return {@link #identifier} (Unique identifier used to reference the account. May or may not be intended for human use (e.g. credit card number).)
*/
public List<Identifier> getIdentifier() {
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
return this.identifier;
}
public boolean hasIdentifier() {
if (this.identifier == null)
return false;
for (Identifier item : this.identifier)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #identifier} (Unique identifier used to reference the account. May or may not be intended for human use (e.g. credit card number).)
*/
// syntactic sugar
public Identifier addIdentifier() { //3
Identifier t = new Identifier();
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return t;
}
// syntactic sugar
public Account addIdentifier(Identifier t) { //3
if (t == null)
return this;
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return this;
}
/**
* @return {@link #name} (Name used for the account when displaying it to humans in reports, etc.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value
*/
public StringType getNameElement() {
if (this.name == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Account.name");
else if (Configuration.doAutoCreate())
this.name = new StringType(); // bb
return this.name;
}
public boolean hasNameElement() {
return this.name != null && !this.name.isEmpty();
}
public boolean hasName() {
return this.name != null && !this.name.isEmpty();
}
/**
* @param value {@link #name} (Name used for the account when displaying it to humans in reports, etc.). This is the underlying object with id, value and extensions. The accessor "getName" gives direct access to the value
*/
public Account setNameElement(StringType value) {
this.name = value;
return this;
}
/**
* @return Name used for the account when displaying it to humans in reports, etc.
*/
public String getName() {
return this.name == null ? null : this.name.getValue();
}
/**
* @param value Name used for the account when displaying it to humans in reports, etc.
*/
public Account setName(String value) {
if (Utilities.noString(value))
this.name = null;
else {
if (this.name == null)
this.name = new StringType();
this.name.setValue(value);
}
return this;
}
/**
* @return {@link #type} (Categorizes the account for reporting and searching purposes.)
*/
public CodeableConcept getType() {
if (this.type == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Account.type");
else if (Configuration.doAutoCreate())
this.type = new CodeableConcept(); // cc
return this.type;
}
public boolean hasType() {
return this.type != null && !this.type.isEmpty();
}
/**
* @param value {@link #type} (Categorizes the account for reporting and searching purposes.)
*/
public Account setType(CodeableConcept value) {
this.type = value;
return this;
}
/**
* @return {@link #status} (Indicates whether the account is presently used/useable or not.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value
*/
public Enumeration<AccountStatus> getStatusElement() {
if (this.status == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Account.status");
else if (Configuration.doAutoCreate())
this.status = new Enumeration<AccountStatus>(new AccountStatusEnumFactory()); // bb
return this.status;
}
public boolean hasStatusElement() {
return this.status != null && !this.status.isEmpty();
}
public boolean hasStatus() {
return this.status != null && !this.status.isEmpty();
}
/**
* @param value {@link #status} (Indicates whether the account is presently used/useable or not.). This is the underlying object with id, value and extensions. The accessor "getStatus" gives direct access to the value
*/
public Account setStatusElement(Enumeration<AccountStatus> value) {
this.status = value;
return this;
}
/**
* @return Indicates whether the account is presently used/useable or not.
*/
public AccountStatus getStatus() {
return this.status == null ? null : this.status.getValue();
}
/**
* @param value Indicates whether the account is presently used/useable or not.
*/
public Account setStatus(AccountStatus value) {
if (value == null)
this.status = null;
else {
if (this.status == null)
this.status = new Enumeration<AccountStatus>(new AccountStatusEnumFactory());
this.status.setValue(value);
}
return this;
}
/**
* @return {@link #activePeriod} (Indicates the period of time over which the account is allowed.)
*/
public Period getActivePeriod() {
if (this.activePeriod == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Account.activePeriod");
else if (Configuration.doAutoCreate())
this.activePeriod = new Period(); // cc
return this.activePeriod;
}
public boolean hasActivePeriod() {
return this.activePeriod != null && !this.activePeriod.isEmpty();
}
/**
* @param value {@link #activePeriod} (Indicates the period of time over which the account is allowed.)
*/
public Account setActivePeriod(Period value) {
this.activePeriod = value;
return this;
}
/**
* @return {@link #currency} (Identifies the currency to which transactions must be converted when crediting or debiting the account.)
*/
public Coding getCurrency() {
if (this.currency == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Account.currency");
else if (Configuration.doAutoCreate())
this.currency = new Coding(); // cc
return this.currency;
}
public boolean hasCurrency() {
return this.currency != null && !this.currency.isEmpty();
}
/**
* @param value {@link #currency} (Identifies the currency to which transactions must be converted when crediting or debiting the account.)
*/
public Account setCurrency(Coding value) {
this.currency = value;
return this;
}
/**
* @return {@link #balance} (Represents the sum of all credits less all debits associated with the account. Might be positive, zero or negative.)
*/
public Money getBalance() {
if (this.balance == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Account.balance");
else if (Configuration.doAutoCreate())
this.balance = new Money(); // cc
return this.balance;
}
public boolean hasBalance() {
return this.balance != null && !this.balance.isEmpty();
}
/**
* @param value {@link #balance} (Represents the sum of all credits less all debits associated with the account. Might be positive, zero or negative.)
*/
public Account setBalance(Money value) {
this.balance = value;
return this;
}
/**
* @return {@link #coveragePeriod} (Identifies the period of time the account applies to; e.g. accounts created per fiscal year, quarter, etc.)
*/
public Period getCoveragePeriod() {
if (this.coveragePeriod == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Account.coveragePeriod");
else if (Configuration.doAutoCreate())
this.coveragePeriod = new Period(); // cc
return this.coveragePeriod;
}
public boolean hasCoveragePeriod() {
return this.coveragePeriod != null && !this.coveragePeriod.isEmpty();
}
/**
* @param value {@link #coveragePeriod} (Identifies the period of time the account applies to; e.g. accounts created per fiscal year, quarter, etc.)
*/
public Account setCoveragePeriod(Period value) {
this.coveragePeriod = value;
return this;
}
/**
* @return {@link #subject} (Identifies the patient, device, practitioner, location or other object the account is associated with.)
*/
public Reference getSubject() {
if (this.subject == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Account.subject");
else if (Configuration.doAutoCreate())
this.subject = new Reference(); // cc
return this.subject;
}
public boolean hasSubject() {
return this.subject != null && !this.subject.isEmpty();
}
/**
* @param value {@link #subject} (Identifies the patient, device, practitioner, location or other object the account is associated with.)
*/
public Account setSubject(Reference value) {
this.subject = value;
return this;
}
/**
* @return {@link #subject} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Identifies the patient, device, practitioner, location or other object the account is associated with.)
*/
public Resource getSubjectTarget() {
return this.subjectTarget;
}
/**
* @param value {@link #subject} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Identifies the patient, device, practitioner, location or other object the account is associated with.)
*/
public Account setSubjectTarget(Resource value) {
this.subjectTarget = value;
return this;
}
/**
* @return {@link #owner} (Indicates the organization, department, etc. with responsibility for the account.)
*/
public Reference getOwner() {
if (this.owner == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Account.owner");
else if (Configuration.doAutoCreate())
this.owner = new Reference(); // cc
return this.owner;
}
public boolean hasOwner() {
return this.owner != null && !this.owner.isEmpty();
}
/**
* @param value {@link #owner} (Indicates the organization, department, etc. with responsibility for the account.)
*/
public Account setOwner(Reference value) {
this.owner = value;
return this;
}
/**
* @return {@link #owner} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Indicates the organization, department, etc. with responsibility for the account.)
*/
public Organization getOwnerTarget() {
if (this.ownerTarget == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Account.owner");
else if (Configuration.doAutoCreate())
this.ownerTarget = new Organization(); // aa
return this.ownerTarget;
}
/**
* @param value {@link #owner} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Indicates the organization, department, etc. with responsibility for the account.)
*/
public Account setOwnerTarget(Organization value) {
this.ownerTarget = value;
return this;
}
/**
* @return {@link #description} (Provides additional information about what the account tracks and how it is used.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value
*/
public StringType getDescriptionElement() {
if (this.description == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Account.description");
else if (Configuration.doAutoCreate())
this.description = new StringType(); // bb
return this.description;
}
public boolean hasDescriptionElement() {
return this.description != null && !this.description.isEmpty();
}
public boolean hasDescription() {
return this.description != null && !this.description.isEmpty();
}
/**
* @param value {@link #description} (Provides additional information about what the account tracks and how it is used.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value
*/
public Account setDescriptionElement(StringType value) {
this.description = value;
return this;
}
/**
* @return Provides additional information about what the account tracks and how it is used.
*/
public String getDescription() {
return this.description == null ? null : this.description.getValue();
}
/**
* @param value Provides additional information about what the account tracks and how it is used.
*/
public Account setDescription(String value) {
if (Utilities.noString(value))
this.description = null;
else {
if (this.description == null)
this.description = new StringType();
this.description.setValue(value);
}
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("identifier", "Identifier", "Unique identifier used to reference the account. May or may not be intended for human use (e.g. credit card number).", 0, java.lang.Integer.MAX_VALUE, identifier));
childrenList.add(new Property("name", "string", "Name used for the account when displaying it to humans in reports, etc.", 0, java.lang.Integer.MAX_VALUE, name));
childrenList.add(new Property("type", "CodeableConcept", "Categorizes the account for reporting and searching purposes.", 0, java.lang.Integer.MAX_VALUE, type));
childrenList.add(new Property("status", "code", "Indicates whether the account is presently used/useable or not.", 0, java.lang.Integer.MAX_VALUE, status));
childrenList.add(new Property("activePeriod", "Period", "Indicates the period of time over which the account is allowed.", 0, java.lang.Integer.MAX_VALUE, activePeriod));
childrenList.add(new Property("currency", "Coding", "Identifies the currency to which transactions must be converted when crediting or debiting the account.", 0, java.lang.Integer.MAX_VALUE, currency));
childrenList.add(new Property("balance", "Money", "Represents the sum of all credits less all debits associated with the account. Might be positive, zero or negative.", 0, java.lang.Integer.MAX_VALUE, balance));
childrenList.add(new Property("coveragePeriod", "Period", "Identifies the period of time the account applies to; e.g. accounts created per fiscal year, quarter, etc.", 0, java.lang.Integer.MAX_VALUE, coveragePeriod));
childrenList.add(new Property("subject", "Reference(Patient|Device|Practitioner|Location|HealthcareService|Organization)", "Identifies the patient, device, practitioner, location or other object the account is associated with.", 0, java.lang.Integer.MAX_VALUE, subject));
childrenList.add(new Property("owner", "Reference(Organization)", "Indicates the organization, department, etc. with responsibility for the account.", 0, java.lang.Integer.MAX_VALUE, owner));
childrenList.add(new Property("description", "string", "Provides additional information about what the account tracks and how it is used.", 0, java.lang.Integer.MAX_VALUE, description));
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("identifier"))
this.getIdentifier().add(castToIdentifier(value));
else if (name.equals("name"))
this.name = castToString(value); // StringType
else if (name.equals("type"))
this.type = castToCodeableConcept(value); // CodeableConcept
else if (name.equals("status"))
this.status = new AccountStatusEnumFactory().fromType(value); // Enumeration<AccountStatus>
else if (name.equals("activePeriod"))
this.activePeriod = castToPeriod(value); // Period
else if (name.equals("currency"))
this.currency = castToCoding(value); // Coding
else if (name.equals("balance"))
this.balance = castToMoney(value); // Money
else if (name.equals("coveragePeriod"))
this.coveragePeriod = castToPeriod(value); // Period
else if (name.equals("subject"))
this.subject = castToReference(value); // Reference
else if (name.equals("owner"))
this.owner = castToReference(value); // Reference
else if (name.equals("description"))
this.description = castToString(value); // StringType
else
super.setProperty(name, value);
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("identifier")) {
return addIdentifier();
}
else if (name.equals("name")) {
throw new FHIRException("Cannot call addChild on a primitive type Account.name");
}
else if (name.equals("type")) {
this.type = new CodeableConcept();
return this.type;
}
else if (name.equals("status")) {
throw new FHIRException("Cannot call addChild on a primitive type Account.status");
}
else if (name.equals("activePeriod")) {
this.activePeriod = new Period();
return this.activePeriod;
}
else if (name.equals("currency")) {
this.currency = new Coding();
return this.currency;
}
else if (name.equals("balance")) {
this.balance = new Money();
return this.balance;
}
else if (name.equals("coveragePeriod")) {
this.coveragePeriod = new Period();
return this.coveragePeriod;
}
else if (name.equals("subject")) {
this.subject = new Reference();
return this.subject;
}
else if (name.equals("owner")) {
this.owner = new Reference();
return this.owner;
}
else if (name.equals("description")) {
throw new FHIRException("Cannot call addChild on a primitive type Account.description");
}
else
return super.addChild(name);
}
public String fhirType() {
return "Account";
}
public Account copy() {
Account dst = new Account();
copyValues(dst);
if (identifier != null) {
dst.identifier = new ArrayList<Identifier>();
for (Identifier i : identifier)
dst.identifier.add(i.copy());
};
dst.name = name == null ? null : name.copy();
dst.type = type == null ? null : type.copy();
dst.status = status == null ? null : status.copy();
dst.activePeriod = activePeriod == null ? null : activePeriod.copy();
dst.currency = currency == null ? null : currency.copy();
dst.balance = balance == null ? null : balance.copy();
dst.coveragePeriod = coveragePeriod == null ? null : coveragePeriod.copy();
dst.subject = subject == null ? null : subject.copy();
dst.owner = owner == null ? null : owner.copy();
dst.description = description == null ? null : description.copy();
return dst;
}
protected Account typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof Account))
return false;
Account o = (Account) other;
return compareDeep(identifier, o.identifier, true) && compareDeep(name, o.name, true) && compareDeep(type, o.type, true)
&& compareDeep(status, o.status, true) && compareDeep(activePeriod, o.activePeriod, true) && compareDeep(currency, o.currency, true)
&& compareDeep(balance, o.balance, true) && compareDeep(coveragePeriod, o.coveragePeriod, true)
&& compareDeep(subject, o.subject, true) && compareDeep(owner, o.owner, true) && compareDeep(description, o.description, true)
;
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof Account))
return false;
Account o = (Account) other;
return compareValues(name, o.name, true) && compareValues(status, o.status, true) && compareValues(description, o.description, true)
;
}
public boolean isEmpty() {
return super.isEmpty() && (identifier == null || identifier.isEmpty()) && (name == null || name.isEmpty())
&& (type == null || type.isEmpty()) && (status == null || status.isEmpty()) && (activePeriod == null || activePeriod.isEmpty())
&& (currency == null || currency.isEmpty()) && (balance == null || balance.isEmpty()) && (coveragePeriod == null || coveragePeriod.isEmpty())
&& (subject == null || subject.isEmpty()) && (owner == null || owner.isEmpty()) && (description == null || description.isEmpty())
;
}
@Override
public ResourceType getResourceType() {
return ResourceType.Account;
}
@SearchParamDefinition(name="owner", path="Account.owner", description="Who is responsible?", type="reference" )
public static final String SP_OWNER = "owner";
@SearchParamDefinition(name="identifier", path="Account.identifier", description="Account number", type="token" )
public static final String SP_IDENTIFIER = "identifier";
@SearchParamDefinition(name="period", path="Account.coveragePeriod", description="Transaction window", type="date" )
public static final String SP_PERIOD = "period";
@SearchParamDefinition(name="balance", path="Account.balance", description="How much is in account?", type="quantity" )
public static final String SP_BALANCE = "balance";
@SearchParamDefinition(name="subject", path="Account.subject", description="What is account tied to?", type="reference" )
public static final String SP_SUBJECT = "subject";
@SearchParamDefinition(name="patient", path="Account.subject", description="What is account tied to?", type="reference" )
public static final String SP_PATIENT = "patient";
@SearchParamDefinition(name="name", path="Account.name", description="Human-readable label", type="string" )
public static final String SP_NAME = "name";
@SearchParamDefinition(name="type", path="Account.type", description="E.g. patient, expense, depreciation", type="token" )
public static final String SP_TYPE = "type";
@SearchParamDefinition(name="status", path="Account.status", description="active | inactive", type="token" )
public static final String SP_STATUS = "status";
}

View File

@ -0,0 +1,975 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Wed, Jul 13, 2016 05:32+1000 for FHIR v1.0.2
import java.util.ArrayList;
import java.util.List;
import org.hl7.fhir.dstu2.model.annotations.Child;
import org.hl7.fhir.dstu2.model.annotations.DatatypeDef;
import org.hl7.fhir.dstu2.model.annotations.Description;
import org.hl7.fhir.dstu2.model.api.ICompositeType;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.utilities.Utilities;
/**
* There is a variety of postal address formats defined around the world. This format defines a superset that is the basis for all addresses around the world.
*/
@DatatypeDef(name="Address")
public class Address extends Type implements ICompositeType {
public enum AddressUse {
/**
* A communication address at a home.
*/
HOME,
/**
* An office address. First choice for business related contacts during business hours.
*/
WORK,
/**
* A temporary address. The period can provide more detailed information.
*/
TEMP,
/**
* This address is no longer in use (or was never correct, but retained for records).
*/
OLD,
/**
* added to help the parsers
*/
NULL;
public static AddressUse fromCode(String codeString) throws FHIRException {
if (codeString == null || "".equals(codeString))
return null;
if ("home".equals(codeString))
return HOME;
if ("work".equals(codeString))
return WORK;
if ("temp".equals(codeString))
return TEMP;
if ("old".equals(codeString))
return OLD;
throw new FHIRException("Unknown AddressUse code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case HOME: return "home";
case WORK: return "work";
case TEMP: return "temp";
case OLD: return "old";
default: return "?";
}
}
public String getSystem() {
switch (this) {
case HOME: return "http://hl7.org/fhir/address-use";
case WORK: return "http://hl7.org/fhir/address-use";
case TEMP: return "http://hl7.org/fhir/address-use";
case OLD: return "http://hl7.org/fhir/address-use";
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case HOME: return "A communication address at a home.";
case WORK: return "An office address. First choice for business related contacts during business hours.";
case TEMP: return "A temporary address. The period can provide more detailed information.";
case OLD: return "This address is no longer in use (or was never correct, but retained for records).";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case HOME: return "Home";
case WORK: return "Work";
case TEMP: return "Temporary";
case OLD: return "Old / Incorrect";
default: return "?";
}
}
}
public static class AddressUseEnumFactory implements EnumFactory<AddressUse> {
public AddressUse fromCode(String codeString) throws IllegalArgumentException {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("home".equals(codeString))
return AddressUse.HOME;
if ("work".equals(codeString))
return AddressUse.WORK;
if ("temp".equals(codeString))
return AddressUse.TEMP;
if ("old".equals(codeString))
return AddressUse.OLD;
throw new IllegalArgumentException("Unknown AddressUse code '"+codeString+"'");
}
public Enumeration<AddressUse> fromType(Base code) throws FHIRException {
if (code == null || code.isEmpty())
return null;
String codeString = ((PrimitiveType) code).asStringValue();
if (codeString == null || "".equals(codeString))
return null;
if ("home".equals(codeString))
return new Enumeration<AddressUse>(this, AddressUse.HOME);
if ("work".equals(codeString))
return new Enumeration<AddressUse>(this, AddressUse.WORK);
if ("temp".equals(codeString))
return new Enumeration<AddressUse>(this, AddressUse.TEMP);
if ("old".equals(codeString))
return new Enumeration<AddressUse>(this, AddressUse.OLD);
throw new FHIRException("Unknown AddressUse code '"+codeString+"'");
}
public String toCode(AddressUse code) {
if (code == AddressUse.HOME)
return "home";
if (code == AddressUse.WORK)
return "work";
if (code == AddressUse.TEMP)
return "temp";
if (code == AddressUse.OLD)
return "old";
return "?";
}
}
public enum AddressType {
/**
* Mailing addresses - PO Boxes and care-of addresses.
*/
POSTAL,
/**
* A physical address that can be visited.
*/
PHYSICAL,
/**
* An address that is both physical and postal.
*/
BOTH,
/**
* added to help the parsers
*/
NULL;
public static AddressType fromCode(String codeString) throws FHIRException {
if (codeString == null || "".equals(codeString))
return null;
if ("postal".equals(codeString))
return POSTAL;
if ("physical".equals(codeString))
return PHYSICAL;
if ("both".equals(codeString))
return BOTH;
throw new FHIRException("Unknown AddressType code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case POSTAL: return "postal";
case PHYSICAL: return "physical";
case BOTH: return "both";
default: return "?";
}
}
public String getSystem() {
switch (this) {
case POSTAL: return "http://hl7.org/fhir/address-type";
case PHYSICAL: return "http://hl7.org/fhir/address-type";
case BOTH: return "http://hl7.org/fhir/address-type";
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case POSTAL: return "Mailing addresses - PO Boxes and care-of addresses.";
case PHYSICAL: return "A physical address that can be visited.";
case BOTH: return "An address that is both physical and postal.";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case POSTAL: return "Postal";
case PHYSICAL: return "Physical";
case BOTH: return "Postal & Physical";
default: return "?";
}
}
}
public static class AddressTypeEnumFactory implements EnumFactory<AddressType> {
public AddressType fromCode(String codeString) throws IllegalArgumentException {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("postal".equals(codeString))
return AddressType.POSTAL;
if ("physical".equals(codeString))
return AddressType.PHYSICAL;
if ("both".equals(codeString))
return AddressType.BOTH;
throw new IllegalArgumentException("Unknown AddressType code '"+codeString+"'");
}
public Enumeration<AddressType> fromType(Base code) throws FHIRException {
if (code == null || code.isEmpty())
return null;
String codeString = ((PrimitiveType) code).asStringValue();
if (codeString == null || "".equals(codeString))
return null;
if ("postal".equals(codeString))
return new Enumeration<AddressType>(this, AddressType.POSTAL);
if ("physical".equals(codeString))
return new Enumeration<AddressType>(this, AddressType.PHYSICAL);
if ("both".equals(codeString))
return new Enumeration<AddressType>(this, AddressType.BOTH);
throw new FHIRException("Unknown AddressType code '"+codeString+"'");
}
public String toCode(AddressType code) {
if (code == AddressType.POSTAL)
return "postal";
if (code == AddressType.PHYSICAL)
return "physical";
if (code == AddressType.BOTH)
return "both";
return "?";
}
}
/**
* The purpose of this address.
*/
@Child(name = "use", type = {CodeType.class}, order=0, min=0, max=1, modifier=true, summary=true)
@Description(shortDefinition="home | work | temp | old - purpose of this address", formalDefinition="The purpose of this address." )
protected Enumeration<AddressUse> use;
/**
* Distinguishes between physical addresses (those you can visit) and mailing addresses (e.g. PO Boxes and care-of addresses). Most addresses are both.
*/
@Child(name = "type", type = {CodeType.class}, order=1, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="postal | physical | both", formalDefinition="Distinguishes between physical addresses (those you can visit) and mailing addresses (e.g. PO Boxes and care-of addresses). Most addresses are both." )
protected Enumeration<AddressType> type;
/**
* A full text representation of the address.
*/
@Child(name = "text", type = {StringType.class}, order=2, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Text representation of the address", formalDefinition="A full text representation of the address." )
protected StringType text;
/**
* This component contains the house number, apartment number, street name, street direction, P.O. Box number, delivery hints, and similar address information.
*/
@Child(name = "line", type = {StringType.class}, order=3, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Street name, number, direction & P.O. Box etc.", formalDefinition="This component contains the house number, apartment number, street name, street direction, P.O. Box number, delivery hints, and similar address information." )
protected List<StringType> line;
/**
* The name of the city, town, village or other community or delivery center.
*/
@Child(name = "city", type = {StringType.class}, order=4, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Name of city, town etc.", formalDefinition="The name of the city, town, village or other community or delivery center." )
protected StringType city;
/**
* The name of the administrative area (county).
*/
@Child(name = "district", type = {StringType.class}, order=5, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="District name (aka county)", formalDefinition="The name of the administrative area (county)." )
protected StringType district;
/**
* Sub-unit of a country with limited sovereignty in a federally organized country. A code may be used if codes are in common use (i.e. US 2 letter state codes).
*/
@Child(name = "state", type = {StringType.class}, order=6, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Sub-unit of country (abbreviations ok)", formalDefinition="Sub-unit of a country with limited sovereignty in a federally organized country. A code may be used if codes are in common use (i.e. US 2 letter state codes)." )
protected StringType state;
/**
* A postal code designating a region defined by the postal service.
*/
@Child(name = "postalCode", type = {StringType.class}, order=7, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Postal code for area", formalDefinition="A postal code designating a region defined by the postal service." )
protected StringType postalCode;
/**
* Country - a nation as commonly understood or generally accepted.
*/
@Child(name = "country", type = {StringType.class}, order=8, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Country (can be ISO 3166 3 letter code)", formalDefinition="Country - a nation as commonly understood or generally accepted." )
protected StringType country;
/**
* Time period when address was/is in use.
*/
@Child(name = "period", type = {Period.class}, order=9, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Time period when address was/is in use", formalDefinition="Time period when address was/is in use." )
protected Period period;
private static final long serialVersionUID = 561490318L;
/*
* Constructor
*/
public Address() {
super();
}
/**
* @return {@link #use} (The purpose of this address.). This is the underlying object with id, value and extensions. The accessor "getUse" gives direct access to the value
*/
public Enumeration<AddressUse> getUseElement() {
if (this.use == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.use");
else if (Configuration.doAutoCreate())
this.use = new Enumeration<AddressUse>(new AddressUseEnumFactory()); // bb
return this.use;
}
public boolean hasUseElement() {
return this.use != null && !this.use.isEmpty();
}
public boolean hasUse() {
return this.use != null && !this.use.isEmpty();
}
/**
* @param value {@link #use} (The purpose of this address.). This is the underlying object with id, value and extensions. The accessor "getUse" gives direct access to the value
*/
public Address setUseElement(Enumeration<AddressUse> value) {
this.use = value;
return this;
}
/**
* @return The purpose of this address.
*/
public AddressUse getUse() {
return this.use == null ? null : this.use.getValue();
}
/**
* @param value The purpose of this address.
*/
public Address setUse(AddressUse value) {
if (value == null)
this.use = null;
else {
if (this.use == null)
this.use = new Enumeration<AddressUse>(new AddressUseEnumFactory());
this.use.setValue(value);
}
return this;
}
/**
* @return {@link #type} (Distinguishes between physical addresses (those you can visit) and mailing addresses (e.g. PO Boxes and care-of addresses). Most addresses are both.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value
*/
public Enumeration<AddressType> getTypeElement() {
if (this.type == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.type");
else if (Configuration.doAutoCreate())
this.type = new Enumeration<AddressType>(new AddressTypeEnumFactory()); // bb
return this.type;
}
public boolean hasTypeElement() {
return this.type != null && !this.type.isEmpty();
}
public boolean hasType() {
return this.type != null && !this.type.isEmpty();
}
/**
* @param value {@link #type} (Distinguishes between physical addresses (those you can visit) and mailing addresses (e.g. PO Boxes and care-of addresses). Most addresses are both.). This is the underlying object with id, value and extensions. The accessor "getType" gives direct access to the value
*/
public Address setTypeElement(Enumeration<AddressType> value) {
this.type = value;
return this;
}
/**
* @return Distinguishes between physical addresses (those you can visit) and mailing addresses (e.g. PO Boxes and care-of addresses). Most addresses are both.
*/
public AddressType getType() {
return this.type == null ? null : this.type.getValue();
}
/**
* @param value Distinguishes between physical addresses (those you can visit) and mailing addresses (e.g. PO Boxes and care-of addresses). Most addresses are both.
*/
public Address setType(AddressType value) {
if (value == null)
this.type = null;
else {
if (this.type == null)
this.type = new Enumeration<AddressType>(new AddressTypeEnumFactory());
this.type.setValue(value);
}
return this;
}
/**
* @return {@link #text} (A full text representation of the address.). This is the underlying object with id, value and extensions. The accessor "getText" gives direct access to the value
*/
public StringType getTextElement() {
if (this.text == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.text");
else if (Configuration.doAutoCreate())
this.text = new StringType(); // bb
return this.text;
}
public boolean hasTextElement() {
return this.text != null && !this.text.isEmpty();
}
public boolean hasText() {
return this.text != null && !this.text.isEmpty();
}
/**
* @param value {@link #text} (A full text representation of the address.). This is the underlying object with id, value and extensions. The accessor "getText" gives direct access to the value
*/
public Address setTextElement(StringType value) {
this.text = value;
return this;
}
/**
* @return A full text representation of the address.
*/
public String getText() {
return this.text == null ? null : this.text.getValue();
}
/**
* @param value A full text representation of the address.
*/
public Address setText(String value) {
if (Utilities.noString(value))
this.text = null;
else {
if (this.text == null)
this.text = new StringType();
this.text.setValue(value);
}
return this;
}
/**
* @return {@link #line} (This component contains the house number, apartment number, street name, street direction, P.O. Box number, delivery hints, and similar address information.)
*/
public List<StringType> getLine() {
if (this.line == null)
this.line = new ArrayList<StringType>();
return this.line;
}
public boolean hasLine() {
if (this.line == null)
return false;
for (StringType item : this.line)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #line} (This component contains the house number, apartment number, street name, street direction, P.O. Box number, delivery hints, and similar address information.)
*/
// syntactic sugar
public StringType addLineElement() {//2
StringType t = new StringType();
if (this.line == null)
this.line = new ArrayList<StringType>();
this.line.add(t);
return t;
}
/**
* @param value {@link #line} (This component contains the house number, apartment number, street name, street direction, P.O. Box number, delivery hints, and similar address information.)
*/
public Address addLine(String value) { //1
StringType t = new StringType();
t.setValue(value);
if (this.line == null)
this.line = new ArrayList<StringType>();
this.line.add(t);
return this;
}
/**
* @param value {@link #line} (This component contains the house number, apartment number, street name, street direction, P.O. Box number, delivery hints, and similar address information.)
*/
public boolean hasLine(String value) {
if (this.line == null)
return false;
for (StringType v : this.line)
if (v.equals(value)) // string
return true;
return false;
}
/**
* @return {@link #city} (The name of the city, town, village or other community or delivery center.). This is the underlying object with id, value and extensions. The accessor "getCity" gives direct access to the value
*/
public StringType getCityElement() {
if (this.city == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.city");
else if (Configuration.doAutoCreate())
this.city = new StringType(); // bb
return this.city;
}
public boolean hasCityElement() {
return this.city != null && !this.city.isEmpty();
}
public boolean hasCity() {
return this.city != null && !this.city.isEmpty();
}
/**
* @param value {@link #city} (The name of the city, town, village or other community or delivery center.). This is the underlying object with id, value and extensions. The accessor "getCity" gives direct access to the value
*/
public Address setCityElement(StringType value) {
this.city = value;
return this;
}
/**
* @return The name of the city, town, village or other community or delivery center.
*/
public String getCity() {
return this.city == null ? null : this.city.getValue();
}
/**
* @param value The name of the city, town, village or other community or delivery center.
*/
public Address setCity(String value) {
if (Utilities.noString(value))
this.city = null;
else {
if (this.city == null)
this.city = new StringType();
this.city.setValue(value);
}
return this;
}
/**
* @return {@link #district} (The name of the administrative area (county).). This is the underlying object with id, value and extensions. The accessor "getDistrict" gives direct access to the value
*/
public StringType getDistrictElement() {
if (this.district == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.district");
else if (Configuration.doAutoCreate())
this.district = new StringType(); // bb
return this.district;
}
public boolean hasDistrictElement() {
return this.district != null && !this.district.isEmpty();
}
public boolean hasDistrict() {
return this.district != null && !this.district.isEmpty();
}
/**
* @param value {@link #district} (The name of the administrative area (county).). This is the underlying object with id, value and extensions. The accessor "getDistrict" gives direct access to the value
*/
public Address setDistrictElement(StringType value) {
this.district = value;
return this;
}
/**
* @return The name of the administrative area (county).
*/
public String getDistrict() {
return this.district == null ? null : this.district.getValue();
}
/**
* @param value The name of the administrative area (county).
*/
public Address setDistrict(String value) {
if (Utilities.noString(value))
this.district = null;
else {
if (this.district == null)
this.district = new StringType();
this.district.setValue(value);
}
return this;
}
/**
* @return {@link #state} (Sub-unit of a country with limited sovereignty in a federally organized country. A code may be used if codes are in common use (i.e. US 2 letter state codes).). This is the underlying object with id, value and extensions. The accessor "getState" gives direct access to the value
*/
public StringType getStateElement() {
if (this.state == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.state");
else if (Configuration.doAutoCreate())
this.state = new StringType(); // bb
return this.state;
}
public boolean hasStateElement() {
return this.state != null && !this.state.isEmpty();
}
public boolean hasState() {
return this.state != null && !this.state.isEmpty();
}
/**
* @param value {@link #state} (Sub-unit of a country with limited sovereignty in a federally organized country. A code may be used if codes are in common use (i.e. US 2 letter state codes).). This is the underlying object with id, value and extensions. The accessor "getState" gives direct access to the value
*/
public Address setStateElement(StringType value) {
this.state = value;
return this;
}
/**
* @return Sub-unit of a country with limited sovereignty in a federally organized country. A code may be used if codes are in common use (i.e. US 2 letter state codes).
*/
public String getState() {
return this.state == null ? null : this.state.getValue();
}
/**
* @param value Sub-unit of a country with limited sovereignty in a federally organized country. A code may be used if codes are in common use (i.e. US 2 letter state codes).
*/
public Address setState(String value) {
if (Utilities.noString(value))
this.state = null;
else {
if (this.state == null)
this.state = new StringType();
this.state.setValue(value);
}
return this;
}
/**
* @return {@link #postalCode} (A postal code designating a region defined by the postal service.). This is the underlying object with id, value and extensions. The accessor "getPostalCode" gives direct access to the value
*/
public StringType getPostalCodeElement() {
if (this.postalCode == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.postalCode");
else if (Configuration.doAutoCreate())
this.postalCode = new StringType(); // bb
return this.postalCode;
}
public boolean hasPostalCodeElement() {
return this.postalCode != null && !this.postalCode.isEmpty();
}
public boolean hasPostalCode() {
return this.postalCode != null && !this.postalCode.isEmpty();
}
/**
* @param value {@link #postalCode} (A postal code designating a region defined by the postal service.). This is the underlying object with id, value and extensions. The accessor "getPostalCode" gives direct access to the value
*/
public Address setPostalCodeElement(StringType value) {
this.postalCode = value;
return this;
}
/**
* @return A postal code designating a region defined by the postal service.
*/
public String getPostalCode() {
return this.postalCode == null ? null : this.postalCode.getValue();
}
/**
* @param value A postal code designating a region defined by the postal service.
*/
public Address setPostalCode(String value) {
if (Utilities.noString(value))
this.postalCode = null;
else {
if (this.postalCode == null)
this.postalCode = new StringType();
this.postalCode.setValue(value);
}
return this;
}
/**
* @return {@link #country} (Country - a nation as commonly understood or generally accepted.). This is the underlying object with id, value and extensions. The accessor "getCountry" gives direct access to the value
*/
public StringType getCountryElement() {
if (this.country == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.country");
else if (Configuration.doAutoCreate())
this.country = new StringType(); // bb
return this.country;
}
public boolean hasCountryElement() {
return this.country != null && !this.country.isEmpty();
}
public boolean hasCountry() {
return this.country != null && !this.country.isEmpty();
}
/**
* @param value {@link #country} (Country - a nation as commonly understood or generally accepted.). This is the underlying object with id, value and extensions. The accessor "getCountry" gives direct access to the value
*/
public Address setCountryElement(StringType value) {
this.country = value;
return this;
}
/**
* @return Country - a nation as commonly understood or generally accepted.
*/
public String getCountry() {
return this.country == null ? null : this.country.getValue();
}
/**
* @param value Country - a nation as commonly understood or generally accepted.
*/
public Address setCountry(String value) {
if (Utilities.noString(value))
this.country = null;
else {
if (this.country == null)
this.country = new StringType();
this.country.setValue(value);
}
return this;
}
/**
* @return {@link #period} (Time period when address was/is in use.)
*/
public Period getPeriod() {
if (this.period == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Address.period");
else if (Configuration.doAutoCreate())
this.period = new Period(); // cc
return this.period;
}
public boolean hasPeriod() {
return this.period != null && !this.period.isEmpty();
}
/**
* @param value {@link #period} (Time period when address was/is in use.)
*/
public Address setPeriod(Period value) {
this.period = value;
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("use", "code", "The purpose of this address.", 0, java.lang.Integer.MAX_VALUE, use));
childrenList.add(new Property("type", "code", "Distinguishes between physical addresses (those you can visit) and mailing addresses (e.g. PO Boxes and care-of addresses). Most addresses are both.", 0, java.lang.Integer.MAX_VALUE, type));
childrenList.add(new Property("text", "string", "A full text representation of the address.", 0, java.lang.Integer.MAX_VALUE, text));
childrenList.add(new Property("line", "string", "This component contains the house number, apartment number, street name, street direction, P.O. Box number, delivery hints, and similar address information.", 0, java.lang.Integer.MAX_VALUE, line));
childrenList.add(new Property("city", "string", "The name of the city, town, village or other community or delivery center.", 0, java.lang.Integer.MAX_VALUE, city));
childrenList.add(new Property("district", "string", "The name of the administrative area (county).", 0, java.lang.Integer.MAX_VALUE, district));
childrenList.add(new Property("state", "string", "Sub-unit of a country with limited sovereignty in a federally organized country. A code may be used if codes are in common use (i.e. US 2 letter state codes).", 0, java.lang.Integer.MAX_VALUE, state));
childrenList.add(new Property("postalCode", "string", "A postal code designating a region defined by the postal service.", 0, java.lang.Integer.MAX_VALUE, postalCode));
childrenList.add(new Property("country", "string", "Country - a nation as commonly understood or generally accepted.", 0, java.lang.Integer.MAX_VALUE, country));
childrenList.add(new Property("period", "Period", "Time period when address was/is in use.", 0, java.lang.Integer.MAX_VALUE, period));
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("use"))
this.use = new AddressUseEnumFactory().fromType(value); // Enumeration<AddressUse>
else if (name.equals("type"))
this.type = new AddressTypeEnumFactory().fromType(value); // Enumeration<AddressType>
else if (name.equals("text"))
this.text = castToString(value); // StringType
else if (name.equals("line"))
this.getLine().add(castToString(value));
else if (name.equals("city"))
this.city = castToString(value); // StringType
else if (name.equals("district"))
this.district = castToString(value); // StringType
else if (name.equals("state"))
this.state = castToString(value); // StringType
else if (name.equals("postalCode"))
this.postalCode = castToString(value); // StringType
else if (name.equals("country"))
this.country = castToString(value); // StringType
else if (name.equals("period"))
this.period = castToPeriod(value); // Period
else
super.setProperty(name, value);
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("use")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.use");
}
else if (name.equals("type")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.type");
}
else if (name.equals("text")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.text");
}
else if (name.equals("line")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.line");
}
else if (name.equals("city")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.city");
}
else if (name.equals("district")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.district");
}
else if (name.equals("state")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.state");
}
else if (name.equals("postalCode")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.postalCode");
}
else if (name.equals("country")) {
throw new FHIRException("Cannot call addChild on a primitive type Address.country");
}
else if (name.equals("period")) {
this.period = new Period();
return this.period;
}
else
return super.addChild(name);
}
public String fhirType() {
return "Address";
}
public Address copy() {
Address dst = new Address();
copyValues(dst);
dst.use = use == null ? null : use.copy();
dst.type = type == null ? null : type.copy();
dst.text = text == null ? null : text.copy();
if (line != null) {
dst.line = new ArrayList<StringType>();
for (StringType i : line)
dst.line.add(i.copy());
};
dst.city = city == null ? null : city.copy();
dst.district = district == null ? null : district.copy();
dst.state = state == null ? null : state.copy();
dst.postalCode = postalCode == null ? null : postalCode.copy();
dst.country = country == null ? null : country.copy();
dst.period = period == null ? null : period.copy();
return dst;
}
protected Address typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof Address))
return false;
Address o = (Address) other;
return compareDeep(use, o.use, true) && compareDeep(type, o.type, true) && compareDeep(text, o.text, true)
&& compareDeep(line, o.line, true) && compareDeep(city, o.city, true) && compareDeep(district, o.district, true)
&& compareDeep(state, o.state, true) && compareDeep(postalCode, o.postalCode, true) && compareDeep(country, o.country, true)
&& compareDeep(period, o.period, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof Address))
return false;
Address o = (Address) other;
return compareValues(use, o.use, true) && compareValues(type, o.type, true) && compareValues(text, o.text, true)
&& compareValues(line, o.line, true) && compareValues(city, o.city, true) && compareValues(district, o.district, true)
&& compareValues(state, o.state, true) && compareValues(postalCode, o.postalCode, true) && compareValues(country, o.country, true)
;
}
public boolean isEmpty() {
return super.isEmpty() && (use == null || use.isEmpty()) && (type == null || type.isEmpty())
&& (text == null || text.isEmpty()) && (line == null || line.isEmpty()) && (city == null || city.isEmpty())
&& (district == null || district.isEmpty()) && (state == null || state.isEmpty()) && (postalCode == null || postalCode.isEmpty())
&& (country == null || country.isEmpty()) && (period == null || period.isEmpty());
}
}

View File

@ -0,0 +1,109 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Wed, Jul 13, 2016 05:32+1000 for FHIR v1.0.2
import org.hl7.fhir.dstu2.model.annotations.DatatypeDef;
/**
* A measured amount (or an amount that can potentially be measured). Note that measured amounts include amounts that are not precisely quantified, including amounts involving arbitrary units and floating currencies.
*/
@DatatypeDef(name="Age", profileOf=Quantity.class)
public class Age extends Quantity {
private static final long serialVersionUID = 1069574054L;
public Age copy() {
Age dst = new Age();
copyValues(dst);
dst.value = value == null ? null : value.copy();
dst.comparator = comparator == null ? null : comparator.copy();
dst.unit = unit == null ? null : unit.copy();
dst.system = system == null ? null : system.copy();
dst.code = code == null ? null : code.copy();
return dst;
}
protected Age typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof Age))
return false;
Age o = (Age) other;
return compareDeep(value, o.value, true) && compareDeep(comparator, o.comparator, true) && compareDeep(unit, o.unit, true)
&& compareDeep(system, o.system, true) && compareDeep(code, o.code, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof Age))
return false;
Age o = (Age) other;
return compareValues(value, o.value, true) && compareValues(comparator, o.comparator, true) && compareValues(unit, o.unit, true)
&& compareValues(system, o.system, true) && compareValues(code, o.code, true);
}
public boolean isEmpty() {
return super.isEmpty() && (value == null || value.isEmpty()) && (comparator == null || comparator.isEmpty())
&& (unit == null || unit.isEmpty()) && (system == null || system.isEmpty()) && (code == null || code.isEmpty())
;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,330 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Wed, Jul 13, 2016 05:32+1000 for FHIR v1.0.2
import java.util.Date;
import java.util.List;
import org.hl7.fhir.dstu2.model.annotations.Child;
import org.hl7.fhir.dstu2.model.annotations.DatatypeDef;
import org.hl7.fhir.dstu2.model.annotations.Description;
import org.hl7.fhir.dstu2.model.api.ICompositeType;
import org.hl7.fhir.exceptions.FHIRException;
/**
* A text note which also contains information about who made the statement and when.
*/
@DatatypeDef(name="Annotation")
public class Annotation extends Type implements ICompositeType {
/**
* The individual responsible for making the annotation.
*/
@Child(name = "author", type = {Practitioner.class, Patient.class, RelatedPerson.class, StringType.class}, order=0, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Individual responsible for the annotation", formalDefinition="The individual responsible for making the annotation." )
protected Type author;
/**
* Indicates when this particular annotation was made.
*/
@Child(name = "time", type = {DateTimeType.class}, order=1, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="When the annotation was made", formalDefinition="Indicates when this particular annotation was made." )
protected DateTimeType time;
/**
* The text of the annotation.
*/
@Child(name = "text", type = {StringType.class}, order=2, min=1, max=1, modifier=false, summary=true)
@Description(shortDefinition="The annotation - text content", formalDefinition="The text of the annotation." )
protected StringType text;
private static final long serialVersionUID = -575590381L;
/*
* Constructor
*/
public Annotation() {
super();
}
/*
* Constructor
*/
public Annotation(StringType text) {
super();
this.text = text;
}
/**
* @return {@link #author} (The individual responsible for making the annotation.)
*/
public Type getAuthor() {
return this.author;
}
/**
* @return {@link #author} (The individual responsible for making the annotation.)
*/
public Reference getAuthorReference() throws FHIRException {
if (!(this.author instanceof Reference))
throw new FHIRException("Type mismatch: the type Reference was expected, but "+this.author.getClass().getName()+" was encountered");
return (Reference) this.author;
}
public boolean hasAuthorReference() {
return this.author instanceof Reference;
}
/**
* @return {@link #author} (The individual responsible for making the annotation.)
*/
public StringType getAuthorStringType() throws FHIRException {
if (!(this.author instanceof StringType))
throw new FHIRException("Type mismatch: the type StringType was expected, but "+this.author.getClass().getName()+" was encountered");
return (StringType) this.author;
}
public boolean hasAuthorStringType() {
return this.author instanceof StringType;
}
public boolean hasAuthor() {
return this.author != null && !this.author.isEmpty();
}
/**
* @param value {@link #author} (The individual responsible for making the annotation.)
*/
public Annotation setAuthor(Type value) {
this.author = value;
return this;
}
/**
* @return {@link #time} (Indicates when this particular annotation was made.). This is the underlying object with id, value and extensions. The accessor "getTime" gives direct access to the value
*/
public DateTimeType getTimeElement() {
if (this.time == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Annotation.time");
else if (Configuration.doAutoCreate())
this.time = new DateTimeType(); // bb
return this.time;
}
public boolean hasTimeElement() {
return this.time != null && !this.time.isEmpty();
}
public boolean hasTime() {
return this.time != null && !this.time.isEmpty();
}
/**
* @param value {@link #time} (Indicates when this particular annotation was made.). This is the underlying object with id, value and extensions. The accessor "getTime" gives direct access to the value
*/
public Annotation setTimeElement(DateTimeType value) {
this.time = value;
return this;
}
/**
* @return Indicates when this particular annotation was made.
*/
public Date getTime() {
return this.time == null ? null : this.time.getValue();
}
/**
* @param value Indicates when this particular annotation was made.
*/
public Annotation setTime(Date value) {
if (value == null)
this.time = null;
else {
if (this.time == null)
this.time = new DateTimeType();
this.time.setValue(value);
}
return this;
}
/**
* @return {@link #text} (The text of the annotation.). This is the underlying object with id, value and extensions. The accessor "getText" gives direct access to the value
*/
public StringType getTextElement() {
if (this.text == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Annotation.text");
else if (Configuration.doAutoCreate())
this.text = new StringType(); // bb
return this.text;
}
public boolean hasTextElement() {
return this.text != null && !this.text.isEmpty();
}
public boolean hasText() {
return this.text != null && !this.text.isEmpty();
}
/**
* @param value {@link #text} (The text of the annotation.). This is the underlying object with id, value and extensions. The accessor "getText" gives direct access to the value
*/
public Annotation setTextElement(StringType value) {
this.text = value;
return this;
}
/**
* @return The text of the annotation.
*/
public String getText() {
return this.text == null ? null : this.text.getValue();
}
/**
* @param value The text of the annotation.
*/
public Annotation setText(String value) {
if (this.text == null)
this.text = new StringType();
this.text.setValue(value);
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("author[x]", "Reference(Practitioner|Patient|RelatedPerson)|string", "The individual responsible for making the annotation.", 0, java.lang.Integer.MAX_VALUE, author));
childrenList.add(new Property("time", "dateTime", "Indicates when this particular annotation was made.", 0, java.lang.Integer.MAX_VALUE, time));
childrenList.add(new Property("text", "string", "The text of the annotation.", 0, java.lang.Integer.MAX_VALUE, text));
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("author[x]"))
this.author = (Type) value; // Type
else if (name.equals("time"))
this.time = castToDateTime(value); // DateTimeType
else if (name.equals("text"))
this.text = castToString(value); // StringType
else
super.setProperty(name, value);
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("authorReference")) {
this.author = new Reference();
return this.author;
}
else if (name.equals("authorString")) {
this.author = new StringType();
return this.author;
}
else if (name.equals("time")) {
throw new FHIRException("Cannot call addChild on a primitive type Annotation.time");
}
else if (name.equals("text")) {
throw new FHIRException("Cannot call addChild on a primitive type Annotation.text");
}
else
return super.addChild(name);
}
public String fhirType() {
return "Annotation";
}
public Annotation copy() {
Annotation dst = new Annotation();
copyValues(dst);
dst.author = author == null ? null : author.copy();
dst.time = time == null ? null : time.copy();
dst.text = text == null ? null : text.copy();
return dst;
}
protected Annotation typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof Annotation))
return false;
Annotation o = (Annotation) other;
return compareDeep(author, o.author, true) && compareDeep(time, o.time, true) && compareDeep(text, o.text, true)
;
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof Annotation))
return false;
Annotation o = (Annotation) other;
return compareValues(time, o.time, true) && compareValues(text, o.text, true);
}
public boolean isEmpty() {
return super.isEmpty() && (author == null || author.isEmpty()) && (time == null || time.isEmpty())
&& (text == null || text.isEmpty());
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,806 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Wed, Jul 13, 2016 05:32+1000 for FHIR v1.0.2
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hl7.fhir.dstu2.model.annotations.Child;
import org.hl7.fhir.dstu2.model.annotations.Description;
import org.hl7.fhir.dstu2.model.annotations.ResourceDef;
import org.hl7.fhir.dstu2.model.annotations.SearchParamDefinition;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.utilities.Utilities;
/**
* A reply to an appointment request for a patient and/or practitioner(s), such as a confirmation or rejection.
*/
@ResourceDef(name="AppointmentResponse", profile="http://hl7.org/fhir/Profile/AppointmentResponse")
public class AppointmentResponse extends DomainResource {
public enum ParticipantStatus {
/**
* The appointment participant has accepted that they can attend the appointment at the time specified in the AppointmentResponse.
*/
ACCEPTED,
/**
* The appointment participant has declined the appointment.
*/
DECLINED,
/**
* The appointment participant has tentatively accepted the appointment.
*/
TENTATIVE,
/**
* The participant has in-process the appointment.
*/
INPROCESS,
/**
* The participant has completed the appointment.
*/
COMPLETED,
/**
* This is the intitial status of an appointment participant until a participant has replied. It implies that there is no commitment for the appointment.
*/
NEEDSACTION,
/**
* added to help the parsers
*/
NULL;
public static ParticipantStatus fromCode(String codeString) throws FHIRException {
if (codeString == null || "".equals(codeString))
return null;
if ("accepted".equals(codeString))
return ACCEPTED;
if ("declined".equals(codeString))
return DECLINED;
if ("tentative".equals(codeString))
return TENTATIVE;
if ("in-process".equals(codeString))
return INPROCESS;
if ("completed".equals(codeString))
return COMPLETED;
if ("needs-action".equals(codeString))
return NEEDSACTION;
throw new FHIRException("Unknown ParticipantStatus code '"+codeString+"'");
}
public String toCode() {
switch (this) {
case ACCEPTED: return "accepted";
case DECLINED: return "declined";
case TENTATIVE: return "tentative";
case INPROCESS: return "in-process";
case COMPLETED: return "completed";
case NEEDSACTION: return "needs-action";
default: return "?";
}
}
public String getSystem() {
switch (this) {
case ACCEPTED: return "http://hl7.org/fhir/participantstatus";
case DECLINED: return "http://hl7.org/fhir/participantstatus";
case TENTATIVE: return "http://hl7.org/fhir/participantstatus";
case INPROCESS: return "http://hl7.org/fhir/participantstatus";
case COMPLETED: return "http://hl7.org/fhir/participantstatus";
case NEEDSACTION: return "http://hl7.org/fhir/participantstatus";
default: return "?";
}
}
public String getDefinition() {
switch (this) {
case ACCEPTED: return "The appointment participant has accepted that they can attend the appointment at the time specified in the AppointmentResponse.";
case DECLINED: return "The appointment participant has declined the appointment.";
case TENTATIVE: return "The appointment participant has tentatively accepted the appointment.";
case INPROCESS: return "The participant has in-process the appointment.";
case COMPLETED: return "The participant has completed the appointment.";
case NEEDSACTION: return "This is the intitial status of an appointment participant until a participant has replied. It implies that there is no commitment for the appointment.";
default: return "?";
}
}
public String getDisplay() {
switch (this) {
case ACCEPTED: return "Accepted";
case DECLINED: return "Declined";
case TENTATIVE: return "Tentative";
case INPROCESS: return "In Process";
case COMPLETED: return "Completed";
case NEEDSACTION: return "Needs Action";
default: return "?";
}
}
}
public static class ParticipantStatusEnumFactory implements EnumFactory<ParticipantStatus> {
public ParticipantStatus fromCode(String codeString) throws IllegalArgumentException {
if (codeString == null || "".equals(codeString))
if (codeString == null || "".equals(codeString))
return null;
if ("accepted".equals(codeString))
return ParticipantStatus.ACCEPTED;
if ("declined".equals(codeString))
return ParticipantStatus.DECLINED;
if ("tentative".equals(codeString))
return ParticipantStatus.TENTATIVE;
if ("in-process".equals(codeString))
return ParticipantStatus.INPROCESS;
if ("completed".equals(codeString))
return ParticipantStatus.COMPLETED;
if ("needs-action".equals(codeString))
return ParticipantStatus.NEEDSACTION;
throw new IllegalArgumentException("Unknown ParticipantStatus code '"+codeString+"'");
}
public Enumeration<ParticipantStatus> fromType(Base code) throws FHIRException {
if (code == null || code.isEmpty())
return null;
String codeString = ((PrimitiveType) code).asStringValue();
if (codeString == null || "".equals(codeString))
return null;
if ("accepted".equals(codeString))
return new Enumeration<ParticipantStatus>(this, ParticipantStatus.ACCEPTED);
if ("declined".equals(codeString))
return new Enumeration<ParticipantStatus>(this, ParticipantStatus.DECLINED);
if ("tentative".equals(codeString))
return new Enumeration<ParticipantStatus>(this, ParticipantStatus.TENTATIVE);
if ("in-process".equals(codeString))
return new Enumeration<ParticipantStatus>(this, ParticipantStatus.INPROCESS);
if ("completed".equals(codeString))
return new Enumeration<ParticipantStatus>(this, ParticipantStatus.COMPLETED);
if ("needs-action".equals(codeString))
return new Enumeration<ParticipantStatus>(this, ParticipantStatus.NEEDSACTION);
throw new FHIRException("Unknown ParticipantStatus code '"+codeString+"'");
}
public String toCode(ParticipantStatus code) {
if (code == ParticipantStatus.ACCEPTED)
return "accepted";
if (code == ParticipantStatus.DECLINED)
return "declined";
if (code == ParticipantStatus.TENTATIVE)
return "tentative";
if (code == ParticipantStatus.INPROCESS)
return "in-process";
if (code == ParticipantStatus.COMPLETED)
return "completed";
if (code == ParticipantStatus.NEEDSACTION)
return "needs-action";
return "?";
}
}
/**
* This records identifiers associated with this appointment response concern that are defined by business processes and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate.
*/
@Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="External Ids for this item", formalDefinition="This records identifiers associated with this appointment response concern that are defined by business processes and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate." )
protected List<Identifier> identifier;
/**
* Appointment that this response is replying to.
*/
@Child(name = "appointment", type = {Appointment.class}, order=1, min=1, max=1, modifier=false, summary=true)
@Description(shortDefinition="Appointment this response relates to", formalDefinition="Appointment that this response is replying to." )
protected Reference appointment;
/**
* The actual object that is the target of the reference (Appointment that this response is replying to.)
*/
protected Appointment appointmentTarget;
/**
* Date/Time that the appointment is to take place, or requested new start time.
*/
@Child(name = "start", type = {InstantType.class}, order=2, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Time from appointment, or requested new start time", formalDefinition="Date/Time that the appointment is to take place, or requested new start time." )
protected InstantType start;
/**
* This may be either the same as the appointment request to confirm the details of the appointment, or alternately a new time to request a re-negotiation of the end time.
*/
@Child(name = "end", type = {InstantType.class}, order=3, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Time from appointment, or requested new end time", formalDefinition="This may be either the same as the appointment request to confirm the details of the appointment, or alternately a new time to request a re-negotiation of the end time." )
protected InstantType end;
/**
* Role of participant in the appointment.
*/
@Child(name = "participantType", type = {CodeableConcept.class}, order=4, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Role of participant in the appointment", formalDefinition="Role of participant in the appointment." )
protected List<CodeableConcept> participantType;
/**
* A Person, Location/HealthcareService or Device that is participating in the appointment.
*/
@Child(name = "actor", type = {Patient.class, Practitioner.class, RelatedPerson.class, Device.class, HealthcareService.class, Location.class}, order=5, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Person, Location/HealthcareService or Device", formalDefinition="A Person, Location/HealthcareService or Device that is participating in the appointment." )
protected Reference actor;
/**
* The actual object that is the target of the reference (A Person, Location/HealthcareService or Device that is participating in the appointment.)
*/
protected Resource actorTarget;
/**
* Participation status of the participant. When the status is declined or tentative if the start/end times are different to the appointment, then these times should be interpreted as a requested time change. When the status is accepted, the times can either be the time of the appointment (as a confirmation of the time) or can be empty.
*/
@Child(name = "participantStatus", type = {CodeType.class}, order=6, min=1, max=1, modifier=true, summary=true)
@Description(shortDefinition="accepted | declined | tentative | in-process | completed | needs-action", formalDefinition="Participation status of the participant. When the status is declined or tentative if the start/end times are different to the appointment, then these times should be interpreted as a requested time change. When the status is accepted, the times can either be the time of the appointment (as a confirmation of the time) or can be empty." )
protected Enumeration<ParticipantStatus> participantStatus;
/**
* Additional comments about the appointment.
*/
@Child(name = "comment", type = {StringType.class}, order=7, min=0, max=1, modifier=false, summary=false)
@Description(shortDefinition="Additional comments", formalDefinition="Additional comments about the appointment." )
protected StringType comment;
private static final long serialVersionUID = 248548635L;
/*
* Constructor
*/
public AppointmentResponse() {
super();
}
/*
* Constructor
*/
public AppointmentResponse(Reference appointment, Enumeration<ParticipantStatus> participantStatus) {
super();
this.appointment = appointment;
this.participantStatus = participantStatus;
}
/**
* @return {@link #identifier} (This records identifiers associated with this appointment response concern that are defined by business processes and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate.)
*/
public List<Identifier> getIdentifier() {
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
return this.identifier;
}
public boolean hasIdentifier() {
if (this.identifier == null)
return false;
for (Identifier item : this.identifier)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #identifier} (This records identifiers associated with this appointment response concern that are defined by business processes and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate.)
*/
// syntactic sugar
public Identifier addIdentifier() { //3
Identifier t = new Identifier();
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return t;
}
// syntactic sugar
public AppointmentResponse addIdentifier(Identifier t) { //3
if (t == null)
return this;
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return this;
}
/**
* @return {@link #appointment} (Appointment that this response is replying to.)
*/
public Reference getAppointment() {
if (this.appointment == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create AppointmentResponse.appointment");
else if (Configuration.doAutoCreate())
this.appointment = new Reference(); // cc
return this.appointment;
}
public boolean hasAppointment() {
return this.appointment != null && !this.appointment.isEmpty();
}
/**
* @param value {@link #appointment} (Appointment that this response is replying to.)
*/
public AppointmentResponse setAppointment(Reference value) {
this.appointment = value;
return this;
}
/**
* @return {@link #appointment} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Appointment that this response is replying to.)
*/
public Appointment getAppointmentTarget() {
if (this.appointmentTarget == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create AppointmentResponse.appointment");
else if (Configuration.doAutoCreate())
this.appointmentTarget = new Appointment(); // aa
return this.appointmentTarget;
}
/**
* @param value {@link #appointment} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Appointment that this response is replying to.)
*/
public AppointmentResponse setAppointmentTarget(Appointment value) {
this.appointmentTarget = value;
return this;
}
/**
* @return {@link #start} (Date/Time that the appointment is to take place, or requested new start time.). This is the underlying object with id, value and extensions. The accessor "getStart" gives direct access to the value
*/
public InstantType getStartElement() {
if (this.start == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create AppointmentResponse.start");
else if (Configuration.doAutoCreate())
this.start = new InstantType(); // bb
return this.start;
}
public boolean hasStartElement() {
return this.start != null && !this.start.isEmpty();
}
public boolean hasStart() {
return this.start != null && !this.start.isEmpty();
}
/**
* @param value {@link #start} (Date/Time that the appointment is to take place, or requested new start time.). This is the underlying object with id, value and extensions. The accessor "getStart" gives direct access to the value
*/
public AppointmentResponse setStartElement(InstantType value) {
this.start = value;
return this;
}
/**
* @return Date/Time that the appointment is to take place, or requested new start time.
*/
public Date getStart() {
return this.start == null ? null : this.start.getValue();
}
/**
* @param value Date/Time that the appointment is to take place, or requested new start time.
*/
public AppointmentResponse setStart(Date value) {
if (value == null)
this.start = null;
else {
if (this.start == null)
this.start = new InstantType();
this.start.setValue(value);
}
return this;
}
/**
* @return {@link #end} (This may be either the same as the appointment request to confirm the details of the appointment, or alternately a new time to request a re-negotiation of the end time.). This is the underlying object with id, value and extensions. The accessor "getEnd" gives direct access to the value
*/
public InstantType getEndElement() {
if (this.end == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create AppointmentResponse.end");
else if (Configuration.doAutoCreate())
this.end = new InstantType(); // bb
return this.end;
}
public boolean hasEndElement() {
return this.end != null && !this.end.isEmpty();
}
public boolean hasEnd() {
return this.end != null && !this.end.isEmpty();
}
/**
* @param value {@link #end} (This may be either the same as the appointment request to confirm the details of the appointment, or alternately a new time to request a re-negotiation of the end time.). This is the underlying object with id, value and extensions. The accessor "getEnd" gives direct access to the value
*/
public AppointmentResponse setEndElement(InstantType value) {
this.end = value;
return this;
}
/**
* @return This may be either the same as the appointment request to confirm the details of the appointment, or alternately a new time to request a re-negotiation of the end time.
*/
public Date getEnd() {
return this.end == null ? null : this.end.getValue();
}
/**
* @param value This may be either the same as the appointment request to confirm the details of the appointment, or alternately a new time to request a re-negotiation of the end time.
*/
public AppointmentResponse setEnd(Date value) {
if (value == null)
this.end = null;
else {
if (this.end == null)
this.end = new InstantType();
this.end.setValue(value);
}
return this;
}
/**
* @return {@link #participantType} (Role of participant in the appointment.)
*/
public List<CodeableConcept> getParticipantType() {
if (this.participantType == null)
this.participantType = new ArrayList<CodeableConcept>();
return this.participantType;
}
public boolean hasParticipantType() {
if (this.participantType == null)
return false;
for (CodeableConcept item : this.participantType)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #participantType} (Role of participant in the appointment.)
*/
// syntactic sugar
public CodeableConcept addParticipantType() { //3
CodeableConcept t = new CodeableConcept();
if (this.participantType == null)
this.participantType = new ArrayList<CodeableConcept>();
this.participantType.add(t);
return t;
}
// syntactic sugar
public AppointmentResponse addParticipantType(CodeableConcept t) { //3
if (t == null)
return this;
if (this.participantType == null)
this.participantType = new ArrayList<CodeableConcept>();
this.participantType.add(t);
return this;
}
/**
* @return {@link #actor} (A Person, Location/HealthcareService or Device that is participating in the appointment.)
*/
public Reference getActor() {
if (this.actor == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create AppointmentResponse.actor");
else if (Configuration.doAutoCreate())
this.actor = new Reference(); // cc
return this.actor;
}
public boolean hasActor() {
return this.actor != null && !this.actor.isEmpty();
}
/**
* @param value {@link #actor} (A Person, Location/HealthcareService or Device that is participating in the appointment.)
*/
public AppointmentResponse setActor(Reference value) {
this.actor = value;
return this;
}
/**
* @return {@link #actor} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (A Person, Location/HealthcareService or Device that is participating in the appointment.)
*/
public Resource getActorTarget() {
return this.actorTarget;
}
/**
* @param value {@link #actor} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (A Person, Location/HealthcareService or Device that is participating in the appointment.)
*/
public AppointmentResponse setActorTarget(Resource value) {
this.actorTarget = value;
return this;
}
/**
* @return {@link #participantStatus} (Participation status of the participant. When the status is declined or tentative if the start/end times are different to the appointment, then these times should be interpreted as a requested time change. When the status is accepted, the times can either be the time of the appointment (as a confirmation of the time) or can be empty.). This is the underlying object with id, value and extensions. The accessor "getParticipantStatus" gives direct access to the value
*/
public Enumeration<ParticipantStatus> getParticipantStatusElement() {
if (this.participantStatus == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create AppointmentResponse.participantStatus");
else if (Configuration.doAutoCreate())
this.participantStatus = new Enumeration<ParticipantStatus>(new ParticipantStatusEnumFactory()); // bb
return this.participantStatus;
}
public boolean hasParticipantStatusElement() {
return this.participantStatus != null && !this.participantStatus.isEmpty();
}
public boolean hasParticipantStatus() {
return this.participantStatus != null && !this.participantStatus.isEmpty();
}
/**
* @param value {@link #participantStatus} (Participation status of the participant. When the status is declined or tentative if the start/end times are different to the appointment, then these times should be interpreted as a requested time change. When the status is accepted, the times can either be the time of the appointment (as a confirmation of the time) or can be empty.). This is the underlying object with id, value and extensions. The accessor "getParticipantStatus" gives direct access to the value
*/
public AppointmentResponse setParticipantStatusElement(Enumeration<ParticipantStatus> value) {
this.participantStatus = value;
return this;
}
/**
* @return Participation status of the participant. When the status is declined or tentative if the start/end times are different to the appointment, then these times should be interpreted as a requested time change. When the status is accepted, the times can either be the time of the appointment (as a confirmation of the time) or can be empty.
*/
public ParticipantStatus getParticipantStatus() {
return this.participantStatus == null ? null : this.participantStatus.getValue();
}
/**
* @param value Participation status of the participant. When the status is declined or tentative if the start/end times are different to the appointment, then these times should be interpreted as a requested time change. When the status is accepted, the times can either be the time of the appointment (as a confirmation of the time) or can be empty.
*/
public AppointmentResponse setParticipantStatus(ParticipantStatus value) {
if (this.participantStatus == null)
this.participantStatus = new Enumeration<ParticipantStatus>(new ParticipantStatusEnumFactory());
this.participantStatus.setValue(value);
return this;
}
/**
* @return {@link #comment} (Additional comments about the appointment.). This is the underlying object with id, value and extensions. The accessor "getComment" gives direct access to the value
*/
public StringType getCommentElement() {
if (this.comment == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create AppointmentResponse.comment");
else if (Configuration.doAutoCreate())
this.comment = new StringType(); // bb
return this.comment;
}
public boolean hasCommentElement() {
return this.comment != null && !this.comment.isEmpty();
}
public boolean hasComment() {
return this.comment != null && !this.comment.isEmpty();
}
/**
* @param value {@link #comment} (Additional comments about the appointment.). This is the underlying object with id, value and extensions. The accessor "getComment" gives direct access to the value
*/
public AppointmentResponse setCommentElement(StringType value) {
this.comment = value;
return this;
}
/**
* @return Additional comments about the appointment.
*/
public String getComment() {
return this.comment == null ? null : this.comment.getValue();
}
/**
* @param value Additional comments about the appointment.
*/
public AppointmentResponse setComment(String value) {
if (Utilities.noString(value))
this.comment = null;
else {
if (this.comment == null)
this.comment = new StringType();
this.comment.setValue(value);
}
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("identifier", "Identifier", "This records identifiers associated with this appointment response concern that are defined by business processes and/ or used to refer to it when a direct URL reference to the resource itself is not appropriate.", 0, java.lang.Integer.MAX_VALUE, identifier));
childrenList.add(new Property("appointment", "Reference(Appointment)", "Appointment that this response is replying to.", 0, java.lang.Integer.MAX_VALUE, appointment));
childrenList.add(new Property("start", "instant", "Date/Time that the appointment is to take place, or requested new start time.", 0, java.lang.Integer.MAX_VALUE, start));
childrenList.add(new Property("end", "instant", "This may be either the same as the appointment request to confirm the details of the appointment, or alternately a new time to request a re-negotiation of the end time.", 0, java.lang.Integer.MAX_VALUE, end));
childrenList.add(new Property("participantType", "CodeableConcept", "Role of participant in the appointment.", 0, java.lang.Integer.MAX_VALUE, participantType));
childrenList.add(new Property("actor", "Reference(Patient|Practitioner|RelatedPerson|Device|HealthcareService|Location)", "A Person, Location/HealthcareService or Device that is participating in the appointment.", 0, java.lang.Integer.MAX_VALUE, actor));
childrenList.add(new Property("participantStatus", "code", "Participation status of the participant. When the status is declined or tentative if the start/end times are different to the appointment, then these times should be interpreted as a requested time change. When the status is accepted, the times can either be the time of the appointment (as a confirmation of the time) or can be empty.", 0, java.lang.Integer.MAX_VALUE, participantStatus));
childrenList.add(new Property("comment", "string", "Additional comments about the appointment.", 0, java.lang.Integer.MAX_VALUE, comment));
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("identifier"))
this.getIdentifier().add(castToIdentifier(value));
else if (name.equals("appointment"))
this.appointment = castToReference(value); // Reference
else if (name.equals("start"))
this.start = castToInstant(value); // InstantType
else if (name.equals("end"))
this.end = castToInstant(value); // InstantType
else if (name.equals("participantType"))
this.getParticipantType().add(castToCodeableConcept(value));
else if (name.equals("actor"))
this.actor = castToReference(value); // Reference
else if (name.equals("participantStatus"))
this.participantStatus = new ParticipantStatusEnumFactory().fromType(value); // Enumeration<ParticipantStatus>
else if (name.equals("comment"))
this.comment = castToString(value); // StringType
else
super.setProperty(name, value);
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("identifier")) {
return addIdentifier();
}
else if (name.equals("appointment")) {
this.appointment = new Reference();
return this.appointment;
}
else if (name.equals("start")) {
throw new FHIRException("Cannot call addChild on a primitive type AppointmentResponse.start");
}
else if (name.equals("end")) {
throw new FHIRException("Cannot call addChild on a primitive type AppointmentResponse.end");
}
else if (name.equals("participantType")) {
return addParticipantType();
}
else if (name.equals("actor")) {
this.actor = new Reference();
return this.actor;
}
else if (name.equals("participantStatus")) {
throw new FHIRException("Cannot call addChild on a primitive type AppointmentResponse.participantStatus");
}
else if (name.equals("comment")) {
throw new FHIRException("Cannot call addChild on a primitive type AppointmentResponse.comment");
}
else
return super.addChild(name);
}
public String fhirType() {
return "AppointmentResponse";
}
public AppointmentResponse copy() {
AppointmentResponse dst = new AppointmentResponse();
copyValues(dst);
if (identifier != null) {
dst.identifier = new ArrayList<Identifier>();
for (Identifier i : identifier)
dst.identifier.add(i.copy());
};
dst.appointment = appointment == null ? null : appointment.copy();
dst.start = start == null ? null : start.copy();
dst.end = end == null ? null : end.copy();
if (participantType != null) {
dst.participantType = new ArrayList<CodeableConcept>();
for (CodeableConcept i : participantType)
dst.participantType.add(i.copy());
};
dst.actor = actor == null ? null : actor.copy();
dst.participantStatus = participantStatus == null ? null : participantStatus.copy();
dst.comment = comment == null ? null : comment.copy();
return dst;
}
protected AppointmentResponse typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof AppointmentResponse))
return false;
AppointmentResponse o = (AppointmentResponse) other;
return compareDeep(identifier, o.identifier, true) && compareDeep(appointment, o.appointment, true)
&& compareDeep(start, o.start, true) && compareDeep(end, o.end, true) && compareDeep(participantType, o.participantType, true)
&& compareDeep(actor, o.actor, true) && compareDeep(participantStatus, o.participantStatus, true)
&& compareDeep(comment, o.comment, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof AppointmentResponse))
return false;
AppointmentResponse o = (AppointmentResponse) other;
return compareValues(start, o.start, true) && compareValues(end, o.end, true) && compareValues(participantStatus, o.participantStatus, true)
&& compareValues(comment, o.comment, true);
}
public boolean isEmpty() {
return super.isEmpty() && (identifier == null || identifier.isEmpty()) && (appointment == null || appointment.isEmpty())
&& (start == null || start.isEmpty()) && (end == null || end.isEmpty()) && (participantType == null || participantType.isEmpty())
&& (actor == null || actor.isEmpty()) && (participantStatus == null || participantStatus.isEmpty())
&& (comment == null || comment.isEmpty());
}
@Override
public ResourceType getResourceType() {
return ResourceType.AppointmentResponse;
}
@SearchParamDefinition(name="actor", path="AppointmentResponse.actor", description="The Person, Location/HealthcareService or Device that this appointment response replies for", type="reference" )
public static final String SP_ACTOR = "actor";
@SearchParamDefinition(name="identifier", path="AppointmentResponse.identifier", description="An Identifier in this appointment response", type="token" )
public static final String SP_IDENTIFIER = "identifier";
@SearchParamDefinition(name="practitioner", path="AppointmentResponse.actor", description="This Response is for this Practitioner", type="reference" )
public static final String SP_PRACTITIONER = "practitioner";
@SearchParamDefinition(name="part-status", path="AppointmentResponse.participantStatus", description="The participants acceptance status for this appointment", type="token" )
public static final String SP_PARTSTATUS = "part-status";
@SearchParamDefinition(name="patient", path="AppointmentResponse.actor", description="This Response is for this Patient", type="reference" )
public static final String SP_PATIENT = "patient";
@SearchParamDefinition(name="appointment", path="AppointmentResponse.appointment", description="The appointment that the response is attached to", type="reference" )
public static final String SP_APPOINTMENT = "appointment";
@SearchParamDefinition(name="location", path="AppointmentResponse.actor", description="This Response is for this Location", type="reference" )
public static final String SP_LOCATION = "location";
}

View File

@ -0,0 +1,644 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Wed, Jul 13, 2016 05:32+1000 for FHIR v1.0.2
import java.util.Date;
import java.util.List;
import org.hl7.fhir.dstu2.model.annotations.Child;
import org.hl7.fhir.dstu2.model.annotations.DatatypeDef;
import org.hl7.fhir.dstu2.model.annotations.Description;
import org.hl7.fhir.dstu2.model.api.ICompositeType;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.utilities.Utilities;
/**
* For referring to data content defined in other formats.
*/
@DatatypeDef(name="Attachment")
public class Attachment extends Type implements ICompositeType {
/**
* Identifies the type of the data in the attachment and allows a method to be chosen to interpret or render the data. Includes mime type parameters such as charset where appropriate.
*/
@Child(name = "contentType", type = {CodeType.class}, order=0, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Mime type of the content, with charset etc.", formalDefinition="Identifies the type of the data in the attachment and allows a method to be chosen to interpret or render the data. Includes mime type parameters such as charset where appropriate." )
protected CodeType contentType;
/**
* The human language of the content. The value can be any valid value according to BCP 47.
*/
@Child(name = "language", type = {CodeType.class}, order=1, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Human language of the content (BCP-47)", formalDefinition="The human language of the content. The value can be any valid value according to BCP 47." )
protected CodeType language;
/**
* The actual data of the attachment - a sequence of bytes. In XML, represented using base64.
*/
@Child(name = "data", type = {Base64BinaryType.class}, order=2, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Data inline, base64ed", formalDefinition="The actual data of the attachment - a sequence of bytes. In XML, represented using base64." )
protected Base64BinaryType data;
/**
* An alternative location where the data can be accessed.
*/
@Child(name = "url", type = {UriType.class}, order=3, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Uri where the data can be found", formalDefinition="An alternative location where the data can be accessed." )
protected UriType url;
/**
* The number of bytes of data that make up this attachment.
*/
@Child(name = "size", type = {UnsignedIntType.class}, order=4, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Number of bytes of content (if url provided)", formalDefinition="The number of bytes of data that make up this attachment." )
protected UnsignedIntType size;
/**
* The calculated hash of the data using SHA-1. Represented using base64.
*/
@Child(name = "hash", type = {Base64BinaryType.class}, order=5, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Hash of the data (sha-1, base64ed)", formalDefinition="The calculated hash of the data using SHA-1. Represented using base64." )
protected Base64BinaryType hash;
/**
* A label or set of text to display in place of the data.
*/
@Child(name = "title", type = {StringType.class}, order=6, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Label to display in place of the data", formalDefinition="A label or set of text to display in place of the data." )
protected StringType title;
/**
* The date that the attachment was first created.
*/
@Child(name = "creation", type = {DateTimeType.class}, order=7, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Date attachment was first created", formalDefinition="The date that the attachment was first created." )
protected DateTimeType creation;
private static final long serialVersionUID = 581007080L;
/*
* Constructor
*/
public Attachment() {
super();
}
/**
* @return {@link #contentType} (Identifies the type of the data in the attachment and allows a method to be chosen to interpret or render the data. Includes mime type parameters such as charset where appropriate.). This is the underlying object with id, value and extensions. The accessor "getContentType" gives direct access to the value
*/
public CodeType getContentTypeElement() {
if (this.contentType == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Attachment.contentType");
else if (Configuration.doAutoCreate())
this.contentType = new CodeType(); // bb
return this.contentType;
}
public boolean hasContentTypeElement() {
return this.contentType != null && !this.contentType.isEmpty();
}
public boolean hasContentType() {
return this.contentType != null && !this.contentType.isEmpty();
}
/**
* @param value {@link #contentType} (Identifies the type of the data in the attachment and allows a method to be chosen to interpret or render the data. Includes mime type parameters such as charset where appropriate.). This is the underlying object with id, value and extensions. The accessor "getContentType" gives direct access to the value
*/
public Attachment setContentTypeElement(CodeType value) {
this.contentType = value;
return this;
}
/**
* @return Identifies the type of the data in the attachment and allows a method to be chosen to interpret or render the data. Includes mime type parameters such as charset where appropriate.
*/
public String getContentType() {
return this.contentType == null ? null : this.contentType.getValue();
}
/**
* @param value Identifies the type of the data in the attachment and allows a method to be chosen to interpret or render the data. Includes mime type parameters such as charset where appropriate.
*/
public Attachment setContentType(String value) {
if (Utilities.noString(value))
this.contentType = null;
else {
if (this.contentType == null)
this.contentType = new CodeType();
this.contentType.setValue(value);
}
return this;
}
/**
* @return {@link #language} (The human language of the content. The value can be any valid value according to BCP 47.). This is the underlying object with id, value and extensions. The accessor "getLanguage" gives direct access to the value
*/
public CodeType getLanguageElement() {
if (this.language == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Attachment.language");
else if (Configuration.doAutoCreate())
this.language = new CodeType(); // bb
return this.language;
}
public boolean hasLanguageElement() {
return this.language != null && !this.language.isEmpty();
}
public boolean hasLanguage() {
return this.language != null && !this.language.isEmpty();
}
/**
* @param value {@link #language} (The human language of the content. The value can be any valid value according to BCP 47.). This is the underlying object with id, value and extensions. The accessor "getLanguage" gives direct access to the value
*/
public Attachment setLanguageElement(CodeType value) {
this.language = value;
return this;
}
/**
* @return The human language of the content. The value can be any valid value according to BCP 47.
*/
public String getLanguage() {
return this.language == null ? null : this.language.getValue();
}
/**
* @param value The human language of the content. The value can be any valid value according to BCP 47.
*/
public Attachment setLanguage(String value) {
if (Utilities.noString(value))
this.language = null;
else {
if (this.language == null)
this.language = new CodeType();
this.language.setValue(value);
}
return this;
}
/**
* @return {@link #data} (The actual data of the attachment - a sequence of bytes. In XML, represented using base64.). This is the underlying object with id, value and extensions. The accessor "getData" gives direct access to the value
*/
public Base64BinaryType getDataElement() {
if (this.data == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Attachment.data");
else if (Configuration.doAutoCreate())
this.data = new Base64BinaryType(); // bb
return this.data;
}
public boolean hasDataElement() {
return this.data != null && !this.data.isEmpty();
}
public boolean hasData() {
return this.data != null && !this.data.isEmpty();
}
/**
* @param value {@link #data} (The actual data of the attachment - a sequence of bytes. In XML, represented using base64.). This is the underlying object with id, value and extensions. The accessor "getData" gives direct access to the value
*/
public Attachment setDataElement(Base64BinaryType value) {
this.data = value;
return this;
}
/**
* @return The actual data of the attachment - a sequence of bytes. In XML, represented using base64.
*/
public byte[] getData() {
return this.data == null ? null : this.data.getValue();
}
/**
* @param value The actual data of the attachment - a sequence of bytes. In XML, represented using base64.
*/
public Attachment setData(byte[] value) {
if (value == null)
this.data = null;
else {
if (this.data == null)
this.data = new Base64BinaryType();
this.data.setValue(value);
}
return this;
}
/**
* @return {@link #url} (An alternative location where the data can be accessed.). This is the underlying object with id, value and extensions. The accessor "getUrl" gives direct access to the value
*/
public UriType getUrlElement() {
if (this.url == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Attachment.url");
else if (Configuration.doAutoCreate())
this.url = new UriType(); // bb
return this.url;
}
public boolean hasUrlElement() {
return this.url != null && !this.url.isEmpty();
}
public boolean hasUrl() {
return this.url != null && !this.url.isEmpty();
}
/**
* @param value {@link #url} (An alternative location where the data can be accessed.). This is the underlying object with id, value and extensions. The accessor "getUrl" gives direct access to the value
*/
public Attachment setUrlElement(UriType value) {
this.url = value;
return this;
}
/**
* @return An alternative location where the data can be accessed.
*/
public String getUrl() {
return this.url == null ? null : this.url.getValue();
}
/**
* @param value An alternative location where the data can be accessed.
*/
public Attachment setUrl(String value) {
if (Utilities.noString(value))
this.url = null;
else {
if (this.url == null)
this.url = new UriType();
this.url.setValue(value);
}
return this;
}
/**
* @return {@link #size} (The number of bytes of data that make up this attachment.). This is the underlying object with id, value and extensions. The accessor "getSize" gives direct access to the value
*/
public UnsignedIntType getSizeElement() {
if (this.size == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Attachment.size");
else if (Configuration.doAutoCreate())
this.size = new UnsignedIntType(); // bb
return this.size;
}
public boolean hasSizeElement() {
return this.size != null && !this.size.isEmpty();
}
public boolean hasSize() {
return this.size != null && !this.size.isEmpty();
}
/**
* @param value {@link #size} (The number of bytes of data that make up this attachment.). This is the underlying object with id, value and extensions. The accessor "getSize" gives direct access to the value
*/
public Attachment setSizeElement(UnsignedIntType value) {
this.size = value;
return this;
}
/**
* @return The number of bytes of data that make up this attachment.
*/
public int getSize() {
return this.size == null || this.size.isEmpty() ? 0 : this.size.getValue();
}
/**
* @param value The number of bytes of data that make up this attachment.
*/
public Attachment setSize(int value) {
if (this.size == null)
this.size = new UnsignedIntType();
this.size.setValue(value);
return this;
}
/**
* @return {@link #hash} (The calculated hash of the data using SHA-1. Represented using base64.). This is the underlying object with id, value and extensions. The accessor "getHash" gives direct access to the value
*/
public Base64BinaryType getHashElement() {
if (this.hash == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Attachment.hash");
else if (Configuration.doAutoCreate())
this.hash = new Base64BinaryType(); // bb
return this.hash;
}
public boolean hasHashElement() {
return this.hash != null && !this.hash.isEmpty();
}
public boolean hasHash() {
return this.hash != null && !this.hash.isEmpty();
}
/**
* @param value {@link #hash} (The calculated hash of the data using SHA-1. Represented using base64.). This is the underlying object with id, value and extensions. The accessor "getHash" gives direct access to the value
*/
public Attachment setHashElement(Base64BinaryType value) {
this.hash = value;
return this;
}
/**
* @return The calculated hash of the data using SHA-1. Represented using base64.
*/
public byte[] getHash() {
return this.hash == null ? null : this.hash.getValue();
}
/**
* @param value The calculated hash of the data using SHA-1. Represented using base64.
*/
public Attachment setHash(byte[] value) {
if (value == null)
this.hash = null;
else {
if (this.hash == null)
this.hash = new Base64BinaryType();
this.hash.setValue(value);
}
return this;
}
/**
* @return {@link #title} (A label or set of text to display in place of the data.). This is the underlying object with id, value and extensions. The accessor "getTitle" gives direct access to the value
*/
public StringType getTitleElement() {
if (this.title == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Attachment.title");
else if (Configuration.doAutoCreate())
this.title = new StringType(); // bb
return this.title;
}
public boolean hasTitleElement() {
return this.title != null && !this.title.isEmpty();
}
public boolean hasTitle() {
return this.title != null && !this.title.isEmpty();
}
/**
* @param value {@link #title} (A label or set of text to display in place of the data.). This is the underlying object with id, value and extensions. The accessor "getTitle" gives direct access to the value
*/
public Attachment setTitleElement(StringType value) {
this.title = value;
return this;
}
/**
* @return A label or set of text to display in place of the data.
*/
public String getTitle() {
return this.title == null ? null : this.title.getValue();
}
/**
* @param value A label or set of text to display in place of the data.
*/
public Attachment setTitle(String value) {
if (Utilities.noString(value))
this.title = null;
else {
if (this.title == null)
this.title = new StringType();
this.title.setValue(value);
}
return this;
}
/**
* @return {@link #creation} (The date that the attachment was first created.). This is the underlying object with id, value and extensions. The accessor "getCreation" gives direct access to the value
*/
public DateTimeType getCreationElement() {
if (this.creation == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Attachment.creation");
else if (Configuration.doAutoCreate())
this.creation = new DateTimeType(); // bb
return this.creation;
}
public boolean hasCreationElement() {
return this.creation != null && !this.creation.isEmpty();
}
public boolean hasCreation() {
return this.creation != null && !this.creation.isEmpty();
}
/**
* @param value {@link #creation} (The date that the attachment was first created.). This is the underlying object with id, value and extensions. The accessor "getCreation" gives direct access to the value
*/
public Attachment setCreationElement(DateTimeType value) {
this.creation = value;
return this;
}
/**
* @return The date that the attachment was first created.
*/
public Date getCreation() {
return this.creation == null ? null : this.creation.getValue();
}
/**
* @param value The date that the attachment was first created.
*/
public Attachment setCreation(Date value) {
if (value == null)
this.creation = null;
else {
if (this.creation == null)
this.creation = new DateTimeType();
this.creation.setValue(value);
}
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("contentType", "code", "Identifies the type of the data in the attachment and allows a method to be chosen to interpret or render the data. Includes mime type parameters such as charset where appropriate.", 0, java.lang.Integer.MAX_VALUE, contentType));
childrenList.add(new Property("language", "code", "The human language of the content. The value can be any valid value according to BCP 47.", 0, java.lang.Integer.MAX_VALUE, language));
childrenList.add(new Property("data", "base64Binary", "The actual data of the attachment - a sequence of bytes. In XML, represented using base64.", 0, java.lang.Integer.MAX_VALUE, data));
childrenList.add(new Property("url", "uri", "An alternative location where the data can be accessed.", 0, java.lang.Integer.MAX_VALUE, url));
childrenList.add(new Property("size", "unsignedInt", "The number of bytes of data that make up this attachment.", 0, java.lang.Integer.MAX_VALUE, size));
childrenList.add(new Property("hash", "base64Binary", "The calculated hash of the data using SHA-1. Represented using base64.", 0, java.lang.Integer.MAX_VALUE, hash));
childrenList.add(new Property("title", "string", "A label or set of text to display in place of the data.", 0, java.lang.Integer.MAX_VALUE, title));
childrenList.add(new Property("creation", "dateTime", "The date that the attachment was first created.", 0, java.lang.Integer.MAX_VALUE, creation));
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("contentType"))
this.contentType = castToCode(value); // CodeType
else if (name.equals("language"))
this.language = castToCode(value); // CodeType
else if (name.equals("data"))
this.data = castToBase64Binary(value); // Base64BinaryType
else if (name.equals("url"))
this.url = castToUri(value); // UriType
else if (name.equals("size"))
this.size = castToUnsignedInt(value); // UnsignedIntType
else if (name.equals("hash"))
this.hash = castToBase64Binary(value); // Base64BinaryType
else if (name.equals("title"))
this.title = castToString(value); // StringType
else if (name.equals("creation"))
this.creation = castToDateTime(value); // DateTimeType
else
super.setProperty(name, value);
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("contentType")) {
throw new FHIRException("Cannot call addChild on a primitive type Attachment.contentType");
}
else if (name.equals("language")) {
throw new FHIRException("Cannot call addChild on a primitive type Attachment.language");
}
else if (name.equals("data")) {
throw new FHIRException("Cannot call addChild on a primitive type Attachment.data");
}
else if (name.equals("url")) {
throw new FHIRException("Cannot call addChild on a primitive type Attachment.url");
}
else if (name.equals("size")) {
throw new FHIRException("Cannot call addChild on a primitive type Attachment.size");
}
else if (name.equals("hash")) {
throw new FHIRException("Cannot call addChild on a primitive type Attachment.hash");
}
else if (name.equals("title")) {
throw new FHIRException("Cannot call addChild on a primitive type Attachment.title");
}
else if (name.equals("creation")) {
throw new FHIRException("Cannot call addChild on a primitive type Attachment.creation");
}
else
return super.addChild(name);
}
public String fhirType() {
return "Attachment";
}
public Attachment copy() {
Attachment dst = new Attachment();
copyValues(dst);
dst.contentType = contentType == null ? null : contentType.copy();
dst.language = language == null ? null : language.copy();
dst.data = data == null ? null : data.copy();
dst.url = url == null ? null : url.copy();
dst.size = size == null ? null : size.copy();
dst.hash = hash == null ? null : hash.copy();
dst.title = title == null ? null : title.copy();
dst.creation = creation == null ? null : creation.copy();
return dst;
}
protected Attachment typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof Attachment))
return false;
Attachment o = (Attachment) other;
return compareDeep(contentType, o.contentType, true) && compareDeep(language, o.language, true)
&& compareDeep(data, o.data, true) && compareDeep(url, o.url, true) && compareDeep(size, o.size, true)
&& compareDeep(hash, o.hash, true) && compareDeep(title, o.title, true) && compareDeep(creation, o.creation, true)
;
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof Attachment))
return false;
Attachment o = (Attachment) other;
return compareValues(contentType, o.contentType, true) && compareValues(language, o.language, true)
&& compareValues(data, o.data, true) && compareValues(url, o.url, true) && compareValues(size, o.size, true)
&& compareValues(hash, o.hash, true) && compareValues(title, o.title, true) && compareValues(creation, o.creation, true)
;
}
public boolean isEmpty() {
return super.isEmpty() && (contentType == null || contentType.isEmpty()) && (language == null || language.isEmpty())
&& (data == null || data.isEmpty()) && (url == null || url.isEmpty()) && (size == null || size.isEmpty())
&& (hash == null || hash.isEmpty()) && (title == null || title.isEmpty()) && (creation == null || creation.isEmpty())
;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,186 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Wed, Jul 13, 2016 05:32+1000 for FHIR v1.0.2
import java.util.ArrayList;
import java.util.List;
import org.hl7.fhir.dstu2.model.annotations.Child;
import org.hl7.fhir.dstu2.model.annotations.DatatypeDef;
import org.hl7.fhir.dstu2.model.annotations.Description;
import org.hl7.fhir.dstu2.model.api.IBaseBackboneElement;
import org.hl7.fhir.exceptions.FHIRException;
/**
* Base definition for all elements that are defined inside a resource - but not those in a data type.
*/
@DatatypeDef(name="BackboneElement")
public abstract class BackboneElement extends Element implements IBaseBackboneElement {
/**
* May be used to represent additional information that is not part of the basic definition of the element, and that modifies the understanding of the element that contains it. Usually modifier elements provide negation or qualification. In order to make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions.
*/
@Child(name = "modifierExtension", type = {Extension.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=true, summary=false)
@Description(shortDefinition="Extensions that cannot be ignored", formalDefinition="May be used to represent additional information that is not part of the basic definition of the element, and that modifies the understanding of the element that contains it. Usually modifier elements provide negation or qualification. In order to make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions." )
protected List<Extension> modifierExtension;
private static final long serialVersionUID = -1431673179L;
/*
* Constructor
*/
public BackboneElement() {
super();
}
/**
* @return {@link #modifierExtension} (May be used to represent additional information that is not part of the basic definition of the element, and that modifies the understanding of the element that contains it. Usually modifier elements provide negation or qualification. In order to make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions.)
*/
public List<Extension> getModifierExtension() {
if (this.modifierExtension == null)
this.modifierExtension = new ArrayList<Extension>();
return this.modifierExtension;
}
public boolean hasModifierExtension() {
if (this.modifierExtension == null)
return false;
for (Extension item : this.modifierExtension)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #modifierExtension} (May be used to represent additional information that is not part of the basic definition of the element, and that modifies the understanding of the element that contains it. Usually modifier elements provide negation or qualification. In order to make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions.)
*/
// syntactic sugar
public Extension addModifierExtension() { //3
Extension t = new Extension();
if (this.modifierExtension == null)
this.modifierExtension = new ArrayList<Extension>();
this.modifierExtension.add(t);
return t;
}
// syntactic sugar
public BackboneElement addModifierExtension(Extension t) { //3
if (t == null)
return this;
if (this.modifierExtension == null)
this.modifierExtension = new ArrayList<Extension>();
this.modifierExtension.add(t);
return this;
}
protected void listChildren(List<Property> childrenList) {
childrenList.add(new Property("modifierExtension", "Extension", "May be used to represent additional information that is not part of the basic definition of the element, and that modifies the understanding of the element that contains it. Usually modifier elements provide negation or qualification. In order to make the use of extensions safe and manageable, there is a strict set of governance applied to the definition and use of extensions. Though any implementer is allowed to define an extension, there is a set of requirements that SHALL be met as part of the definition of the extension. Applications processing a resource are required to check for modifier extensions.", 0, java.lang.Integer.MAX_VALUE, modifierExtension));
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("modifierExtension"))
this.getModifierExtension().add(castToExtension(value));
else
super.setProperty(name, value);
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("modifierExtension")) {
return addModifierExtension();
}
else
return super.addChild(name);
}
public String fhirType() {
return "BackboneElement";
}
public abstract BackboneElement copy();
public void copyValues(BackboneElement dst) {
if (modifierExtension != null) {
dst.modifierExtension = new ArrayList<Extension>();
for (Extension i : modifierExtension)
dst.modifierExtension.add(i.copy());
};
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof BackboneElement))
return false;
BackboneElement o = (BackboneElement) other;
return compareDeep(modifierExtension, o.modifierExtension, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof BackboneElement))
return false;
BackboneElement o = (BackboneElement) other;
return true;
}
public boolean isEmpty() {
return super.isEmpty() && (modifierExtension == null || modifierExtension.isEmpty());
}
}

View File

@ -0,0 +1,560 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hl7.fhir.dstu2.model.api.IBase;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.utilities.xhtml.XhtmlNode;
public abstract class Base implements Serializable, IBase {
/**
* User appended data items - allow users to add extra information to the class
*/
private Map<String, Object> userData;
/**
* Round tracking xml comments for testing convenience
*/
private List<String> formatCommentsPre;
/**
* Round tracking xml comments for testing convenience
*/
private List<String> formatCommentsPost;
public Object getUserData(String name) {
if (userData == null)
return null;
return userData.get(name);
}
public void setUserData(String name, Object value) {
if (userData == null)
userData = new HashMap<String, Object>();
userData.put(name, value);
}
public void setUserDataINN(String name, Object value) {
if (value == null)
return;
if (userData == null)
userData = new HashMap<String, Object>();
userData.put(name, value);
}
public boolean hasUserData(String name) {
if (userData == null)
return false;
else
return userData.containsKey(name);
}
public String getUserString(String name) {
return (String) getUserData(name);
}
public int getUserInt(String name) {
if (!hasUserData(name))
return 0;
return (Integer) getUserData(name);
}
public boolean hasFormatComment() {
return (formatCommentsPre != null && !formatCommentsPre.isEmpty()) || (formatCommentsPost != null && !formatCommentsPost.isEmpty());
}
public List<String> getFormatCommentsPre() {
if (formatCommentsPre == null)
formatCommentsPre = new ArrayList<String>();
return formatCommentsPre;
}
public List<String> getFormatCommentsPost() {
if (formatCommentsPost == null)
formatCommentsPost = new ArrayList<String>();
return formatCommentsPost;
}
// these 2 allow evaluation engines to get access to primitive values
public boolean isPrimitive() {
return false;
}
public String primitiveValue() {
return null;
}
public abstract String fhirType() ;
public boolean hasType(String... name) {
String t = fhirType();
for (String n : name)
if (n.equals(t))
return true;
return false;
}
protected abstract void listChildren(List<Property> result) ;
public void setProperty(String name, Base value) throws FHIRException {
throw new FHIRException("Attempt to set unknown property "+name);
}
public Base addChild(String name) throws FHIRException {
throw new FHIRException("Attempt to add child with unknown name "+name);
}
/**
* Supports iterating the children elements in some generic processor or browser
* All defined children will be listed, even if they have no value on this instance
*
* Note that the actual content of primitive or xhtml elements is not iterated explicitly.
* To find these, the processing code must recognise the element as a primitive, typecast
* the value to a {@link Type}, and examine the value
*
* @return a list of all the children defined for this element
*/
public List<Property> children() {
List<Property> result = new ArrayList<Property>();
listChildren(result);
return result;
}
public Property getChildByName(String name) {
List<Property> children = new ArrayList<Property>();
listChildren(children);
for (Property c : children)
if (c.getName().equals(name))
return c;
return null;
}
public List<Base> listChildrenByName(String name) {
List<Property> children = new ArrayList<Property>();
listChildren(children);
if (name.equals("*")) {
List<Base> res = new ArrayList<Base>();
for (Property p : children) {
res.addAll(p.getValues());
}
return res;
} else {
for (Property c : children)
if (c.getName().equals(name) || (c.getName().equals(name+"[x]")))
return c.getValues();
}
return new ArrayList<Base>();
}
public boolean isEmpty() {
return true; // userData does not count
}
public boolean equalsDeep(Base other) {
return other != null;
}
public boolean equalsShallow(Base other) {
return other != null;
}
public static boolean compareDeep(List<? extends Base> e1, List<? extends Base> e2, boolean allowNull) {
if (noList(e1) && noList(e2) && allowNull)
return true;
if (noList(e1) || noList(e2))
return false;
if (e1.size() != e2.size())
return false;
for (int i = 0; i < e1.size(); i++) {
if (!compareDeep(e1.get(i), e2.get(i), allowNull))
return false;
}
return true;
}
private static boolean noList(List<? extends Base> list) {
return list == null || list.isEmpty();
}
public static boolean compareDeep(Base e1, Base e2, boolean allowNull) {
if (e1 == null && e2 == null && allowNull)
return true;
if (e1 == null || e2 == null)
return false;
if (e2.isMetadataBased() && !e1.isMetadataBased()) // respect existing order for debugging consistency; outcome must be the same either way
return e2.equalsDeep(e1);
else
return e1.equalsDeep(e2);
}
public static boolean compareDeep(XhtmlNode div1, XhtmlNode div2, boolean allowNull) {
if (div1 == null && div2 == null && allowNull)
return true;
if (div1 == null || div2 == null)
return false;
return div1.equalsDeep(div2);
}
public static boolean compareValues(List<? extends PrimitiveType> e1, List<? extends PrimitiveType> e2, boolean allowNull) {
if (e1 == null && e2 == null && allowNull)
return true;
if (e1 == null || e2 == null)
return false;
if (e1.size() != e2.size())
return false;
for (int i = 0; i < e1.size(); i++) {
if (!compareValues(e1.get(i), e2.get(i), allowNull))
return false;
}
return true;
}
public static boolean compareValues(PrimitiveType e1, PrimitiveType e2, boolean allowNull) {
if (e1 == null && e2 == null && allowNull)
return true;
if (e1 == null || e2 == null)
return false;
return e1.equalsShallow(e2);
}
// -- converters for property setters
public BooleanType castToBoolean(Base b) throws FHIRException {
if (b instanceof BooleanType)
return (BooleanType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Boolean");
}
public IntegerType castToInteger(Base b) throws FHIRException {
if (b instanceof IntegerType)
return (IntegerType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Integer");
}
public DecimalType castToDecimal(Base b) throws FHIRException {
if (b instanceof DecimalType)
return (DecimalType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Decimal");
}
public Base64BinaryType castToBase64Binary(Base b) throws FHIRException {
if (b instanceof Base64BinaryType)
return (Base64BinaryType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Base64Binary");
}
public InstantType castToInstant(Base b) throws FHIRException {
if (b instanceof InstantType)
return (InstantType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Instant");
}
public StringType castToString(Base b) throws FHIRException {
if (b instanceof StringType)
return (StringType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a String");
}
public UriType castToUri(Base b) throws FHIRException {
if (b instanceof UriType)
return (UriType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Uri");
}
public DateType castToDate(Base b) throws FHIRException {
if (b instanceof DateType)
return (DateType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Date");
}
public DateTimeType castToDateTime(Base b) throws FHIRException {
if (b instanceof DateTimeType)
return (DateTimeType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a DateTime");
}
public TimeType castToTime(Base b) throws FHIRException {
if (b instanceof TimeType)
return (TimeType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Time");
}
public CodeType castToCode(Base b) throws FHIRException {
if (b instanceof CodeType)
return (CodeType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Code");
}
public OidType castToOid(Base b) throws FHIRException {
if (b instanceof OidType)
return (OidType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Oid");
}
public IdType castToId(Base b) throws FHIRException {
if (b instanceof IdType)
return (IdType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Id");
}
public UnsignedIntType castToUnsignedInt(Base b) throws FHIRException {
if (b instanceof UnsignedIntType)
return (UnsignedIntType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a UnsignedInt");
}
public PositiveIntType castToPositiveInt(Base b) throws FHIRException {
if (b instanceof PositiveIntType)
return (PositiveIntType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a PositiveInt");
}
public MarkdownType castToMarkdown(Base b) throws FHIRException {
if (b instanceof MarkdownType)
return (MarkdownType) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Markdown");
}
public Annotation castToAnnotation(Base b) throws FHIRException {
if (b instanceof Annotation)
return (Annotation) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to an Annotation");
}
public Attachment castToAttachment(Base b) throws FHIRException {
if (b instanceof Attachment)
return (Attachment) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to an Attachment");
}
public Identifier castToIdentifier(Base b) throws FHIRException {
if (b instanceof Identifier)
return (Identifier) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to an Identifier");
}
public CodeableConcept castToCodeableConcept(Base b) throws FHIRException {
if (b instanceof CodeableConcept)
return (CodeableConcept) b;
else if (b instanceof CodeType) {
CodeableConcept cc = new CodeableConcept();
cc.addCoding().setCode(((CodeType) b).asStringValue());
return cc;
} else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a CodeableConcept");
}
public Coding castToCoding(Base b) throws FHIRException {
if (b instanceof Coding)
return (Coding) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Coding");
}
public Quantity castToQuantity(Base b) throws FHIRException {
if (b instanceof Quantity)
return (Quantity) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to an Quantity");
}
public Money castToMoney(Base b) throws FHIRException {
if (b instanceof Money)
return (Money) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to an Money");
}
public Duration castToDuration(Base b) throws FHIRException {
if (b instanceof Duration)
return (Duration) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to an Duration");
}
public SimpleQuantity castToSimpleQuantity(Base b) throws FHIRException {
if (b instanceof SimpleQuantity)
return (SimpleQuantity) b;
else if (b instanceof Quantity) {
Quantity q = (Quantity) b;
SimpleQuantity sq = new SimpleQuantity();
sq.setValueElement(q.getValueElement());
sq.setComparatorElement(q.getComparatorElement());
sq.setUnitElement(q.getUnitElement());
sq.setSystemElement(q.getSystemElement());
sq.setCodeElement(q.getCodeElement());
return sq;
} else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to an SimpleQuantity");
}
public Range castToRange(Base b) throws FHIRException {
if (b instanceof Range)
return (Range) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Range");
}
public Period castToPeriod(Base b) throws FHIRException {
if (b instanceof Period)
return (Period) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Period");
}
public Ratio castToRatio(Base b) throws FHIRException {
if (b instanceof Ratio)
return (Ratio) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Ratio");
}
public SampledData castToSampledData(Base b) throws FHIRException {
if (b instanceof SampledData)
return (SampledData) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a SampledData");
}
public Signature castToSignature(Base b) throws FHIRException {
if (b instanceof Signature)
return (Signature) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Signature");
}
public HumanName castToHumanName(Base b) throws FHIRException {
if (b instanceof HumanName)
return (HumanName) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a HumanName");
}
public Address castToAddress(Base b) throws FHIRException {
if (b instanceof Address)
return (Address) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Address");
}
public ContactPoint castToContactPoint(Base b) throws FHIRException {
if (b instanceof ContactPoint)
return (ContactPoint) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a ContactPoint");
}
public Timing castToTiming(Base b) throws FHIRException {
if (b instanceof Timing)
return (Timing) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Timing");
}
public Reference castToReference(Base b) throws FHIRException {
if (b instanceof Reference)
return (Reference) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Reference");
}
public Meta castToMeta(Base b) throws FHIRException {
if (b instanceof Meta)
return (Meta) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Meta");
}
public Extension castToExtension(Base b) throws FHIRException {
if (b instanceof Extension)
return (Extension) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Extension");
}
public Resource castToResource(Base b) throws FHIRException {
if (b instanceof Resource)
return (Resource) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Resource");
}
public Narrative castToNarrative(Base b) throws FHIRException {
if (b instanceof Narrative)
return (Narrative) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a Narrative");
}
public ElementDefinition castToElementDefinition(Base b) throws FHIRException {
if (b instanceof ElementDefinition)
return (ElementDefinition) b;
else
throw new FHIRException("Unable to convert a "+b.getClass().getName()+" to a ElementDefinition");
}
protected boolean isMetadataBased() {
return false;
}
public static boolean equals(String v1, String v2) {
if (v1 == null && v2 == null)
return true;
else if (v1 == null || v2 == null)
return false;
else
return v1.equals(v2);
}
}

View File

@ -0,0 +1,96 @@
/*
Copyright (c) 2011+, HL7, Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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.apache.commons.codec.binary.Base64;
import org.hl7.fhir.dstu2.model.annotations.DatatypeDef;
/**
* Primitive type "base64Binary" in FHIR: a sequence of bytes represented in base64
*/
@DatatypeDef(name="base64binary")
public class Base64BinaryType extends PrimitiveType<byte[]> {
private static final long serialVersionUID = 3L;
/**
* Constructor
*/
public Base64BinaryType() {
super();
}
public Base64BinaryType(byte[] theBytes) {
super();
setValue(theBytes);
}
public Base64BinaryType(String theValue) {
super();
setValueAsString(theValue);
}
protected byte[] parse(String theValue) {
return Base64.decodeBase64(theValue);
}
protected String encode(byte[] theValue) {
return Base64.encodeBase64String(theValue);
}
@Override
public Base64BinaryType copy() {
return new Base64BinaryType(getValue());
}
public String fhirType() {
return "base64Binary";
}
}

View File

@ -0,0 +1,44 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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.dstu2.model.api.IBaseBinary;
public abstract class BaseBinary extends Resource implements IBaseBinary {
@Override
public String getContentAsBase64() {
return getContentElement().getValueAsString();
}
@Override
public BaseBinary setContentAsBase64(String theContent) {
if (theContent != null) {
getContentElement().setValueAsString(theContent);
} else {
setContent(null);
}
return this;
}
abstract Base64BinaryType getContentElement();
}

View File

@ -0,0 +1,641 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import static org.hl7.fhir.dstu2.model.TemporalPrecisionEnum.DAY;
import static org.hl7.fhir.dstu2.model.TemporalPrecisionEnum.MONTH;
import static org.hl7.fhir.dstu2.model.TemporalPrecisionEnum.YEAR;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.TimeZone;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.time.FastDateFormat;
public abstract class BaseDateTimeType extends PrimitiveType<Date> {
private static final long serialVersionUID = 1L;
/*
* Add any new formatters to the static block below!!
*/
private static final List<FastDateFormat> ourFormatters;
private static final Pattern ourYearDashMonthDashDayPattern = Pattern.compile("[0-9]{4}-[0-9]{2}-[0-9]{2}");
private static final Pattern ourYearDashMonthPattern = Pattern.compile("[0-9]{4}-[0-9]{2}");
private static final FastDateFormat ourYearFormat = FastDateFormat.getInstance("yyyy");
private static final FastDateFormat ourYearMonthDayFormat = FastDateFormat.getInstance("yyyy-MM-dd");
private static final FastDateFormat ourYearMonthDayNoDashesFormat = FastDateFormat.getInstance("yyyyMMdd");
private static final Pattern ourYearMonthDayPattern = Pattern.compile("[0-9]{4}[0-9]{2}[0-9]{2}");
private static final FastDateFormat ourYearMonthDayTimeFormat = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss");
private static final FastDateFormat ourYearMonthDayTimeMilliFormat = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS");
private static final FastDateFormat ourYearMonthDayTimeMilliUTCZFormat = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("UTC"));
private static final FastDateFormat ourYearMonthDayTimeMilliZoneFormat = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSSZZ");
private static final FastDateFormat ourYearMonthDayTimeUTCZFormat = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss'Z'", TimeZone.getTimeZone("UTC"));
private static final FastDateFormat ourYearMonthDayTimeZoneFormat = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ssZZ");
private static final FastDateFormat ourYearMonthFormat = FastDateFormat.getInstance("yyyy-MM");
private static final FastDateFormat ourYearMonthNoDashesFormat = FastDateFormat.getInstance("yyyyMM");
private static final Pattern ourYearMonthPattern = Pattern.compile("[0-9]{4}[0-9]{2}");
private static final Pattern ourYearPattern = Pattern.compile("[0-9]{4}");
private static final FastDateFormat ourYearMonthDayTimeMinsFormat = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm");
private static final FastDateFormat ourYearMonthDayTimeMinsUTCZFormat = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm'Z'", TimeZone.getTimeZone("UTC"));
private static final FastDateFormat ourYearMonthDayTimeMinsZoneFormat = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mmZZ");
private static final FastDateFormat ourHumanDateTimeFormat = FastDateFormat.getDateTimeInstance(FastDateFormat.MEDIUM, FastDateFormat.MEDIUM);
private static final FastDateFormat ourHumanDateFormat = FastDateFormat.getDateInstance(FastDateFormat.MEDIUM);
static {
ArrayList<FastDateFormat> formatters = new ArrayList<FastDateFormat>();
formatters.add(ourYearFormat);
formatters.add(ourYearMonthDayFormat);
formatters.add(ourYearMonthDayNoDashesFormat);
formatters.add(ourYearMonthDayTimeFormat);
formatters.add(ourYearMonthDayTimeUTCZFormat);
formatters.add(ourYearMonthDayTimeZoneFormat);
formatters.add(ourYearMonthDayTimeMilliFormat);
formatters.add(ourYearMonthDayTimeMilliUTCZFormat);
formatters.add(ourYearMonthDayTimeMilliZoneFormat);
formatters.add(ourYearMonthDayTimeMinsFormat);
formatters.add(ourYearMonthDayTimeMinsUTCZFormat);
formatters.add(ourYearMonthDayTimeMinsZoneFormat);
formatters.add(ourYearMonthFormat);
formatters.add(ourYearMonthNoDashesFormat);
ourFormatters = Collections.unmodifiableList(formatters);
}
private TemporalPrecisionEnum myPrecision = TemporalPrecisionEnum.SECOND;
private TimeZone myTimeZone;
private boolean myTimeZoneZulu = false;
/**
* Constructor
*/
public BaseDateTimeType() {
// nothing
}
/**
* Constructor
*
* @throws IllegalArgumentException
* If the specified precision is not allowed for this type
*/
public BaseDateTimeType(Date theDate, TemporalPrecisionEnum thePrecision) {
setValue(theDate, thePrecision);
if (isPrecisionAllowed(thePrecision) == false) {
throw new IllegalArgumentException("Invalid date/time string (datatype " + getClass().getSimpleName() + " does not support " + thePrecision + " precision): " + theDate);
}
}
/**
* Constructor
*
* @throws IllegalArgumentException
* If the specified precision is not allowed for this type
*/
public BaseDateTimeType(String theString) {
setValueAsString(theString);
if (isPrecisionAllowed(getPrecision()) == false) {
throw new IllegalArgumentException("Invalid date/time string (datatype " + getClass().getSimpleName() + " does not support " + getPrecision() + " precision): " + theString);
}
}
/**
* Constructor
*/
public BaseDateTimeType(Date theDate, TemporalPrecisionEnum thePrecision, TimeZone theTimeZone) {
this(theDate, thePrecision);
setTimeZone(theTimeZone);
}
private void clearTimeZone() {
myTimeZone = null;
myTimeZoneZulu = false;
}
@Override
protected String encode(Date theValue) {
if (theValue == null) {
return null;
} else {
switch (myPrecision) {
case DAY:
return ourYearMonthDayFormat.format(theValue);
case MONTH:
return ourYearMonthFormat.format(theValue);
case YEAR:
return ourYearFormat.format(theValue);
case MINUTE:
if (myTimeZoneZulu) {
GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
cal.setTime(theValue);
return ourYearMonthDayTimeMinsFormat.format(cal) + "Z";
} else if (myTimeZone != null) {
GregorianCalendar cal = new GregorianCalendar(myTimeZone);
cal.setTime(theValue);
return (ourYearMonthDayTimeMinsZoneFormat.format(cal));
} else {
return ourYearMonthDayTimeMinsFormat.format(theValue);
}
case SECOND:
if (myTimeZoneZulu) {
GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
cal.setTime(theValue);
return ourYearMonthDayTimeFormat.format(cal) + "Z";
} else if (myTimeZone != null) {
GregorianCalendar cal = new GregorianCalendar(myTimeZone);
cal.setTime(theValue);
return (ourYearMonthDayTimeZoneFormat.format(cal));
} else {
return ourYearMonthDayTimeFormat.format(theValue);
}
case MILLI:
if (myTimeZoneZulu) {
GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
cal.setTime(theValue);
return ourYearMonthDayTimeMilliFormat.format(cal) + "Z";
} else if (myTimeZone != null) {
GregorianCalendar cal = new GregorianCalendar(myTimeZone);
cal.setTime(theValue);
return (ourYearMonthDayTimeMilliZoneFormat.format(cal));
} else {
return ourYearMonthDayTimeMilliFormat.format(theValue);
}
}
throw new IllegalStateException("Invalid precision (this is a bug, shouldn't happen): " + myPrecision);
}
}
/**
* Returns the default precision for the given datatype
*/
protected abstract TemporalPrecisionEnum getDefaultPrecisionForDatatype();
/**
* Gets the precision for this datatype (using the default for the given type if not set)
*
* @see #setPrecision(TemporalPrecisionEnum)
*/
public TemporalPrecisionEnum getPrecision() {
if (myPrecision == null) {
return getDefaultPrecisionForDatatype();
}
return myPrecision;
}
/**
* Returns the TimeZone associated with this dateTime's value. May return <code>null</code> if no timezone was
* supplied.
*/
public TimeZone getTimeZone() {
return myTimeZone;
}
private boolean hasOffset(String theValue) {
boolean inTime = false;
for (int i = 0; i < theValue.length(); i++) {
switch (theValue.charAt(i)) {
case 'T':
inTime = true;
break;
case '+':
case '-':
if (inTime) {
return true;
}
break;
}
}
return false;
}
/**
* To be implemented by subclasses to indicate whether the given precision is allowed by this type
*/
abstract boolean isPrecisionAllowed(TemporalPrecisionEnum thePrecision);
public boolean isTimeZoneZulu() {
return myTimeZoneZulu;
}
/**
* Returns <code>true</code> if this object represents a date that is today's date
*
* @throws NullPointerException
* if {@link #getValue()} returns <code>null</code>
*/
public boolean isToday() {
Validate.notNull(getValue(), getClass().getSimpleName() + " contains null value");
return DateUtils.isSameDay(new Date(), getValue());
}
@Override
protected Date parse(String theValue) throws IllegalArgumentException {
try {
if (theValue.length() == 4 && ourYearPattern.matcher(theValue).matches()) {
if (!isPrecisionAllowed(YEAR)) {
// ourLog.debug("Invalid date/time string (datatype " + getClass().getSimpleName() +
// " does not support YEAR precision): " + theValue);
}
setPrecision(YEAR);
clearTimeZone();
return ((ourYearFormat).parse(theValue));
} else if (theValue.length() == 6 && ourYearMonthPattern.matcher(theValue).matches()) {
// Eg. 198401 (allow this just to be lenient)
if (!isPrecisionAllowed(MONTH)) {
// ourLog.debug("Invalid date/time string (datatype " + getClass().getSimpleName() +
// " does not support DAY precision): " + theValue);
}
setPrecision(MONTH);
clearTimeZone();
return ((ourYearMonthNoDashesFormat).parse(theValue));
} else if (theValue.length() == 7 && ourYearDashMonthPattern.matcher(theValue).matches()) {
// E.g. 1984-01 (this is valid according to the spec)
if (!isPrecisionAllowed(MONTH)) {
// ourLog.debug("Invalid date/time string (datatype " + getClass().getSimpleName() +
// " does not support MONTH precision): " + theValue);
}
setPrecision(MONTH);
clearTimeZone();
return ((ourYearMonthFormat).parse(theValue));
} else if (theValue.length() == 8 && ourYearMonthDayPattern.matcher(theValue).matches()) {
// Eg. 19840101 (allow this just to be lenient)
if (!isPrecisionAllowed(DAY)) {
// ourLog.debug("Invalid date/time string (datatype " + getClass().getSimpleName() +
// " does not support DAY precision): " + theValue);
}
setPrecision(DAY);
clearTimeZone();
return ((ourYearMonthDayNoDashesFormat).parse(theValue));
} else if (theValue.length() == 10 && ourYearDashMonthDashDayPattern.matcher(theValue).matches()) {
// E.g. 1984-01-01 (this is valid according to the spec)
if (!isPrecisionAllowed(DAY)) {
// ourLog.debug("Invalid date/time string (datatype " + getClass().getSimpleName() +
// " does not support DAY precision): " + theValue);
}
setPrecision(DAY);
clearTimeZone();
return ((ourYearMonthDayFormat).parse(theValue));
} else if (theValue.length() >= 16) { // date and time with possible time zone
int firstColonIndex = theValue.indexOf(':');
if (firstColonIndex == -1) {
throw new IllegalArgumentException("Invalid date/time string: " + theValue);
}
boolean hasSeconds = theValue.length() > firstColonIndex+3 ? theValue.charAt(firstColonIndex+3) == ':' : false;
int dotIndex = theValue.length() >= 18 ? theValue.indexOf('.', 18): -1;
boolean hasMillis = dotIndex > -1;
// if (!hasMillis && !isPrecisionAllowed(SECOND)) {
// ourLog.debug("Invalid date/time string (data type does not support SECONDS precision): " +
// theValue);
// } else if (hasMillis && !isPrecisionAllowed(MILLI)) {
// ourLog.debug("Invalid date/time string (data type " + getClass().getSimpleName() +
// " does not support MILLIS precision):" + theValue);
// }
Date retVal;
if (hasMillis) {
try {
if (hasOffset(theValue)) {
retVal = ourYearMonthDayTimeMilliZoneFormat.parse(theValue);
} else if (theValue.endsWith("Z")) {
retVal = ourYearMonthDayTimeMilliUTCZFormat.parse(theValue);
} else {
retVal = ourYearMonthDayTimeMilliFormat.parse(theValue);
}
} catch (ParseException p2) {
throw new IllegalArgumentException("Invalid data/time string (" + p2.getMessage() + "): " + theValue);
}
setTimeZone(theValue, hasMillis);
setPrecision(TemporalPrecisionEnum.MILLI);
} else if (hasSeconds) {
try {
if (hasOffset(theValue)) {
retVal = ourYearMonthDayTimeZoneFormat.parse(theValue);
} else if (theValue.endsWith("Z")) {
retVal = ourYearMonthDayTimeUTCZFormat.parse(theValue);
} else {
retVal = ourYearMonthDayTimeFormat.parse(theValue);
}
} catch (ParseException p2) {
throw new IllegalArgumentException("Invalid data/time string (" + p2.getMessage() + "): " + theValue);
}
setTimeZone(theValue, hasMillis);
setPrecision(TemporalPrecisionEnum.SECOND);
} else {
try {
if (hasOffset(theValue)) {
retVal = ourYearMonthDayTimeMinsZoneFormat.parse(theValue);
} else if (theValue.endsWith("Z")) {
retVal = ourYearMonthDayTimeMinsUTCZFormat.parse(theValue);
} else {
retVal = ourYearMonthDayTimeMinsFormat.parse(theValue);
}
} catch (ParseException p2) {
throw new IllegalArgumentException("Invalid data/time string (" + p2.getMessage() + "): " + theValue, p2);
}
setTimeZone(theValue, hasMillis);
setPrecision(TemporalPrecisionEnum.MINUTE);
}
return retVal;
} else {
throw new IllegalArgumentException("Invalid date/time string (invalid length): " + theValue);
}
} catch (ParseException e) {
throw new IllegalArgumentException("Invalid date string (" + e.getMessage() + "): " + theValue);
}
}
/**
* Sets the precision for this datatype using field values from {@link Calendar}. Valid values are:
* <ul>
* <li>{@link Calendar#SECOND}
* <li>{@link Calendar#DAY_OF_MONTH}
* <li>{@link Calendar#MONTH}
* <li>{@link Calendar#YEAR}
* </ul>
*
* @throws IllegalArgumentException
*/
public void setPrecision(TemporalPrecisionEnum thePrecision) throws IllegalArgumentException {
if (thePrecision == null) {
throw new NullPointerException("Precision may not be null");
}
myPrecision = thePrecision;
updateStringValue();
}
private void setTimeZone(String theValueString, boolean hasMillis) {
clearTimeZone();
int timeZoneStart = 19;
if (hasMillis)
timeZoneStart += 4;
if (theValueString.endsWith("Z")) {
setTimeZoneZulu(true);
} else if (theValueString.indexOf("GMT", timeZoneStart) != -1) {
setTimeZone(TimeZone.getTimeZone(theValueString.substring(timeZoneStart)));
} else if (theValueString.indexOf('+', timeZoneStart) != -1 || theValueString.indexOf('-', timeZoneStart) != -1) {
setTimeZone(TimeZone.getTimeZone("GMT" + theValueString.substring(timeZoneStart)));
}
}
public void setTimeZone(TimeZone theTimeZone) {
myTimeZone = theTimeZone;
updateStringValue();
}
public void setTimeZoneZulu(boolean theTimeZoneZulu) {
myTimeZoneZulu = theTimeZoneZulu;
updateStringValue();
}
/**
* Sets the value of this date/time using the default level of precision
* for this datatype
* using the system local time zone
*
* @param theValue
* The date value
*/
@Override
public BaseDateTimeType setValue(Date theValue) {
if (myTimeZoneZulu == false && myTimeZone == null) {
myTimeZone = TimeZone.getDefault();
}
myPrecision = getDefaultPrecisionForDatatype();
BaseDateTimeType retVal = (BaseDateTimeType) super.setValue(theValue);
return retVal;
}
/**
* Sets the value of this date/time using the specified level of precision
* using the system local time zone
*
* @param theValue
* The date value
* @param thePrecision
* The precision
* @throws IllegalArgumentException
*/
public void setValue(Date theValue, TemporalPrecisionEnum thePrecision) throws IllegalArgumentException {
if (myTimeZoneZulu == false && myTimeZone == null) {
myTimeZone = TimeZone.getDefault();
}
myPrecision = thePrecision;
super.setValue(theValue);
}
@Override
public void setValueAsString(String theValue) throws IllegalArgumentException {
clearTimeZone();
super.setValueAsString(theValue);
}
/**
* For unit tests only
*/
static List<FastDateFormat> getFormatters() {
return ourFormatters;
}
public boolean before(DateTimeType theDateTimeType) {
return getValue().before(theDateTimeType.getValue());
}
public boolean after(DateTimeType theDateTimeType) {
return getValue().after(theDateTimeType.getValue());
}
/**
* Returns a human readable version of this date/time using the system local format.
* <p>
* <b>Note on time zones:</b> This method renders the value using the time zone
* that is contained within the value. For example, if this date object contains the
* value "2012-01-05T12:00:00-08:00", the human display will be rendered as "12:00:00"
* even if the application is being executed on a system in a different time zone. If
* this behaviour is not what you want, use {@link #toHumanDisplayLocalTimezone()}
* instead.
* </p>
*/
public String toHumanDisplay() {
TimeZone tz = getTimeZone();
Calendar value = tz != null ? Calendar.getInstance(tz) : Calendar.getInstance();
value.setTime(getValue());
switch (getPrecision()) {
case YEAR:
case MONTH:
case DAY:
return ourHumanDateFormat.format(value);
case MILLI:
case SECOND:
default:
return ourHumanDateTimeFormat.format(value);
}
}
/**
* Returns a human readable version of this date/time using the system local format,
* converted to the local timezone if neccesary.
*
* @see #toHumanDisplay() for a method which does not convert the time to the local
* timezone before rendering it.
*/
public String toHumanDisplayLocalTimezone() {
switch (getPrecision()) {
case YEAR:
case MONTH:
case DAY:
return ourHumanDateFormat.format(getValue());
case MILLI:
case SECOND:
default:
return ourHumanDateTimeFormat.format(getValue());
}
}
/**
* Returns a view of this date/time as a Calendar object
*/
public Calendar toCalendar() {
Calendar retVal = Calendar.getInstance();
retVal.setTime(getValue());
retVal.setTimeZone(getTimeZone());
return retVal;
}
/**
* Sets the TimeZone offset in minutes relative to GMT
*/
public void setOffsetMinutes(int theZoneOffsetMinutes) {
int offsetAbs = Math.abs(theZoneOffsetMinutes);
int mins = offsetAbs % 60;
int hours = offsetAbs / 60;
if (theZoneOffsetMinutes < 0) {
setTimeZone(TimeZone.getTimeZone("GMT-" + hours + ":" + mins));
} else {
setTimeZone(TimeZone.getTimeZone("GMT+" + hours + ":" + mins));
}
}
/**
* Returns the time in millis as represented by this Date/Time
*/
public long getTime() {
return getValue().getTime();
}
/**
* Adds the given amount to the field specified by theField
*
* @param theField
* The field, uses constants from {@link Calendar} such as {@link Calendar#YEAR}
* @param theValue
* The number to add (or subtract for a negative number)
*/
public void add(int theField, int theValue) {
switch (theField) {
case Calendar.YEAR:
setValue(DateUtils.addYears(getValue(), theValue), getPrecision());
break;
case Calendar.MONTH:
setValue(DateUtils.addMonths(getValue(), theValue), getPrecision());
break;
case Calendar.DATE:
setValue(DateUtils.addDays(getValue(), theValue), getPrecision());
break;
case Calendar.HOUR:
setValue(DateUtils.addHours(getValue(), theValue), getPrecision());
break;
case Calendar.MINUTE:
setValue(DateUtils.addMinutes(getValue(), theValue), getPrecision());
break;
case Calendar.SECOND:
setValue(DateUtils.addSeconds(getValue(), theValue), getPrecision());
break;
case Calendar.MILLISECOND:
setValue(DateUtils.addMilliseconds(getValue(), theValue), getPrecision());
break;
default:
throw new IllegalArgumentException("Unknown field constant: " + theField);
}
}
protected void setValueAsV3String(String theV3String) {
if (StringUtils.isBlank(theV3String)) {
setValue(null);
} else {
StringBuilder b = new StringBuilder();
String timeZone = null;
for (int i = 0; i < theV3String.length(); i++) {
char nextChar = theV3String.charAt(i);
if (nextChar == '+' || nextChar == '-' || nextChar == 'Z') {
timeZone = (theV3String.substring(i));
break;
}
// assertEquals("2013-02-02T20:13:03-05:00", DateAndTime.parseV3("20130202201303-0500").toString());
if (i == 4 || i == 6) {
b.append('-');
} else if (i == 8) {
b.append('T');
} else if (i == 10 || i == 12) {
b.append(':');
}
b.append(nextChar);
}
if (b.length() == 16)
b.append(":00"); // schema rule, must have seconds
if (timeZone != null && b.length() > 10) {
if (timeZone.length() ==5) {
b.append(timeZone.substring(0, 3));
b.append(':');
b.append(timeZone.substring(3));
}else {
b.append(timeZone);
}
}
setValueAsString(b.toString());
}
}
}

View File

@ -0,0 +1,37 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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.dstu2.model.api.IBaseDatatype;
import org.hl7.fhir.dstu2.model.api.IBaseExtension;
import org.hl7.fhir.dstu2.model.api.IBaseHasExtensions;
public abstract class BaseExtension extends Type implements IBaseExtension<Extension, Type>, IBaseHasExtensions {
@Override
public Extension setValue(IBaseDatatype theValue) {
setValue((Type)theValue);
return (Extension) this;
}
public abstract Extension setValue(Type theValue);
}

View File

@ -0,0 +1,59 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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.apache.commons.lang3.StringUtils;
import org.hl7.fhir.dstu2.model.api.INarrative;
import org.hl7.fhir.utilities.xhtml.XhtmlNode;
public abstract class BaseNarrative extends Type implements INarrative {
/**
* Sets the value of
*
* @param theString
* @throws Exception
*/
public void setDivAsString(String theString) {
XhtmlNode div;
if (StringUtils.isNotBlank(theString)) {
div = new XhtmlNode();
div.setValueAsString(theString);
} else {
div = null;
}
setDiv(div);
}
protected abstract BaseNarrative setDiv(XhtmlNode theDiv);
public String getDivAsString() {
XhtmlNode div = getDiv();
if (div != null && !div.isEmpty()) {
return div.getValueAsString();
} else {
return null;
}
}
protected abstract XhtmlNode getDiv();
}

View File

@ -0,0 +1,85 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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.dstu2.model.api.IAnyResource;
import org.hl7.fhir.dstu2.model.api.IBaseReference;
import org.hl7.fhir.dstu2.model.api.IBaseResource;
import org.hl7.fhir.dstu2.model.api.ICompositeType;
import org.hl7.fhir.dstu2.model.api.IIdType;
public abstract class BaseReference extends Type implements IBaseReference, ICompositeType {
/**
* This is not a part of the "wire format" resource, but can be changed/accessed by parsers
*/
private transient IBaseResource resource;
public BaseReference(String theReference) {
setReference(theReference);
}
public BaseReference(IdType theReference) {
if (theReference != null) {
setReference(theReference.getValue());
} else {
setReference(null);
}
}
public BaseReference(IAnyResource theResource) {
resource = theResource;
}
public BaseReference() {
}
/**
* Retrieves the actual resource referenced by this reference. Note that the resource itself is not
* a part of the FHIR "wire format" and is never transmitted or receieved inline, but this property
* may be changed/accessed by parsers.
*/
public IBaseResource getResource() {
return resource;
}
@Override
public IIdType getReferenceElement() {
return new IdType(getReference());
}
abstract String getReference();
/**
* Sets the actual resource referenced by this reference. Note that the resource itself is not
* a part of the FHIR "wire format" and is never transmitted or receieved inline, but this property
* may be changed/accessed by parsers.
*/
public void setResource(IBaseResource theResource) {
resource = theResource;
}
@Override
public boolean isEmpty() {
return resource == null && super.isEmpty();
}
}

View File

@ -0,0 +1,46 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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.dstu2.model.api.IAnyResource;
import org.hl7.fhir.dstu2.model.api.IIdType;
public abstract class BaseResource extends Base implements IAnyResource {
private static final long serialVersionUID = 1L;
/**
* @param value The logical id of the resource, as used in the url for the resoure. Once assigned, this value never changes.
*/
public BaseResource setId(IIdType value) {
if (value == null) {
setIdElement((IdType)null);
} else if (value instanceof IdType) {
setIdElement((IdType) value);
} else {
setIdElement(new IdType(value.getValue()));
}
return this;
}
public abstract BaseResource setIdElement(IdType theIdType);
}

View File

@ -0,0 +1,441 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Wed, Jul 13, 2016 05:32+1000 for FHIR v1.0.2
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hl7.fhir.dstu2.model.annotations.Child;
import org.hl7.fhir.dstu2.model.annotations.Description;
import org.hl7.fhir.dstu2.model.annotations.ResourceDef;
import org.hl7.fhir.dstu2.model.annotations.SearchParamDefinition;
import org.hl7.fhir.exceptions.FHIRException;
/**
* Basic is used for handling concepts not yet defined in FHIR, narrative-only resources that don't map to an existing resource, and custom resources not appropriate for inclusion in the FHIR specification.
*/
@ResourceDef(name="Basic", profile="http://hl7.org/fhir/Profile/Basic")
public class Basic extends DomainResource {
/**
* Identifier assigned to the resource for business purposes, outside the context of FHIR.
*/
@Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Business identifier", formalDefinition="Identifier assigned to the resource for business purposes, outside the context of FHIR." )
protected List<Identifier> identifier;
/**
* Identifies the 'type' of resource - equivalent to the resource name for other resources.
*/
@Child(name = "code", type = {CodeableConcept.class}, order=1, min=1, max=1, modifier=true, summary=true)
@Description(shortDefinition="Kind of Resource", formalDefinition="Identifies the 'type' of resource - equivalent to the resource name for other resources." )
protected CodeableConcept code;
/**
* Identifies the patient, practitioner, device or any other resource that is the "focus" of this resource.
*/
@Child(name = "subject", type = {}, order=2, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Identifies the focus of this resource", formalDefinition="Identifies the patient, practitioner, device or any other resource that is the \"focus\" of this resource." )
protected Reference subject;
/**
* The actual object that is the target of the reference (Identifies the patient, practitioner, device or any other resource that is the "focus" of this resource.)
*/
protected Resource subjectTarget;
/**
* Indicates who was responsible for creating the resource instance.
*/
@Child(name = "author", type = {Practitioner.class, Patient.class, RelatedPerson.class}, order=3, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Who created", formalDefinition="Indicates who was responsible for creating the resource instance." )
protected Reference author;
/**
* The actual object that is the target of the reference (Indicates who was responsible for creating the resource instance.)
*/
protected Resource authorTarget;
/**
* Identifies when the resource was first created.
*/
@Child(name = "created", type = {DateType.class}, order=4, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="When created", formalDefinition="Identifies when the resource was first created." )
protected DateType created;
private static final long serialVersionUID = 916539354L;
/*
* Constructor
*/
public Basic() {
super();
}
/*
* Constructor
*/
public Basic(CodeableConcept code) {
super();
this.code = code;
}
/**
* @return {@link #identifier} (Identifier assigned to the resource for business purposes, outside the context of FHIR.)
*/
public List<Identifier> getIdentifier() {
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
return this.identifier;
}
public boolean hasIdentifier() {
if (this.identifier == null)
return false;
for (Identifier item : this.identifier)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #identifier} (Identifier assigned to the resource for business purposes, outside the context of FHIR.)
*/
// syntactic sugar
public Identifier addIdentifier() { //3
Identifier t = new Identifier();
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return t;
}
// syntactic sugar
public Basic addIdentifier(Identifier t) { //3
if (t == null)
return this;
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return this;
}
/**
* @return {@link #code} (Identifies the 'type' of resource - equivalent to the resource name for other resources.)
*/
public CodeableConcept getCode() {
if (this.code == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Basic.code");
else if (Configuration.doAutoCreate())
this.code = new CodeableConcept(); // cc
return this.code;
}
public boolean hasCode() {
return this.code != null && !this.code.isEmpty();
}
/**
* @param value {@link #code} (Identifies the 'type' of resource - equivalent to the resource name for other resources.)
*/
public Basic setCode(CodeableConcept value) {
this.code = value;
return this;
}
/**
* @return {@link #subject} (Identifies the patient, practitioner, device or any other resource that is the "focus" of this resource.)
*/
public Reference getSubject() {
if (this.subject == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Basic.subject");
else if (Configuration.doAutoCreate())
this.subject = new Reference(); // cc
return this.subject;
}
public boolean hasSubject() {
return this.subject != null && !this.subject.isEmpty();
}
/**
* @param value {@link #subject} (Identifies the patient, practitioner, device or any other resource that is the "focus" of this resource.)
*/
public Basic setSubject(Reference value) {
this.subject = value;
return this;
}
/**
* @return {@link #subject} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Identifies the patient, practitioner, device or any other resource that is the "focus" of this resource.)
*/
public Resource getSubjectTarget() {
return this.subjectTarget;
}
/**
* @param value {@link #subject} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Identifies the patient, practitioner, device or any other resource that is the "focus" of this resource.)
*/
public Basic setSubjectTarget(Resource value) {
this.subjectTarget = value;
return this;
}
/**
* @return {@link #author} (Indicates who was responsible for creating the resource instance.)
*/
public Reference getAuthor() {
if (this.author == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Basic.author");
else if (Configuration.doAutoCreate())
this.author = new Reference(); // cc
return this.author;
}
public boolean hasAuthor() {
return this.author != null && !this.author.isEmpty();
}
/**
* @param value {@link #author} (Indicates who was responsible for creating the resource instance.)
*/
public Basic setAuthor(Reference value) {
this.author = value;
return this;
}
/**
* @return {@link #author} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (Indicates who was responsible for creating the resource instance.)
*/
public Resource getAuthorTarget() {
return this.authorTarget;
}
/**
* @param value {@link #author} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (Indicates who was responsible for creating the resource instance.)
*/
public Basic setAuthorTarget(Resource value) {
this.authorTarget = value;
return this;
}
/**
* @return {@link #created} (Identifies when the resource was first created.). This is the underlying object with id, value and extensions. The accessor "getCreated" gives direct access to the value
*/
public DateType getCreatedElement() {
if (this.created == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Basic.created");
else if (Configuration.doAutoCreate())
this.created = new DateType(); // bb
return this.created;
}
public boolean hasCreatedElement() {
return this.created != null && !this.created.isEmpty();
}
public boolean hasCreated() {
return this.created != null && !this.created.isEmpty();
}
/**
* @param value {@link #created} (Identifies when the resource was first created.). This is the underlying object with id, value and extensions. The accessor "getCreated" gives direct access to the value
*/
public Basic setCreatedElement(DateType value) {
this.created = value;
return this;
}
/**
* @return Identifies when the resource was first created.
*/
public Date getCreated() {
return this.created == null ? null : this.created.getValue();
}
/**
* @param value Identifies when the resource was first created.
*/
public Basic setCreated(Date value) {
if (value == null)
this.created = null;
else {
if (this.created == null)
this.created = new DateType();
this.created.setValue(value);
}
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("identifier", "Identifier", "Identifier assigned to the resource for business purposes, outside the context of FHIR.", 0, java.lang.Integer.MAX_VALUE, identifier));
childrenList.add(new Property("code", "CodeableConcept", "Identifies the 'type' of resource - equivalent to the resource name for other resources.", 0, java.lang.Integer.MAX_VALUE, code));
childrenList.add(new Property("subject", "Reference(Any)", "Identifies the patient, practitioner, device or any other resource that is the \"focus\" of this resource.", 0, java.lang.Integer.MAX_VALUE, subject));
childrenList.add(new Property("author", "Reference(Practitioner|Patient|RelatedPerson)", "Indicates who was responsible for creating the resource instance.", 0, java.lang.Integer.MAX_VALUE, author));
childrenList.add(new Property("created", "date", "Identifies when the resource was first created.", 0, java.lang.Integer.MAX_VALUE, created));
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("identifier"))
this.getIdentifier().add(castToIdentifier(value));
else if (name.equals("code"))
this.code = castToCodeableConcept(value); // CodeableConcept
else if (name.equals("subject"))
this.subject = castToReference(value); // Reference
else if (name.equals("author"))
this.author = castToReference(value); // Reference
else if (name.equals("created"))
this.created = castToDate(value); // DateType
else
super.setProperty(name, value);
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("identifier")) {
return addIdentifier();
}
else if (name.equals("code")) {
this.code = new CodeableConcept();
return this.code;
}
else if (name.equals("subject")) {
this.subject = new Reference();
return this.subject;
}
else if (name.equals("author")) {
this.author = new Reference();
return this.author;
}
else if (name.equals("created")) {
throw new FHIRException("Cannot call addChild on a primitive type Basic.created");
}
else
return super.addChild(name);
}
public String fhirType() {
return "Basic";
}
public Basic copy() {
Basic dst = new Basic();
copyValues(dst);
if (identifier != null) {
dst.identifier = new ArrayList<Identifier>();
for (Identifier i : identifier)
dst.identifier.add(i.copy());
};
dst.code = code == null ? null : code.copy();
dst.subject = subject == null ? null : subject.copy();
dst.author = author == null ? null : author.copy();
dst.created = created == null ? null : created.copy();
return dst;
}
protected Basic typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof Basic))
return false;
Basic o = (Basic) other;
return compareDeep(identifier, o.identifier, true) && compareDeep(code, o.code, true) && compareDeep(subject, o.subject, true)
&& compareDeep(author, o.author, true) && compareDeep(created, o.created, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof Basic))
return false;
Basic o = (Basic) other;
return compareValues(created, o.created, true);
}
public boolean isEmpty() {
return super.isEmpty() && (identifier == null || identifier.isEmpty()) && (code == null || code.isEmpty())
&& (subject == null || subject.isEmpty()) && (author == null || author.isEmpty()) && (created == null || created.isEmpty())
;
}
@Override
public ResourceType getResourceType() {
return ResourceType.Basic;
}
@SearchParamDefinition(name="identifier", path="Basic.identifier", description="Business identifier", type="token" )
public static final String SP_IDENTIFIER = "identifier";
@SearchParamDefinition(name="code", path="Basic.code", description="Kind of Resource", type="token" )
public static final String SP_CODE = "code";
@SearchParamDefinition(name="subject", path="Basic.subject", description="Identifies the focus of this resource", type="reference" )
public static final String SP_SUBJECT = "subject";
@SearchParamDefinition(name="created", path="Basic.created", description="When created", type="date" )
public static final String SP_CREATED = "created";
@SearchParamDefinition(name="patient", path="Basic.subject", description="Identifies the focus of this resource", type="reference" )
public static final String SP_PATIENT = "patient";
@SearchParamDefinition(name="author", path="Basic.author", description="Who created", type="reference" )
public static final String SP_AUTHOR = "author";
}

View File

@ -0,0 +1,269 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Wed, Jul 13, 2016 05:32+1000 for FHIR v1.0.2
import java.util.List;
import org.hl7.fhir.dstu2.model.annotations.Child;
import org.hl7.fhir.dstu2.model.annotations.Description;
import org.hl7.fhir.dstu2.model.annotations.ResourceDef;
import org.hl7.fhir.dstu2.model.annotations.SearchParamDefinition;
import org.hl7.fhir.dstu2.model.api.IBaseBinary;
import org.hl7.fhir.exceptions.FHIRException;
/**
* A binary resource can contain any content, whether text, image, pdf, zip archive, etc.
*/
@ResourceDef(name="Binary", profile="http://hl7.org/fhir/Profile/Binary")
public class Binary extends BaseBinary implements IBaseBinary {
/**
* MimeType of the binary content represented as a standard MimeType (BCP 13).
*/
@Child(name = "contentType", type = {CodeType.class}, order=0, min=1, max=1, modifier=false, summary=true)
@Description(shortDefinition="MimeType of the binary content", formalDefinition="MimeType of the binary content represented as a standard MimeType (BCP 13)." )
protected CodeType contentType;
/**
* The actual content, base64 encoded.
*/
@Child(name = "content", type = {Base64BinaryType.class}, order=1, min=1, max=1, modifier=false, summary=true)
@Description(shortDefinition="The actual content", formalDefinition="The actual content, base64 encoded." )
protected Base64BinaryType content;
private static final long serialVersionUID = 974764407L;
/*
* Constructor
*/
public Binary() {
super();
}
/*
* Constructor
*/
public Binary(CodeType contentType, Base64BinaryType content) {
super();
this.contentType = contentType;
this.content = content;
}
/**
* @return {@link #contentType} (MimeType of the binary content represented as a standard MimeType (BCP 13).). This is the underlying object with id, value and extensions. The accessor "getContentType" gives direct access to the value
*/
public CodeType getContentTypeElement() {
if (this.contentType == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Binary.contentType");
else if (Configuration.doAutoCreate())
this.contentType = new CodeType(); // bb
return this.contentType;
}
public boolean hasContentTypeElement() {
return this.contentType != null && !this.contentType.isEmpty();
}
public boolean hasContentType() {
return this.contentType != null && !this.contentType.isEmpty();
}
/**
* @param value {@link #contentType} (MimeType of the binary content represented as a standard MimeType (BCP 13).). This is the underlying object with id, value and extensions. The accessor "getContentType" gives direct access to the value
*/
public Binary setContentTypeElement(CodeType value) {
this.contentType = value;
return this;
}
/**
* @return MimeType of the binary content represented as a standard MimeType (BCP 13).
*/
public String getContentType() {
return this.contentType == null ? null : this.contentType.getValue();
}
/**
* @param value MimeType of the binary content represented as a standard MimeType (BCP 13).
*/
public Binary setContentType(String value) {
if (this.contentType == null)
this.contentType = new CodeType();
this.contentType.setValue(value);
return this;
}
/**
* @return {@link #content} (The actual content, base64 encoded.). This is the underlying object with id, value and extensions. The accessor "getContent" gives direct access to the value
*/
public Base64BinaryType getContentElement() {
if (this.content == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Binary.content");
else if (Configuration.doAutoCreate())
this.content = new Base64BinaryType(); // bb
return this.content;
}
public boolean hasContentElement() {
return this.content != null && !this.content.isEmpty();
}
public boolean hasContent() {
return this.content != null && !this.content.isEmpty();
}
/**
* @param value {@link #content} (The actual content, base64 encoded.). This is the underlying object with id, value and extensions. The accessor "getContent" gives direct access to the value
*/
public Binary setContentElement(Base64BinaryType value) {
this.content = value;
return this;
}
/**
* @return The actual content, base64 encoded.
*/
public byte[] getContent() {
return this.content == null ? null : this.content.getValue();
}
/**
* @param value The actual content, base64 encoded.
*/
public Binary setContent(byte[] value) {
if (this.content == null)
this.content = new Base64BinaryType();
this.content.setValue(value);
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("contentType", "code", "MimeType of the binary content represented as a standard MimeType (BCP 13).", 0, java.lang.Integer.MAX_VALUE, contentType));
childrenList.add(new Property("content", "base64Binary", "The actual content, base64 encoded.", 0, java.lang.Integer.MAX_VALUE, content));
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("contentType"))
this.contentType = castToCode(value); // CodeType
else if (name.equals("content"))
this.content = castToBase64Binary(value); // Base64BinaryType
else
super.setProperty(name, value);
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("contentType")) {
throw new FHIRException("Cannot call addChild on a primitive type Binary.contentType");
}
else if (name.equals("content")) {
throw new FHIRException("Cannot call addChild on a primitive type Binary.content");
}
else
return super.addChild(name);
}
public String fhirType() {
return "Binary";
}
public Binary copy() {
Binary dst = new Binary();
copyValues(dst);
dst.contentType = contentType == null ? null : contentType.copy();
dst.content = content == null ? null : content.copy();
return dst;
}
protected Binary typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof Binary))
return false;
Binary o = (Binary) other;
return compareDeep(contentType, o.contentType, true) && compareDeep(content, o.content, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof Binary))
return false;
Binary o = (Binary) other;
return compareValues(contentType, o.contentType, true) && compareValues(content, o.content, true);
}
public boolean isEmpty() {
return super.isEmpty() && (contentType == null || contentType.isEmpty()) && (content == null || content.isEmpty())
;
}
@Override
public ResourceType getResourceType() {
return ResourceType.Binary;
}
@SearchParamDefinition(name="contenttype", path="Binary.contentType", description="MimeType of the binary content", type="token" )
public static final String SP_CONTENTTYPE = "contenttype";
}

View File

@ -0,0 +1,498 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Wed, Jul 13, 2016 05:32+1000 for FHIR v1.0.2
import java.util.ArrayList;
import java.util.List;
import org.hl7.fhir.dstu2.model.annotations.Child;
import org.hl7.fhir.dstu2.model.annotations.Description;
import org.hl7.fhir.dstu2.model.annotations.ResourceDef;
import org.hl7.fhir.dstu2.model.annotations.SearchParamDefinition;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.utilities.Utilities;
/**
* Record details about the anatomical location of a specimen or body part. This resource may be used when a coded concept does not provide the necessary detail needed for the use case.
*/
@ResourceDef(name="BodySite", profile="http://hl7.org/fhir/Profile/BodySite")
public class BodySite extends DomainResource {
/**
* The person to which the body site belongs.
*/
@Child(name = "patient", type = {Patient.class}, order=0, min=1, max=1, modifier=false, summary=true)
@Description(shortDefinition="Patient", formalDefinition="The person to which the body site belongs." )
protected Reference patient;
/**
* The actual object that is the target of the reference (The person to which the body site belongs.)
*/
protected Patient patientTarget;
/**
* Identifier for this instance of the anatomical location.
*/
@Child(name = "identifier", type = {Identifier.class}, order=1, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Bodysite identifier", formalDefinition="Identifier for this instance of the anatomical location." )
protected List<Identifier> identifier;
/**
* Named anatomical location - ideally coded where possible.
*/
@Child(name = "code", type = {CodeableConcept.class}, order=2, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Named anatomical location", formalDefinition="Named anatomical location - ideally coded where possible." )
protected CodeableConcept code;
/**
* Modifier to refine the anatomical location. These include modifiers for laterality, relative location, directionality, number, and plane.
*/
@Child(name = "modifier", type = {CodeableConcept.class}, order=3, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
@Description(shortDefinition="Modification to location code", formalDefinition="Modifier to refine the anatomical location. These include modifiers for laterality, relative location, directionality, number, and plane." )
protected List<CodeableConcept> modifier;
/**
* Description of anatomical location.
*/
@Child(name = "description", type = {StringType.class}, order=4, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="The Description of anatomical location", formalDefinition="Description of anatomical location." )
protected StringType description;
/**
* Image or images used to identify a location.
*/
@Child(name = "image", type = {Attachment.class}, order=5, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=false)
@Description(shortDefinition="Attached images", formalDefinition="Image or images used to identify a location." )
protected List<Attachment> image;
private static final long serialVersionUID = 1568109920L;
/*
* Constructor
*/
public BodySite() {
super();
}
/*
* Constructor
*/
public BodySite(Reference patient) {
super();
this.patient = patient;
}
/**
* @return {@link #patient} (The person to which the body site belongs.)
*/
public Reference getPatient() {
if (this.patient == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create BodySite.patient");
else if (Configuration.doAutoCreate())
this.patient = new Reference(); // cc
return this.patient;
}
public boolean hasPatient() {
return this.patient != null && !this.patient.isEmpty();
}
/**
* @param value {@link #patient} (The person to which the body site belongs.)
*/
public BodySite setPatient(Reference value) {
this.patient = value;
return this;
}
/**
* @return {@link #patient} The actual object that is the target of the reference. The reference library doesn't populate this, but you can use it to hold the resource if you resolve it. (The person to which the body site belongs.)
*/
public Patient getPatientTarget() {
if (this.patientTarget == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create BodySite.patient");
else if (Configuration.doAutoCreate())
this.patientTarget = new Patient(); // aa
return this.patientTarget;
}
/**
* @param value {@link #patient} The actual object that is the target of the reference. The reference library doesn't use these, but you can use it to hold the resource if you resolve it. (The person to which the body site belongs.)
*/
public BodySite setPatientTarget(Patient value) {
this.patientTarget = value;
return this;
}
/**
* @return {@link #identifier} (Identifier for this instance of the anatomical location.)
*/
public List<Identifier> getIdentifier() {
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
return this.identifier;
}
public boolean hasIdentifier() {
if (this.identifier == null)
return false;
for (Identifier item : this.identifier)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #identifier} (Identifier for this instance of the anatomical location.)
*/
// syntactic sugar
public Identifier addIdentifier() { //3
Identifier t = new Identifier();
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return t;
}
// syntactic sugar
public BodySite addIdentifier(Identifier t) { //3
if (t == null)
return this;
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return this;
}
/**
* @return {@link #code} (Named anatomical location - ideally coded where possible.)
*/
public CodeableConcept getCode() {
if (this.code == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create BodySite.code");
else if (Configuration.doAutoCreate())
this.code = new CodeableConcept(); // cc
return this.code;
}
public boolean hasCode() {
return this.code != null && !this.code.isEmpty();
}
/**
* @param value {@link #code} (Named anatomical location - ideally coded where possible.)
*/
public BodySite setCode(CodeableConcept value) {
this.code = value;
return this;
}
/**
* @return {@link #modifier} (Modifier to refine the anatomical location. These include modifiers for laterality, relative location, directionality, number, and plane.)
*/
public List<CodeableConcept> getModifier() {
if (this.modifier == null)
this.modifier = new ArrayList<CodeableConcept>();
return this.modifier;
}
public boolean hasModifier() {
if (this.modifier == null)
return false;
for (CodeableConcept item : this.modifier)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #modifier} (Modifier to refine the anatomical location. These include modifiers for laterality, relative location, directionality, number, and plane.)
*/
// syntactic sugar
public CodeableConcept addModifier() { //3
CodeableConcept t = new CodeableConcept();
if (this.modifier == null)
this.modifier = new ArrayList<CodeableConcept>();
this.modifier.add(t);
return t;
}
// syntactic sugar
public BodySite addModifier(CodeableConcept t) { //3
if (t == null)
return this;
if (this.modifier == null)
this.modifier = new ArrayList<CodeableConcept>();
this.modifier.add(t);
return this;
}
/**
* @return {@link #description} (Description of anatomical location.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value
*/
public StringType getDescriptionElement() {
if (this.description == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create BodySite.description");
else if (Configuration.doAutoCreate())
this.description = new StringType(); // bb
return this.description;
}
public boolean hasDescriptionElement() {
return this.description != null && !this.description.isEmpty();
}
public boolean hasDescription() {
return this.description != null && !this.description.isEmpty();
}
/**
* @param value {@link #description} (Description of anatomical location.). This is the underlying object with id, value and extensions. The accessor "getDescription" gives direct access to the value
*/
public BodySite setDescriptionElement(StringType value) {
this.description = value;
return this;
}
/**
* @return Description of anatomical location.
*/
public String getDescription() {
return this.description == null ? null : this.description.getValue();
}
/**
* @param value Description of anatomical location.
*/
public BodySite setDescription(String value) {
if (Utilities.noString(value))
this.description = null;
else {
if (this.description == null)
this.description = new StringType();
this.description.setValue(value);
}
return this;
}
/**
* @return {@link #image} (Image or images used to identify a location.)
*/
public List<Attachment> getImage() {
if (this.image == null)
this.image = new ArrayList<Attachment>();
return this.image;
}
public boolean hasImage() {
if (this.image == null)
return false;
for (Attachment item : this.image)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #image} (Image or images used to identify a location.)
*/
// syntactic sugar
public Attachment addImage() { //3
Attachment t = new Attachment();
if (this.image == null)
this.image = new ArrayList<Attachment>();
this.image.add(t);
return t;
}
// syntactic sugar
public BodySite addImage(Attachment t) { //3
if (t == null)
return this;
if (this.image == null)
this.image = new ArrayList<Attachment>();
this.image.add(t);
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("patient", "Reference(Patient)", "The person to which the body site belongs.", 0, java.lang.Integer.MAX_VALUE, patient));
childrenList.add(new Property("identifier", "Identifier", "Identifier for this instance of the anatomical location.", 0, java.lang.Integer.MAX_VALUE, identifier));
childrenList.add(new Property("code", "CodeableConcept", "Named anatomical location - ideally coded where possible.", 0, java.lang.Integer.MAX_VALUE, code));
childrenList.add(new Property("modifier", "CodeableConcept", "Modifier to refine the anatomical location. These include modifiers for laterality, relative location, directionality, number, and plane.", 0, java.lang.Integer.MAX_VALUE, modifier));
childrenList.add(new Property("description", "string", "Description of anatomical location.", 0, java.lang.Integer.MAX_VALUE, description));
childrenList.add(new Property("image", "Attachment", "Image or images used to identify a location.", 0, java.lang.Integer.MAX_VALUE, image));
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("patient"))
this.patient = castToReference(value); // Reference
else if (name.equals("identifier"))
this.getIdentifier().add(castToIdentifier(value));
else if (name.equals("code"))
this.code = castToCodeableConcept(value); // CodeableConcept
else if (name.equals("modifier"))
this.getModifier().add(castToCodeableConcept(value));
else if (name.equals("description"))
this.description = castToString(value); // StringType
else if (name.equals("image"))
this.getImage().add(castToAttachment(value));
else
super.setProperty(name, value);
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("patient")) {
this.patient = new Reference();
return this.patient;
}
else if (name.equals("identifier")) {
return addIdentifier();
}
else if (name.equals("code")) {
this.code = new CodeableConcept();
return this.code;
}
else if (name.equals("modifier")) {
return addModifier();
}
else if (name.equals("description")) {
throw new FHIRException("Cannot call addChild on a primitive type BodySite.description");
}
else if (name.equals("image")) {
return addImage();
}
else
return super.addChild(name);
}
public String fhirType() {
return "BodySite";
}
public BodySite copy() {
BodySite dst = new BodySite();
copyValues(dst);
dst.patient = patient == null ? null : patient.copy();
if (identifier != null) {
dst.identifier = new ArrayList<Identifier>();
for (Identifier i : identifier)
dst.identifier.add(i.copy());
};
dst.code = code == null ? null : code.copy();
if (modifier != null) {
dst.modifier = new ArrayList<CodeableConcept>();
for (CodeableConcept i : modifier)
dst.modifier.add(i.copy());
};
dst.description = description == null ? null : description.copy();
if (image != null) {
dst.image = new ArrayList<Attachment>();
for (Attachment i : image)
dst.image.add(i.copy());
};
return dst;
}
protected BodySite typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof BodySite))
return false;
BodySite o = (BodySite) other;
return compareDeep(patient, o.patient, true) && compareDeep(identifier, o.identifier, true) && compareDeep(code, o.code, true)
&& compareDeep(modifier, o.modifier, true) && compareDeep(description, o.description, true) && compareDeep(image, o.image, true)
;
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof BodySite))
return false;
BodySite o = (BodySite) other;
return compareValues(description, o.description, true);
}
public boolean isEmpty() {
return super.isEmpty() && (patient == null || patient.isEmpty()) && (identifier == null || identifier.isEmpty())
&& (code == null || code.isEmpty()) && (modifier == null || modifier.isEmpty()) && (description == null || description.isEmpty())
&& (image == null || image.isEmpty());
}
@Override
public ResourceType getResourceType() {
return ResourceType.BodySite;
}
@SearchParamDefinition(name="identifier", path="BodySite.identifier", description="Identifier for this instance of the anatomical location", type="token" )
public static final String SP_IDENTIFIER = "identifier";
@SearchParamDefinition(name="code", path="BodySite.code", description="Named anatomical location", type="token" )
public static final String SP_CODE = "code";
@SearchParamDefinition(name="patient", path="BodySite.patient", description="Patient to whom bodysite belongs", type="reference" )
public static final String SP_PATIENT = "patient";
}

View File

@ -0,0 +1,114 @@
/*
Copyright (c) 2011+, HL7, Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/**
*
*/
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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.dstu2.model.annotations.DatatypeDef;
import org.hl7.fhir.dstu2.model.api.IBaseBooleanDatatype;
/**
* Primitive type "boolean" in FHIR "true" or "false"
*/
@DatatypeDef(name="boolean")
public class BooleanType extends PrimitiveType<Boolean> implements IBaseBooleanDatatype {
private static final long serialVersionUID = 3L;
public BooleanType() {
super();
}
public BooleanType(boolean theBoolean) {
super();
setValue(theBoolean);
}
public BooleanType(Boolean theBoolean) {
super();
setValue(theBoolean);
}
public BooleanType(String value) {
super();
setValueAsString(value);
}
protected Boolean parse(String theValue) {
String value = theValue.trim();
if ("true".equals(value)) {
return Boolean.TRUE;
} else if ("false".equals(value)) {
return Boolean.FALSE;
} else {
throw new IllegalArgumentException("Invalid boolean string: '" + theValue + "'");
}
}
protected String encode(Boolean theValue) {
if (Boolean.TRUE.equals(theValue)) {
return "true";
} else {
return "false";
}
}
public BooleanType copy() {
return new BooleanType(getValue());
}
public String fhirType() {
return "boolean";
}
public boolean booleanValue() {
return getValue().booleanValue();
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,97 @@
/*
Copyright (c) 2011+, HL7, Inc
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import static org.apache.commons.lang3.StringUtils.defaultString;
import org.hl7.fhir.dstu2.model.annotations.DatatypeDef;
/**
* Primitive type "code" in FHIR, when not bound to an enumerated list of codes
*/
@DatatypeDef(name="code", profileOf=StringType.class)
public class CodeType extends StringType implements Comparable<CodeType> {
private static final long serialVersionUID = 3L;
public CodeType() {
super();
}
public CodeType(String theCode) {
setValue(theCode);
}
public int compareTo(CodeType theCode) {
if (theCode == null) {
return 1;
}
return defaultString(getValue()).compareTo(defaultString(theCode.getValue()));
}
@Override
protected String parse(String theValue) {
return theValue.trim();
}
@Override
protected String encode(String theValue) {
return theValue;
}
@Override
public CodeType copy() {
return new CodeType(getValue());
}
public String fhirType() {
return "code";
}
}

View File

@ -0,0 +1,257 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Wed, Jul 13, 2016 05:32+1000 for FHIR v1.0.2
import java.util.ArrayList;
import java.util.List;
import org.hl7.fhir.dstu2.model.annotations.Child;
import org.hl7.fhir.dstu2.model.annotations.DatatypeDef;
import org.hl7.fhir.dstu2.model.annotations.Description;
import org.hl7.fhir.dstu2.model.api.ICompositeType;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.utilities.Utilities;
/**
* A concept that may be defined by a formal reference to a terminology or ontology or may be provided by text.
*/
@DatatypeDef(name="CodeableConcept")
public class CodeableConcept extends Type implements ICompositeType {
/**
* A reference to a code defined by a terminology system.
*/
@Child(name = "coding", type = {Coding.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Code defined by a terminology system", formalDefinition="A reference to a code defined by a terminology system." )
protected List<Coding> coding;
/**
* A human language representation of the concept as seen/selected/uttered by the user who entered the data and/or which represents the intended meaning of the user.
*/
@Child(name = "text", type = {StringType.class}, order=1, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Plain text representation of the concept", formalDefinition="A human language representation of the concept as seen/selected/uttered by the user who entered the data and/or which represents the intended meaning of the user." )
protected StringType text;
private static final long serialVersionUID = 760353246L;
/*
* Constructor
*/
public CodeableConcept() {
super();
}
/**
* @return {@link #coding} (A reference to a code defined by a terminology system.)
*/
public List<Coding> getCoding() {
if (this.coding == null)
this.coding = new ArrayList<Coding>();
return this.coding;
}
public boolean hasCoding() {
if (this.coding == null)
return false;
for (Coding item : this.coding)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #coding} (A reference to a code defined by a terminology system.)
*/
// syntactic sugar
public Coding addCoding() { //3
Coding t = new Coding();
if (this.coding == null)
this.coding = new ArrayList<Coding>();
this.coding.add(t);
return t;
}
// syntactic sugar
public CodeableConcept addCoding(Coding t) { //3
if (t == null)
return this;
if (this.coding == null)
this.coding = new ArrayList<Coding>();
this.coding.add(t);
return this;
}
/**
* @return {@link #text} (A human language representation of the concept as seen/selected/uttered by the user who entered the data and/or which represents the intended meaning of the user.). This is the underlying object with id, value and extensions. The accessor "getText" gives direct access to the value
*/
public StringType getTextElement() {
if (this.text == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create CodeableConcept.text");
else if (Configuration.doAutoCreate())
this.text = new StringType(); // bb
return this.text;
}
public boolean hasTextElement() {
return this.text != null && !this.text.isEmpty();
}
public boolean hasText() {
return this.text != null && !this.text.isEmpty();
}
/**
* @param value {@link #text} (A human language representation of the concept as seen/selected/uttered by the user who entered the data and/or which represents the intended meaning of the user.). This is the underlying object with id, value and extensions. The accessor "getText" gives direct access to the value
*/
public CodeableConcept setTextElement(StringType value) {
this.text = value;
return this;
}
/**
* @return A human language representation of the concept as seen/selected/uttered by the user who entered the data and/or which represents the intended meaning of the user.
*/
public String getText() {
return this.text == null ? null : this.text.getValue();
}
/**
* @param value A human language representation of the concept as seen/selected/uttered by the user who entered the data and/or which represents the intended meaning of the user.
*/
public CodeableConcept setText(String value) {
if (Utilities.noString(value))
this.text = null;
else {
if (this.text == null)
this.text = new StringType();
this.text.setValue(value);
}
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("coding", "Coding", "A reference to a code defined by a terminology system.", 0, java.lang.Integer.MAX_VALUE, coding));
childrenList.add(new Property("text", "string", "A human language representation of the concept as seen/selected/uttered by the user who entered the data and/or which represents the intended meaning of the user.", 0, java.lang.Integer.MAX_VALUE, text));
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("coding"))
this.getCoding().add(castToCoding(value));
else if (name.equals("text"))
this.text = castToString(value); // StringType
else
super.setProperty(name, value);
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("coding")) {
return addCoding();
}
else if (name.equals("text")) {
throw new FHIRException("Cannot call addChild on a primitive type CodeableConcept.text");
}
else
return super.addChild(name);
}
public String fhirType() {
return "CodeableConcept";
}
public CodeableConcept copy() {
CodeableConcept dst = new CodeableConcept();
copyValues(dst);
if (coding != null) {
dst.coding = new ArrayList<Coding>();
for (Coding i : coding)
dst.coding.add(i.copy());
};
dst.text = text == null ? null : text.copy();
return dst;
}
protected CodeableConcept typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof CodeableConcept))
return false;
CodeableConcept o = (CodeableConcept) other;
return compareDeep(coding, o.coding, true) && compareDeep(text, o.text, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof CodeableConcept))
return false;
CodeableConcept o = (CodeableConcept) other;
return compareValues(text, o.text, true);
}
public boolean isEmpty() {
return super.isEmpty() && (coding == null || coding.isEmpty()) && (text == null || text.isEmpty())
;
}
}

View File

@ -0,0 +1,450 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Wed, Jul 13, 2016 05:32+1000 for FHIR v1.0.2
import java.util.List;
import org.hl7.fhir.dstu2.model.annotations.Child;
import org.hl7.fhir.dstu2.model.annotations.DatatypeDef;
import org.hl7.fhir.dstu2.model.annotations.Description;
import org.hl7.fhir.dstu2.model.api.IBaseCoding;
import org.hl7.fhir.dstu2.model.api.ICompositeType;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.utilities.Utilities;
/**
* A reference to a code defined by a terminology system.
*/
@DatatypeDef(name="Coding")
public class Coding extends Type implements IBaseCoding, ICompositeType {
/**
* The identification of the code system that defines the meaning of the symbol in the code.
*/
@Child(name = "system", type = {UriType.class}, order=0, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Identity of the terminology system", formalDefinition="The identification of the code system that defines the meaning of the symbol in the code." )
protected UriType system;
/**
* The version of the code system which was used when choosing this code. Note that a well-maintained code system does not need the version reported, because the meaning of codes is consistent across versions. However this cannot consistently be assured. and when the meaning is not guaranteed to be consistent, the version SHOULD be exchanged.
*/
@Child(name = "version", type = {StringType.class}, order=1, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Version of the system - if relevant", formalDefinition="The version of the code system which was used when choosing this code. Note that a well-maintained code system does not need the version reported, because the meaning of codes is consistent across versions. However this cannot consistently be assured. and when the meaning is not guaranteed to be consistent, the version SHOULD be exchanged." )
protected StringType version;
/**
* A symbol in syntax defined by the system. The symbol may be a predefined code or an expression in a syntax defined by the coding system (e.g. post-coordination).
*/
@Child(name = "code", type = {CodeType.class}, order=2, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Symbol in syntax defined by the system", formalDefinition="A symbol in syntax defined by the system. The symbol may be a predefined code or an expression in a syntax defined by the coding system (e.g. post-coordination)." )
protected CodeType code;
/**
* A representation of the meaning of the code in the system, following the rules of the system.
*/
@Child(name = "display", type = {StringType.class}, order=3, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Representation defined by the system", formalDefinition="A representation of the meaning of the code in the system, following the rules of the system." )
protected StringType display;
/**
* Indicates that this coding was chosen by a user directly - i.e. off a pick list of available items (codes or displays).
*/
@Child(name = "userSelected", type = {BooleanType.class}, order=4, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="If this coding was chosen directly by the user", formalDefinition="Indicates that this coding was chosen by a user directly - i.e. off a pick list of available items (codes or displays)." )
protected BooleanType userSelected;
private static final long serialVersionUID = -1417514061L;
/*
* Constructor
*/
public Coding() {
super();
}
/**
* @return {@link #system} (The identification of the code system that defines the meaning of the symbol in the code.). This is the underlying object with id, value and extensions. The accessor "getSystem" gives direct access to the value
*/
public UriType getSystemElement() {
if (this.system == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Coding.system");
else if (Configuration.doAutoCreate())
this.system = new UriType(); // bb
return this.system;
}
public boolean hasSystemElement() {
return this.system != null && !this.system.isEmpty();
}
public boolean hasSystem() {
return this.system != null && !this.system.isEmpty();
}
/**
* @param value {@link #system} (The identification of the code system that defines the meaning of the symbol in the code.). This is the underlying object with id, value and extensions. The accessor "getSystem" gives direct access to the value
*/
public Coding setSystemElement(UriType value) {
this.system = value;
return this;
}
/**
* @return The identification of the code system that defines the meaning of the symbol in the code.
*/
public String getSystem() {
return this.system == null ? null : this.system.getValue();
}
/**
* @param value The identification of the code system that defines the meaning of the symbol in the code.
*/
public Coding setSystem(String value) {
if (Utilities.noString(value))
this.system = null;
else {
if (this.system == null)
this.system = new UriType();
this.system.setValue(value);
}
return this;
}
/**
* @return {@link #version} (The version of the code system which was used when choosing this code. Note that a well-maintained code system does not need the version reported, because the meaning of codes is consistent across versions. However this cannot consistently be assured. and when the meaning is not guaranteed to be consistent, the version SHOULD be exchanged.). This is the underlying object with id, value and extensions. The accessor "getVersion" gives direct access to the value
*/
public StringType getVersionElement() {
if (this.version == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Coding.version");
else if (Configuration.doAutoCreate())
this.version = new StringType(); // bb
return this.version;
}
public boolean hasVersionElement() {
return this.version != null && !this.version.isEmpty();
}
public boolean hasVersion() {
return this.version != null && !this.version.isEmpty();
}
/**
* @param value {@link #version} (The version of the code system which was used when choosing this code. Note that a well-maintained code system does not need the version reported, because the meaning of codes is consistent across versions. However this cannot consistently be assured. and when the meaning is not guaranteed to be consistent, the version SHOULD be exchanged.). This is the underlying object with id, value and extensions. The accessor "getVersion" gives direct access to the value
*/
public Coding setVersionElement(StringType value) {
this.version = value;
return this;
}
/**
* @return The version of the code system which was used when choosing this code. Note that a well-maintained code system does not need the version reported, because the meaning of codes is consistent across versions. However this cannot consistently be assured. and when the meaning is not guaranteed to be consistent, the version SHOULD be exchanged.
*/
public String getVersion() {
return this.version == null ? null : this.version.getValue();
}
/**
* @param value The version of the code system which was used when choosing this code. Note that a well-maintained code system does not need the version reported, because the meaning of codes is consistent across versions. However this cannot consistently be assured. and when the meaning is not guaranteed to be consistent, the version SHOULD be exchanged.
*/
public Coding setVersion(String value) {
if (Utilities.noString(value))
this.version = null;
else {
if (this.version == null)
this.version = new StringType();
this.version.setValue(value);
}
return this;
}
/**
* @return {@link #code} (A symbol in syntax defined by the system. The symbol may be a predefined code or an expression in a syntax defined by the coding system (e.g. post-coordination).). This is the underlying object with id, value and extensions. The accessor "getCode" gives direct access to the value
*/
public CodeType getCodeElement() {
if (this.code == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Coding.code");
else if (Configuration.doAutoCreate())
this.code = new CodeType(); // bb
return this.code;
}
public boolean hasCodeElement() {
return this.code != null && !this.code.isEmpty();
}
public boolean hasCode() {
return this.code != null && !this.code.isEmpty();
}
/**
* @param value {@link #code} (A symbol in syntax defined by the system. The symbol may be a predefined code or an expression in a syntax defined by the coding system (e.g. post-coordination).). This is the underlying object with id, value and extensions. The accessor "getCode" gives direct access to the value
*/
public Coding setCodeElement(CodeType value) {
this.code = value;
return this;
}
/**
* @return A symbol in syntax defined by the system. The symbol may be a predefined code or an expression in a syntax defined by the coding system (e.g. post-coordination).
*/
public String getCode() {
return this.code == null ? null : this.code.getValue();
}
/**
* @param value A symbol in syntax defined by the system. The symbol may be a predefined code or an expression in a syntax defined by the coding system (e.g. post-coordination).
*/
public Coding setCode(String value) {
if (Utilities.noString(value))
this.code = null;
else {
if (this.code == null)
this.code = new CodeType();
this.code.setValue(value);
}
return this;
}
/**
* @return {@link #display} (A representation of the meaning of the code in the system, following the rules of the system.). This is the underlying object with id, value and extensions. The accessor "getDisplay" gives direct access to the value
*/
public StringType getDisplayElement() {
if (this.display == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Coding.display");
else if (Configuration.doAutoCreate())
this.display = new StringType(); // bb
return this.display;
}
public boolean hasDisplayElement() {
return this.display != null && !this.display.isEmpty();
}
public boolean hasDisplay() {
return this.display != null && !this.display.isEmpty();
}
/**
* @param value {@link #display} (A representation of the meaning of the code in the system, following the rules of the system.). This is the underlying object with id, value and extensions. The accessor "getDisplay" gives direct access to the value
*/
public Coding setDisplayElement(StringType value) {
this.display = value;
return this;
}
/**
* @return A representation of the meaning of the code in the system, following the rules of the system.
*/
public String getDisplay() {
return this.display == null ? null : this.display.getValue();
}
/**
* @param value A representation of the meaning of the code in the system, following the rules of the system.
*/
public Coding setDisplay(String value) {
if (Utilities.noString(value))
this.display = null;
else {
if (this.display == null)
this.display = new StringType();
this.display.setValue(value);
}
return this;
}
/**
* @return {@link #userSelected} (Indicates that this coding was chosen by a user directly - i.e. off a pick list of available items (codes or displays).). This is the underlying object with id, value and extensions. The accessor "getUserSelected" gives direct access to the value
*/
public BooleanType getUserSelectedElement() {
if (this.userSelected == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create Coding.userSelected");
else if (Configuration.doAutoCreate())
this.userSelected = new BooleanType(); // bb
return this.userSelected;
}
public boolean hasUserSelectedElement() {
return this.userSelected != null && !this.userSelected.isEmpty();
}
public boolean hasUserSelected() {
return this.userSelected != null && !this.userSelected.isEmpty();
}
/**
* @param value {@link #userSelected} (Indicates that this coding was chosen by a user directly - i.e. off a pick list of available items (codes or displays).). This is the underlying object with id, value and extensions. The accessor "getUserSelected" gives direct access to the value
*/
public Coding setUserSelectedElement(BooleanType value) {
this.userSelected = value;
return this;
}
/**
* @return Indicates that this coding was chosen by a user directly - i.e. off a pick list of available items (codes or displays).
*/
public boolean getUserSelected() {
return this.userSelected == null || this.userSelected.isEmpty() ? false : this.userSelected.getValue();
}
/**
* @param value Indicates that this coding was chosen by a user directly - i.e. off a pick list of available items (codes or displays).
*/
public Coding setUserSelected(boolean value) {
if (this.userSelected == null)
this.userSelected = new BooleanType();
this.userSelected.setValue(value);
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("system", "uri", "The identification of the code system that defines the meaning of the symbol in the code.", 0, java.lang.Integer.MAX_VALUE, system));
childrenList.add(new Property("version", "string", "The version of the code system which was used when choosing this code. Note that a well-maintained code system does not need the version reported, because the meaning of codes is consistent across versions. However this cannot consistently be assured. and when the meaning is not guaranteed to be consistent, the version SHOULD be exchanged.", 0, java.lang.Integer.MAX_VALUE, version));
childrenList.add(new Property("code", "code", "A symbol in syntax defined by the system. The symbol may be a predefined code or an expression in a syntax defined by the coding system (e.g. post-coordination).", 0, java.lang.Integer.MAX_VALUE, code));
childrenList.add(new Property("display", "string", "A representation of the meaning of the code in the system, following the rules of the system.", 0, java.lang.Integer.MAX_VALUE, display));
childrenList.add(new Property("userSelected", "boolean", "Indicates that this coding was chosen by a user directly - i.e. off a pick list of available items (codes or displays).", 0, java.lang.Integer.MAX_VALUE, userSelected));
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("system"))
this.system = castToUri(value); // UriType
else if (name.equals("version"))
this.version = castToString(value); // StringType
else if (name.equals("code"))
this.code = castToCode(value); // CodeType
else if (name.equals("display"))
this.display = castToString(value); // StringType
else if (name.equals("userSelected"))
this.userSelected = castToBoolean(value); // BooleanType
else
super.setProperty(name, value);
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("system")) {
throw new FHIRException("Cannot call addChild on a primitive type Coding.system");
}
else if (name.equals("version")) {
throw new FHIRException("Cannot call addChild on a primitive type Coding.version");
}
else if (name.equals("code")) {
throw new FHIRException("Cannot call addChild on a primitive type Coding.code");
}
else if (name.equals("display")) {
throw new FHIRException("Cannot call addChild on a primitive type Coding.display");
}
else if (name.equals("userSelected")) {
throw new FHIRException("Cannot call addChild on a primitive type Coding.userSelected");
}
else
return super.addChild(name);
}
public String fhirType() {
return "Coding";
}
public Coding copy() {
Coding dst = new Coding();
copyValues(dst);
dst.system = system == null ? null : system.copy();
dst.version = version == null ? null : version.copy();
dst.code = code == null ? null : code.copy();
dst.display = display == null ? null : display.copy();
dst.userSelected = userSelected == null ? null : userSelected.copy();
return dst;
}
protected Coding typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof Coding))
return false;
Coding o = (Coding) other;
return compareDeep(system, o.system, true) && compareDeep(version, o.version, true) && compareDeep(code, o.code, true)
&& compareDeep(display, o.display, true) && compareDeep(userSelected, o.userSelected, true);
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof Coding))
return false;
Coding o = (Coding) other;
return compareValues(system, o.system, true) && compareValues(version, o.version, true) && compareValues(code, o.code, true)
&& compareValues(display, o.display, true) && compareValues(userSelected, o.userSelected, true);
}
public boolean isEmpty() {
return super.isEmpty() && (system == null || system.isEmpty()) && (version == null || version.isEmpty())
&& (code == null || code.isEmpty()) && (display == null || display.isEmpty()) && (userSelected == null || userSelected.isEmpty())
;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,131 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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.List;
import org.apache.commons.lang3.NotImplementedException;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.utilities.Utilities;
/**
* See http://www.healthintersections.com.au/?p=1941
*
* @author Grahame
*
*/
public class Comparison {
public class MatchProfile {
}
public static boolean matches(String c1, String c2, MatchProfile profile) {
if (Utilities.noString(c1) || Utilities.noString(c2))
return false;
c1 = Utilities.normalize(c1);
c2 = Utilities.normalize(c2);
return c1.equals(c2);
}
public static <T extends Enum<?>> boolean matches(Enumeration<T> e1, Enumeration<T> e2, MatchProfile profile) {
if (e1 == null || e2 == null)
return false;
return e1.getValue().equals(e2.getValue());
}
public static boolean matches(CodeableConcept c1, CodeableConcept c2, MatchProfile profile) throws FHIRException {
if (profile != null)
throw new NotImplementedException("Not Implemented Yet");
if (c1.getCoding().isEmpty() && c2.getCoding().isEmpty()) {
return matches(c1.getText(), c2.getText(), null);
} else {
// in the absence of specific guidance, we just require that all codes match
boolean ok = true;
for (Coding c : c1.getCoding()) {
ok = ok && inList(c2.getCoding(), c, null);
}
for (Coding c : c2.getCoding()) {
ok = ok && inList(c1.getCoding(), c, null);
}
return ok;
}
}
public static void merge(CodeableConcept dst, CodeableConcept src) {
if (dst.getTextElement() == null && src.getTextElement() != null)
dst.setTextElement(src.getTextElement());
}
public static boolean inList(List<Coding> list, Coding c, MatchProfile profile) {
for (Coding item : list) {
if (matches(item, c, profile))
return true;
}
return false;
}
public static boolean matches(Coding c1, Coding c2, MatchProfile profile) {
if (profile != null)
throw new NotImplementedException("Not Implemented Yet");
// in the absence of a profile, we ignore version
return matches(c1.getSystem(), c2.getSystem(), null) && matches(c1.getCode(), c2.getCode(), null);
}
public static boolean matches(Identifier i1, Identifier i2, MatchProfile profile) {
if (profile != null)
throw new NotImplementedException("Not Implemented Yet");
// in the absence of a profile, we ignore version
return matches(i1.getSystem(), i2.getSystem(), null) && matches(i1.getValue(), i2.getValue(), null);
}
public static void merge(Identifier dst, Identifier src) {
if (dst.getUseElement() == null && src.getUseElement() != null)
dst.setUseElement(src.getUseElement());
if (dst.getType() == null && src.getType() != null)
dst.setType(src.getType());
if (dst.getPeriod() == null && src.getPeriod() != null)
dst.setPeriod(src.getPeriod());
if (dst.getAssigner() == null && src.getAssigner() != null)
dst.setAssigner(src.getAssigner());
}
public static boolean matches(ContactPoint c1, ContactPoint c2, Object profile) {
if (profile != null)
throw new NotImplementedException("Not Implemented Yet");
// in the absence of a profile, we insist on system
return matches(c1.getSystemElement(), c2.getSystemElement(), null) && matches(c1.getValue(), c2.getValue(), null);
}
public static void merge(ContactPoint dst, ContactPoint src) {
if (dst.getUseElement() == null && src.getUseElement() != null)
dst.setUseElement(src.getUseElement());
if (dst.getPeriod() == null && src.getPeriod() != null)
dst.setPeriod(src.getPeriod());
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,127 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/**
* This class is created to help implementers deal with a change to
* the API that was made between versions 0.81 and 0.9
*
* The change is the behaviour of the .getX() where the cardinality of
* x is 0..1 or 1..1. Before the change, these routines would return
* null if the object had not previously been assigned, and after the '
* change, they will automatically create the object if it had not
* been assigned (unless the object is polymorphic, in which case,
* only the type specific getters create the object)
*
* When making the transition from the old style to the new style,
* the main change is that when testing for presence or abssense
* of the element, instead of doing one of these two:
*
* if (obj.getProperty() == null)
* if (obj.getProperty() != null)
*
* you instead do
*
* if (!obj.hasProperty())
* if (obj.hasProperty())
*
* or else one of these two:
*
* if (obj.getProperty().isEmpty())
* if (!obj.getProperty().isEmpty())
*
* The only way to sort this out is by finding all these things
* in the code, and changing them.
*
* To help with that, you can set the status field of this class
* to change how this API behaves. Note: the status value is tied
* to the way that you program. The intent of this class is to
* help make developers the transiition to status = 0. The old
* behaviour is status = 2. To make the transition, set the
* status code to 1. This way, any time a .getX routine needs
* to automatically create an object, an exception will be
* raised instead. The expected use of this is:
* - set status = 1
* - test your code (all paths)
* - when an exception happens, change the code to use .hasX() or .isEmpty()
* - when all execution paths don't raise an exception, set status = 0
* - start programming to the new style.
*
* You can set status = 2 and leave it like that, but this is not
* compatible with the utilities and validation code, nor with the
* HAPI code. So everyone shoul make this transition
*
* This is a difficult change to make to an API. Most users should engage with it
* as they migrate from DSTU1 to DSTU2, at the same time as they encounter
* other changes. This change was made in order to align the two java reference
* implementations on a common object model, which is an important outcome that
* justifies making this change to implementers (sorry for any pain caused)
*
* @author Grahame
*
*/
public class Configuration {
private static int status = 0;
// 0: auto-create
// 1: error
// 2: return null
public static boolean errorOnAutoCreate() {
return status == 1;
}
public static boolean doAutoCreate() {
return status == 0;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,61 @@
package org.hl7.fhir.dstu2.model;
/*-
* #%L
* org.hl7.fhir.dstu2
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* 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%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Wed, Jul 13, 2016 05:32+1000 for FHIR v1.0.2
public class Constants {
public final static String VERSION = "1.0.2";
public final static String REVISION = "7475";
public final static String DATE = "Wed Jul 13 05:32:49 AEST 2016";
}

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