001package ca.uhn.fhir.context.support;
002
003/*-
004 * #%L
005 * HAPI FHIR - Core Library
006 * %%
007 * Copyright (C) 2014 - 2020 University Health Network
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 *
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import ca.uhn.fhir.context.ConfigurationException;
024import ca.uhn.fhir.context.FhirContext;
025import ca.uhn.fhir.context.RuntimeResourceDefinition;
026import ca.uhn.fhir.rest.api.Constants;
027import ca.uhn.fhir.util.BundleUtil;
028import org.apache.commons.lang3.StringUtils;
029import org.hl7.fhir.instance.model.api.IBase;
030import org.hl7.fhir.instance.model.api.IBaseBundle;
031import org.hl7.fhir.instance.model.api.IBaseResource;
032import org.hl7.fhir.instance.model.api.IPrimitiveType;
033
034import javax.annotation.Nullable;
035import java.io.IOException;
036import java.io.InputStream;
037import java.io.InputStreamReader;
038import java.util.ArrayList;
039import java.util.Collections;
040import java.util.HashMap;
041import java.util.List;
042import java.util.Map;
043import java.util.Optional;
044import java.util.Properties;
045
046import static org.apache.commons.lang3.StringUtils.isNotBlank;
047
048public class DefaultProfileValidationSupport implements IValidationSupport {
049
050        private static final String URL_PREFIX_STRUCTURE_DEFINITION = "http://hl7.org/fhir/StructureDefinition/";
051        private static final String URL_PREFIX_STRUCTURE_DEFINITION_BASE = "http://hl7.org/fhir/";
052        private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(DefaultProfileValidationSupport.class);
053        private final FhirContext myCtx;
054
055        private Map<String, IBaseResource> myCodeSystems;
056        private Map<String, IBaseResource> myStructureDefinitions;
057        private Map<String, IBaseResource> myValueSets;
058        private List<String> myTerminologyResources;
059        private List<String> myStructureDefinitionResources;
060
061        /**
062         * Constructor
063         *
064         * @param theFhirContext The context to use
065         */
066        public DefaultProfileValidationSupport(FhirContext theFhirContext) {
067                myCtx = theFhirContext;
068        }
069
070
071        private void initializeResourceLists() {
072
073                if (myTerminologyResources != null && myStructureDefinitionResources != null) {
074                        return;
075                }
076
077                List<String> terminologyResources = new ArrayList<>();
078                List<String> structureDefinitionResources = new ArrayList<>();
079                switch (getFhirContext().getVersion().getVersion()) {
080                        case DSTU2:
081                        case DSTU2_HL7ORG:
082                                terminologyResources.add("/org/hl7/fhir/instance/model/valueset/valuesets.xml");
083                                terminologyResources.add("/org/hl7/fhir/instance/model/valueset/v2-tables.xml");
084                                terminologyResources.add("/org/hl7/fhir/instance/model/valueset/v3-codesystems.xml");
085                                Properties profileNameProperties = new Properties();
086                                try {
087                                        profileNameProperties.load(DefaultProfileValidationSupport.class.getResourceAsStream("/org/hl7/fhir/instance/model/profile/profiles.properties"));
088                                        for (Object nextKey : profileNameProperties.keySet()) {
089                                                structureDefinitionResources.add("/org/hl7/fhir/instance/model/profile/" + nextKey);
090                                        }
091                                } catch (IOException e) {
092                                        throw new ConfigurationException(e);
093                                }
094                                break;
095                        case DSTU2_1:
096                                terminologyResources.add("/org/hl7/fhir/dstu2016may/model/valueset/valuesets.xml");
097                                terminologyResources.add("/org/hl7/fhir/dstu2016may/model/valueset/v2-tables.xml");
098                                terminologyResources.add("/org/hl7/fhir/dstu2016may/model/valueset/v3-codesystems.xml");
099                                structureDefinitionResources.add("/org/hl7/fhir/dstu2016may/model/profile/profiles-resources.xml");
100                                structureDefinitionResources.add("/org/hl7/fhir/dstu2016may/model/profile/profiles-types.xml");
101                                structureDefinitionResources.add("/org/hl7/fhir/dstu2016may/model/profile/profiles-others.xml");
102                                break;
103                        case DSTU3:
104                                terminologyResources.add("/org/hl7/fhir/dstu3/model/valueset/valuesets.xml");
105                                terminologyResources.add("/org/hl7/fhir/dstu3/model/valueset/v2-tables.xml");
106                                terminologyResources.add("/org/hl7/fhir/dstu3/model/valueset/v3-codesystems.xml");
107                                structureDefinitionResources.add("/org/hl7/fhir/dstu3/model/profile/profiles-resources.xml");
108                                structureDefinitionResources.add("/org/hl7/fhir/dstu3/model/profile/profiles-types.xml");
109                                structureDefinitionResources.add("/org/hl7/fhir/dstu3/model/profile/profiles-others.xml");
110                                structureDefinitionResources.add("/org/hl7/fhir/dstu3/model/extension/extension-definitions.xml");
111                                break;
112                        case R4:
113                                terminologyResources.add("/org/hl7/fhir/r4/model/valueset/valuesets.xml");
114                                terminologyResources.add("/org/hl7/fhir/r4/model/valueset/v2-tables.xml");
115                                terminologyResources.add("/org/hl7/fhir/r4/model/valueset/v3-codesystems.xml");
116                                structureDefinitionResources.add("/org/hl7/fhir/r4/model/profile/profiles-resources.xml");
117                                structureDefinitionResources.add("/org/hl7/fhir/r4/model/profile/profiles-types.xml");
118                                structureDefinitionResources.add("/org/hl7/fhir/r4/model/profile/profiles-others.xml");
119                                structureDefinitionResources.add("/org/hl7/fhir/r4/model/extension/extension-definitions.xml");
120                                break;
121                        case R5:
122                                structureDefinitionResources.add("/org/hl7/fhir/r5/model/profile/profiles-resources.xml");
123                                structureDefinitionResources.add("/org/hl7/fhir/r5/model/profile/profiles-types.xml");
124                                structureDefinitionResources.add("/org/hl7/fhir/r5/model/profile/profiles-others.xml");
125                                structureDefinitionResources.add("/org/hl7/fhir/r5/model/extension/extension-definitions.xml");
126                                terminologyResources.add("/org/hl7/fhir/r5/model/valueset/valuesets.xml");
127                                terminologyResources.add("/org/hl7/fhir/r5/model/valueset/v2-tables.xml");
128                                terminologyResources.add("/org/hl7/fhir/r5/model/valueset/v3-codesystems.xml");
129                                break;
130                }
131
132                myTerminologyResources = terminologyResources;
133                myStructureDefinitionResources = structureDefinitionResources;
134        }
135
136
137        @Override
138        public List<IBaseResource> fetchAllConformanceResources() {
139                ArrayList<IBaseResource> retVal = new ArrayList<>();
140                retVal.addAll(myCodeSystems.values());
141                retVal.addAll(myStructureDefinitions.values());
142                retVal.addAll(myValueSets.values());
143                return retVal;
144        }
145
146        @Override
147        public <T extends IBaseResource> List<T> fetchAllStructureDefinitions() {
148                return toList(provideStructureDefinitionMap());
149        }
150
151
152        @Override
153        public IBaseResource fetchCodeSystem(String theSystem) {
154                return fetchCodeSystemOrValueSet(theSystem, true);
155        }
156
157        private IBaseResource fetchCodeSystemOrValueSet(String theSystem, boolean codeSystem) {
158                synchronized (this) {
159                        Map<String, IBaseResource> codeSystems = myCodeSystems;
160                        Map<String, IBaseResource> valueSets = myValueSets;
161                        if (codeSystems == null || valueSets == null) {
162                                codeSystems = new HashMap<>();
163                                valueSets = new HashMap<>();
164
165                                initializeResourceLists();
166                                for (String next : myTerminologyResources) {
167                                        loadCodeSystems(codeSystems, valueSets, next);
168                                }
169
170                                myCodeSystems = codeSystems;
171                                myValueSets = valueSets;
172                        }
173
174                        // System can take the form "http://url|version"
175                        String system = theSystem;
176                        if (system.contains("|")) {
177                                String version = system.substring(system.indexOf('|') + 1);
178                                if (version.matches("^[0-9.]+$")) {
179                                        system = system.substring(0, system.indexOf('|'));
180                                }
181                        }
182
183                        if (codeSystem) {
184                                return codeSystems.get(system);
185                        } else {
186                                return valueSets.get(system);
187                        }
188                }
189        }
190
191        @Override
192        public IBaseResource fetchStructureDefinition(String theUrl) {
193                String url = theUrl;
194                if (url.startsWith(URL_PREFIX_STRUCTURE_DEFINITION)) {
195                        // no change
196                } else if (url.indexOf('/') == -1) {
197                        url = URL_PREFIX_STRUCTURE_DEFINITION + url;
198                } else if (StringUtils.countMatches(url, '/') == 1) {
199                        url = URL_PREFIX_STRUCTURE_DEFINITION_BASE + url;
200                }
201                Map<String, IBaseResource> structureDefinitionMap = provideStructureDefinitionMap();
202                IBaseResource retVal = structureDefinitionMap.get(url);
203                return retVal;
204        }
205
206        @Override
207        public IBaseResource fetchValueSet(String theUrl) {
208                IBaseResource retVal = fetchCodeSystemOrValueSet(theUrl, false);
209                return retVal;
210        }
211
212        public void flush() {
213                myCodeSystems = null;
214                myStructureDefinitions = null;
215        }
216
217        @Override
218        public FhirContext getFhirContext() {
219                return myCtx;
220        }
221
222        private Map<String, IBaseResource> provideStructureDefinitionMap() {
223                Map<String, IBaseResource> structureDefinitions = myStructureDefinitions;
224                if (structureDefinitions == null) {
225                        structureDefinitions = new HashMap<>();
226
227                        initializeResourceLists();
228                        for (String next : myStructureDefinitionResources) {
229                                loadStructureDefinitions(structureDefinitions, next);
230                        }
231
232                        myStructureDefinitions = structureDefinitions;
233                }
234                return structureDefinitions;
235        }
236
237        private void loadCodeSystems(Map<String, IBaseResource> theCodeSystems, Map<String, IBaseResource> theValueSets, String theClasspath) {
238                ourLog.info("Loading CodeSystem/ValueSet from classpath: {}", theClasspath);
239                InputStream inputStream = DefaultProfileValidationSupport.class.getResourceAsStream(theClasspath);
240                InputStreamReader reader = null;
241                if (inputStream != null) {
242                        try {
243                                reader = new InputStreamReader(inputStream, Constants.CHARSET_UTF8);
244                                List<IBaseResource> resources = parseBundle(reader);
245                                for (IBaseResource next : resources) {
246
247                                        RuntimeResourceDefinition nextDef = getFhirContext().getResourceDefinition(next);
248                                        Map<String, IBaseResource> map = null;
249                                        switch (nextDef.getName()) {
250                                                case "CodeSystem":
251                                                        map = theCodeSystems;
252                                                        break;
253                                                case "ValueSet":
254                                                        map = theValueSets;
255                                                        break;
256                                        }
257
258                                        if (map != null) {
259                                                String urlValueString = getConformanceResourceUrl(next);
260                                                if (isNotBlank(urlValueString)) {
261                                                        map.put(urlValueString, next);
262                                                }
263
264                                                switch (myCtx.getVersion().getVersion()) {
265                                                        case DSTU2:
266                                                        case DSTU2_HL7ORG:
267
268                                                                IPrimitiveType<?> codeSystem = myCtx.newTerser().getSingleValueOrNull(next, "ValueSet.codeSystem.system", IPrimitiveType.class);
269                                                                if (codeSystem != null && isNotBlank(codeSystem.getValueAsString())) {
270                                                                        theCodeSystems.put(codeSystem.getValueAsString(), next);
271                                                                }
272
273                                                                break;
274
275                                                        default:
276                                                        case DSTU2_1:
277                                                        case DSTU3:
278                                                        case R4:
279                                                        case R5:
280                                                                break;
281                                                }
282                                        }
283
284
285                                }
286                        } finally {
287                                try {
288                                        if (reader != null) {
289                                                reader.close();
290                                        }
291                                        inputStream.close();
292                                } catch (IOException e) {
293                                        ourLog.warn("Failure closing stream", e);
294                                }
295                        }
296                } else {
297                        ourLog.warn("Unable to load resource: {}", theClasspath);
298                }
299        }
300
301        private void loadStructureDefinitions(Map<String, IBaseResource> theCodeSystems, String theClasspath) {
302                ourLog.info("Loading structure definitions from classpath: {}", theClasspath);
303                try (InputStream valuesetText = DefaultProfileValidationSupport.class.getResourceAsStream(theClasspath)) {
304                        if (valuesetText != null) {
305                                try (InputStreamReader reader = new InputStreamReader(valuesetText, Constants.CHARSET_UTF8)) {
306
307                                        List<IBaseResource> resources = parseBundle(reader);
308                                        for (IBaseResource next : resources) {
309
310                                                String nextType = getFhirContext().getResourceType(next);
311                                                if ("StructureDefinition".equals(nextType)) {
312
313                                                        String url = getConformanceResourceUrl(next);
314                                                        if (isNotBlank(url)) {
315                                                                theCodeSystems.put(url, next);
316                                                        }
317
318                                                }
319
320                                        }
321                                }
322                        } else {
323                                ourLog.warn("Unable to load resource: {}", theClasspath);
324                        }
325                } catch (IOException theE) {
326                        ourLog.warn("Unable to load resource: {}", theClasspath);
327                }
328        }
329
330        private String getConformanceResourceUrl(IBaseResource theResource) {
331                return getConformanceResourceUrl(getFhirContext(), theResource);
332        }
333
334        private List<IBaseResource> parseBundle(InputStreamReader theReader) {
335                IBaseResource parsedObject = getFhirContext().newXmlParser().parseResource(theReader);
336                if (parsedObject instanceof IBaseBundle) {
337                        IBaseBundle bundle = (IBaseBundle) parsedObject;
338                        return BundleUtil.toListOfResources(getFhirContext(), bundle);
339                } else {
340                        return Collections.singletonList(parsedObject);
341                }
342        }
343
344        @Nullable
345        public static String getConformanceResourceUrl(FhirContext theFhirContext, IBaseResource theResource) {
346                String urlValueString = null;
347                Optional<IBase> urlValue = theFhirContext.getResourceDefinition(theResource).getChildByName("url").getAccessor().getFirstValueOrNull(theResource);
348                if (urlValue.isPresent()) {
349                        IPrimitiveType<?> urlValueType = (IPrimitiveType<?>) urlValue.get();
350                        urlValueString = urlValueType.getValueAsString();
351                }
352                return urlValueString;
353        }
354
355        static <T extends IBaseResource> List<T> toList(Map<String, IBaseResource> theMap) {
356                ArrayList<IBaseResource> retVal = new ArrayList<>(theMap.values());
357                return (List<T>) Collections.unmodifiableList(retVal);
358        }
359
360}