001package org.hl7.fhir.dstu3.terminologies;
002
003/*-
004 * #%L
005 * org.hl7.fhir.dstu3
006 * %%
007 * Copyright (C) 2014 - 2019 Health Level 7
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
023
024/*
025Copyright (c) 2011+, HL7, Inc
026All rights reserved.
027
028Redistribution and use in source and binary forms, with or without modification, 
029are permitted provided that the following conditions are met:
030
031 * Redistributions of source code must retain the above copyright notice, this 
032   list of conditions and the following disclaimer.
033 * Redistributions in binary form must reproduce the above copyright notice, 
034   this list of conditions and the following disclaimer in the documentation 
035   and/or other materials provided with the distribution.
036 * Neither the name of HL7 nor the names of its contributors may be used to 
037   endorse or promote products derived from this software without specific 
038   prior written permission.
039
040THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
041ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
042WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
043IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
044INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
045NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
046PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
047WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
048ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
049POSSIBILITY OF SUCH DAMAGE.
050
051*/
052
053import java.io.File;
054import java.io.FileInputStream;
055import java.io.FileOutputStream;
056import java.io.IOException;
057import java.util.HashMap;
058import java.util.Map;
059
060import org.apache.commons.io.IOUtils;
061import org.hl7.fhir.dstu3.context.IWorkerContext;
062import org.hl7.fhir.dstu3.formats.IParser.OutputStyle;
063import org.hl7.fhir.dstu3.model.ExpansionProfile;
064import org.hl7.fhir.dstu3.model.OperationOutcome;
065import org.hl7.fhir.dstu3.model.Resource;
066import org.hl7.fhir.dstu3.model.ValueSet;
067import org.hl7.fhir.dstu3.terminologies.ValueSetExpander.TerminologyServiceErrorClass;
068import org.hl7.fhir.dstu3.terminologies.ValueSetExpander.ValueSetExpansionOutcome;
069import org.hl7.fhir.dstu3.utils.ToolingExtensions;
070import org.hl7.fhir.exceptions.FHIRFormatError;
071import org.hl7.fhir.utilities.Utilities;
072import org.hl7.fhir.utilities.xhtml.XhtmlComposer;
073
074public class ValueSetExpansionCache implements ValueSetExpanderFactory {
075
076  public class CacheAwareExpander implements ValueSetExpander {
077
078          @Override
079          public ValueSetExpansionOutcome expand(ValueSet source, ExpansionProfile profile) throws ETooCostly, IOException {
080            String cacheKey = makeCacheKey(source, profile);
081                if (expansions.containsKey(cacheKey))
082                        return expansions.get(cacheKey);
083                ValueSetExpander vse = new ValueSetExpanderSimple(context, ValueSetExpansionCache.this);
084                ValueSetExpansionOutcome vso = vse.expand(source, profile);
085                if (vso.getError() != null) {
086                  // well, we'll see if the designated server can expand it, and if it can, we'll cache it locally
087                        vso = context.expandVS(source, false, profile == null || !profile.getExcludeNested());
088                        if (cacheFolder != null) {
089                        FileOutputStream s = new FileOutputStream(Utilities.path(cacheFolder, makeFile(source.getUrl())));
090                        context.newXmlParser().setOutputStyle(OutputStyle.PRETTY).compose(s, vso.getValueset());
091                        s.close();
092                }
093                }
094                if (vso.getValueset() != null)
095                  expansions.put(cacheKey, vso);
096                return vso;
097          }
098
099    private String makeCacheKey(ValueSet source, ExpansionProfile profile) {
100      return profile == null ? source.getUrl() : source.getUrl() + " " + profile.getUrl()+" "+profile.getExcludeNested(); 
101    }
102
103    private String makeFile(String url) {
104      return url.replace("$", "").replace(":", "").replace("//", "/").replace("/", "_")+".xml";
105    }
106  }
107
108  private static final String VS_ID_EXT = "http://tools/cache";
109
110  private final Map<String, ValueSetExpansionOutcome> expansions = new HashMap<String, ValueSetExpansionOutcome>();
111  private final IWorkerContext context;
112  private final String cacheFolder;
113        
114        public ValueSetExpansionCache(IWorkerContext context) {
115    super();
116    cacheFolder = null;
117    this.context = context;
118  }
119  
120        public ValueSetExpansionCache(IWorkerContext context, String cacheFolder) throws FHIRFormatError, IOException {
121    super();
122    this.context = context;
123    this.cacheFolder = cacheFolder;
124    if (this.cacheFolder != null)
125      loadCache();
126  }
127  
128        private void loadCache() throws FHIRFormatError, IOException {
129          File[] files = new File(cacheFolder).listFiles();
130    for (File f : files) {
131      if (f.getName().endsWith(".xml")) {
132        final FileInputStream is = new FileInputStream(f);
133        try {      
134        Resource r = context.newXmlParser().setOutputStyle(OutputStyle.PRETTY).parse(is);
135        if (r instanceof OperationOutcome) {
136          OperationOutcome oo = (OperationOutcome) r;
137          expansions.put(ToolingExtensions.getExtension(oo,VS_ID_EXT).getValue().toString(),
138            new ValueSetExpansionOutcome(new XhtmlComposer(XhtmlComposer.XML).composePlainText(oo.getText().getDiv()), TerminologyServiceErrorClass.UNKNOWN));
139        } else {
140          ValueSet vs = (ValueSet) r; 
141          expansions.put(vs.getUrl(), new ValueSetExpansionOutcome(vs));
142        }
143        } finally {
144          IOUtils.closeQuietly(is);
145        }
146      }
147    }
148  }
149
150  @Override
151        public ValueSetExpander getExpander() {
152                return new CacheAwareExpander();
153                // return new ValueSetExpander(valuesets, codesystems);
154        }
155
156}