001package org.hl7.fhir.dstu3.hapi.ctx;
002
003import ca.uhn.fhir.context.FhirContext;
004import org.apache.commons.io.Charsets;
005import org.apache.commons.io.IOUtils;
006import org.apache.commons.lang3.StringUtils;
007import org.apache.commons.lang3.Validate;
008import org.hl7.fhir.dstu3.model.*;
009import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent;
010import org.hl7.fhir.dstu3.model.CodeSystem.CodeSystemContentMode;
011import org.hl7.fhir.dstu3.model.CodeSystem.ConceptDefinitionComponent;
012import org.hl7.fhir.dstu3.model.ValueSet.ConceptReferenceComponent;
013import org.hl7.fhir.dstu3.model.ValueSet.ConceptSetComponent;
014import org.hl7.fhir.dstu3.model.ValueSet.ValueSetExpansionComponent;
015import org.hl7.fhir.instance.model.api.IBaseResource;
016import org.hl7.fhir.utilities.validation.ValidationMessage.IssueSeverity;
017
018import java.io.InputStream;
019import java.io.InputStreamReader;
020import java.util.*;
021
022import static org.apache.commons.lang3.StringUtils.defaultString;
023import static org.apache.commons.lang3.StringUtils.isNotBlank;
024
025public class DefaultProfileValidationSupport implements IValidationSupport {
026
027        private static final String URL_PREFIX_VALUE_SET = "http://hl7.org/fhir/ValueSet/";
028        private static final String URL_PREFIX_STRUCTURE_DEFINITION = "http://hl7.org/fhir/StructureDefinition/";
029        private static final String URL_PREFIX_STRUCTURE_DEFINITION_BASE = "http://hl7.org/fhir/";
030
031        private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(DefaultProfileValidationSupport.class);
032
033        private Map<String, CodeSystem> myCodeSystems;
034        private Map<String, StructureDefinition> myStructureDefinitions;
035        private Map<String, ValueSet> myValueSets;
036
037        @Override
038        public ValueSetExpansionComponent expandValueSet(FhirContext theContext, ConceptSetComponent theInclude) {
039                ValueSetExpansionComponent retVal = new ValueSetExpansionComponent();
040
041                Set<String> wantCodes = new HashSet<>();
042                for (ConceptReferenceComponent next : theInclude.getConcept()) {
043                        wantCodes.add(next.getCode());
044                }
045
046                CodeSystem system = fetchCodeSystem(theContext, theInclude.getSystem());
047                if (system != null) {
048                        List<ConceptDefinitionComponent> concepts = system.getConcept();
049                        addConcepts(theInclude, retVal, wantCodes, concepts);
050                }
051
052                for (UriType next: theInclude.getValueSet()) {
053                        ValueSet vs = myValueSets.get(defaultString(next.getValueAsString()));
054                        if (vs != null) {
055                                for (ConceptSetComponent nextInclude : vs.getCompose().getInclude()) {
056                                        ValueSetExpansionComponent contents = expandValueSet(theContext, nextInclude);
057                                        retVal.getContains().addAll(contents.getContains());
058                                }
059                        }
060                }
061
062                return retVal;
063        }
064
065        private void addConcepts(ConceptSetComponent theInclude, ValueSetExpansionComponent theRetVal, Set<String> theWantCodes, List<ConceptDefinitionComponent> theConcepts) {
066                for (ConceptDefinitionComponent next : theConcepts) {
067                        if (theWantCodes.isEmpty() || theWantCodes.contains(next.getCode())) {
068                                theRetVal
069                                        .addContains()
070                                        .setSystem(theInclude.getSystem())
071                                        .setCode(next.getCode())
072                                        .setDisplay(next.getDisplay());
073                        }
074                        addConcepts(theInclude, theRetVal, theWantCodes, next.getConcept());
075                }
076        }
077
078        @Override
079        public List<IBaseResource> fetchAllConformanceResources(FhirContext theContext) {
080                ArrayList<IBaseResource> retVal = new ArrayList<>();
081                retVal.addAll(myCodeSystems.values());
082                retVal.addAll(myStructureDefinitions.values());
083                retVal.addAll(myValueSets.values());
084                return retVal;
085        }
086
087        @Override
088        public List<StructureDefinition> fetchAllStructureDefinitions(FhirContext theContext) {
089                return new ArrayList<StructureDefinition>(provideStructureDefinitionMap(theContext).values());
090        }
091
092        @Override
093        public CodeSystem fetchCodeSystem(FhirContext theContext, String theSystem) {
094                return (CodeSystem) fetchCodeSystemOrValueSet(theContext, theSystem, true);
095        }
096
097        private DomainResource fetchCodeSystemOrValueSet(FhirContext theContext, String theSystem, boolean codeSystem) {
098                synchronized (this) {
099                        Map<String, CodeSystem> codeSystems = myCodeSystems;
100                        Map<String, ValueSet> valueSets = myValueSets;
101                        if (codeSystems == null || valueSets == null) {
102                                codeSystems = new HashMap<String, CodeSystem>();
103                                valueSets = new HashMap<String, ValueSet>();
104
105                                loadCodeSystems(theContext, codeSystems, valueSets, "/org/hl7/fhir/dstu3/model/valueset/valuesets.xml");
106                                loadCodeSystems(theContext, codeSystems, valueSets, "/org/hl7/fhir/dstu3/model/valueset/v2-tables.xml");
107                                loadCodeSystems(theContext, codeSystems, valueSets, "/org/hl7/fhir/dstu3/model/valueset/v3-codesystems.xml");
108
109                                myCodeSystems = codeSystems;
110                                myValueSets = valueSets;
111                        }
112
113                        if (codeSystem) {
114                                return codeSystems.get(theSystem);
115                        } else {
116                                return valueSets.get(theSystem);
117                        }
118                }
119        }
120
121        @SuppressWarnings("unchecked")
122        @Override
123        public <T extends IBaseResource> T fetchResource(FhirContext theContext, Class<T> theClass, String theUri) {
124                Validate.notBlank(theUri, "theUri must not be null or blank");
125
126                if (theClass.equals(StructureDefinition.class)) {
127                        return (T) fetchStructureDefinition(theContext, theUri);
128                }
129
130                if (theClass.equals(ValueSet.class) || theUri.startsWith(URL_PREFIX_VALUE_SET)) {
131                        return (T) fetchValueSet(theContext, theUri);
132                }
133
134                return null;
135        }
136
137        @Override
138        public StructureDefinition fetchStructureDefinition(FhirContext theContext, String theUrl) {
139                String url = theUrl;
140                if (url.startsWith(URL_PREFIX_STRUCTURE_DEFINITION)) {
141                        // no change
142                } else if (url.indexOf('/') == -1) {
143                        url = URL_PREFIX_STRUCTURE_DEFINITION + url;
144                } else if (StringUtils.countMatches(url, '/') == 1) {
145                        url = URL_PREFIX_STRUCTURE_DEFINITION_BASE + url;
146                }
147                Map<String, StructureDefinition> map = provideStructureDefinitionMap(theContext);
148                StructureDefinition retVal = map.get(url);
149
150                if (retVal == null && url.startsWith(URL_PREFIX_STRUCTURE_DEFINITION)) {
151                        String tryUrl = URL_PREFIX_STRUCTURE_DEFINITION + StringUtils.capitalize(url.substring(URL_PREFIX_STRUCTURE_DEFINITION.length()));
152                        retVal = map.get(tryUrl);
153                }
154
155                return retVal;
156        }
157
158        @Override
159        public ValueSet fetchValueSet(FhirContext theContext, String uri) {
160                return (ValueSet) fetchCodeSystemOrValueSet(theContext, uri, false);
161        }
162
163        public void flush() {
164                myCodeSystems = null;
165                myStructureDefinitions = null;
166        }
167
168        @Override
169        public boolean isCodeSystemSupported(FhirContext theContext, String theSystem) {
170                CodeSystem cs = fetchCodeSystem(theContext, theSystem);
171                return cs != null && cs.getContent() != CodeSystemContentMode.NOTPRESENT;
172        }
173
174        private void loadCodeSystems(FhirContext theContext, Map<String, CodeSystem> theCodeSystems, Map<String, ValueSet> theValueSets, String theClasspath) {
175                ourLog.info("Loading CodeSystem/ValueSet from classpath: {}", theClasspath);
176                InputStream inputStream = DefaultProfileValidationSupport.class.getResourceAsStream(theClasspath);
177                InputStreamReader reader = null;
178                if (inputStream != null) {
179                        try {
180                                reader = new InputStreamReader(inputStream, Charsets.UTF_8);
181
182                                Bundle bundle = theContext.newXmlParser().parseResource(Bundle.class, reader);
183                                for (BundleEntryComponent next : bundle.getEntry()) {
184                                        if (next.getResource() instanceof CodeSystem) {
185                                                CodeSystem nextValueSet = (CodeSystem) next.getResource();
186                                                nextValueSet.getText().setDivAsString("");
187                                                String system = nextValueSet.getUrl();
188                                                if (isNotBlank(system)) {
189                                                        theCodeSystems.put(system, nextValueSet);
190                                                }
191                                        } else if (next.getResource() instanceof ValueSet) {
192                                                ValueSet nextValueSet = (ValueSet) next.getResource();
193                                                nextValueSet.getText().setDivAsString("");
194                                                String system = nextValueSet.getUrl();
195                                                if (isNotBlank(system)) {
196                                                        theValueSets.put(system, nextValueSet);
197                                                }
198                                        }
199                                }
200                        } finally {
201                                IOUtils.closeQuietly(reader);
202                                IOUtils.closeQuietly(inputStream);
203                        }
204                } else {
205                        ourLog.warn("Unable to load resource: {}", theClasspath);
206                }
207        }
208
209        private void loadStructureDefinitions(FhirContext theContext, Map<String, StructureDefinition> theCodeSystems, String theClasspath) {
210                ourLog.info("Loading structure definitions from classpath: {}", theClasspath);
211                InputStream valuesetText = DefaultProfileValidationSupport.class.getResourceAsStream(theClasspath);
212                if (valuesetText != null) {
213                        InputStreamReader reader = new InputStreamReader(valuesetText, Charsets.UTF_8);
214
215                        Bundle bundle = theContext.newXmlParser().parseResource(Bundle.class, reader);
216                        for (BundleEntryComponent next : bundle.getEntry()) {
217                                if (next.getResource() instanceof StructureDefinition) {
218                                        StructureDefinition nextSd = (StructureDefinition) next.getResource();
219                                        nextSd.getText().setDivAsString("");
220                                        String system = nextSd.getUrl();
221                                        if (isNotBlank(system)) {
222                                                theCodeSystems.put(system, nextSd);
223                                        }
224                                }
225                        }
226                } else {
227                        ourLog.warn("Unable to load resource: {}", theClasspath);
228                }
229        }
230
231        private Map<String, StructureDefinition> provideStructureDefinitionMap(FhirContext theContext) {
232                Map<String, StructureDefinition> structureDefinitions = myStructureDefinitions;
233                if (structureDefinitions == null) {
234                        structureDefinitions = new HashMap<String, StructureDefinition>();
235
236                        loadStructureDefinitions(theContext, structureDefinitions, "/org/hl7/fhir/dstu3/model/profile/profiles-resources.xml");
237                        loadStructureDefinitions(theContext, structureDefinitions, "/org/hl7/fhir/dstu3/model/profile/profiles-types.xml");
238                        loadStructureDefinitions(theContext, structureDefinitions, "/org/hl7/fhir/dstu3/model/profile/profiles-others.xml");
239                        loadStructureDefinitions(theContext, structureDefinitions, "/org/hl7/fhir/dstu3/model/extension/extension-definitions.xml");
240
241                        myStructureDefinitions = structureDefinitions;
242                }
243                return structureDefinitions;
244        }
245
246        private CodeValidationResult testIfConceptIsInList(String theCode, List<ConceptDefinitionComponent> conceptList, boolean theCaseSensitive) {
247                String code = theCode;
248                if (theCaseSensitive == false) {
249                        code = code.toUpperCase();
250                }
251
252                return testIfConceptIsInListInner(conceptList, theCaseSensitive, code);
253        }
254
255        private CodeValidationResult testIfConceptIsInListInner(List<ConceptDefinitionComponent> conceptList, boolean theCaseSensitive, String code) {
256                CodeValidationResult retVal = null;
257                for (ConceptDefinitionComponent next : conceptList) {
258                        String nextCandidate = next.getCode();
259                        if (theCaseSensitive == false) {
260                                nextCandidate = nextCandidate.toUpperCase();
261                        }
262                        if (nextCandidate.equals(code)) {
263                                retVal = new CodeValidationResult(next);
264                                break;
265                        }
266
267                        // recurse
268                        retVal = testIfConceptIsInList(code, next.getConcept(), theCaseSensitive);
269                        if (retVal != null) {
270                                break;
271                        }
272                }
273
274                return retVal;
275        }
276
277        @Override
278        public CodeValidationResult validateCode(FhirContext theContext, String theCodeSystem, String theCode, String theDisplay) {
279                CodeSystem cs = fetchCodeSystem(theContext, theCodeSystem);
280                if (cs != null) {
281                        boolean caseSensitive = true;
282                        if (cs.hasCaseSensitive()) {
283                                caseSensitive = cs.getCaseSensitive();
284                        }
285
286                        CodeValidationResult retVal = testIfConceptIsInList(theCode, cs.getConcept(), caseSensitive);
287
288                        if (retVal != null) {
289                                return retVal;
290                        }
291                }
292
293                return new CodeValidationResult(IssueSeverity.WARNING, "Unknown code: " + theCodeSystem + " / " + theCode);
294        }
295
296}