001package org.hl7.fhir.r5.terminologies;
002
003/*
004  Copyright (c) 2011+, HL7, Inc.
005  All rights reserved.
006  
007  Redistribution and use in source and binary forms, with or without modification, 
008  are permitted provided that the following conditions are met:
009    
010   * Redistributions of source code must retain the above copyright notice, this 
011     list of conditions and the following disclaimer.
012   * Redistributions in binary form must reproduce the above copyright notice, 
013     this list of conditions and the following disclaimer in the documentation 
014     and/or other materials provided with the distribution.
015   * Neither the name of HL7 nor the names of its contributors may be used to 
016     endorse or promote products derived from this software without specific 
017     prior written permission.
018  
019  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
020  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
021  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
022  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
023  INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
024  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
025  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
026  WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
027  ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
028  POSSIBILITY OF SUCH DAMAGE.
029  
030 */
031
032
033
034/*
035Copyright (c) 2011+, HL7, Inc
036All rights reserved.
037
038Redistribution and use in source and binary forms, with or without modification, 
039are permitted provided that the following conditions are met:
040
041 * Redistributions of source code must retain the above copyright notice, this 
042   list of conditions and the following disclaimer.
043 * Redistributions in binary form must reproduce the above copyright notice, 
044   this list of conditions and the following disclaimer in the documentation 
045   and/or other materials provided with the distribution.
046 * Neither the name of HL7 nor the names of its contributors may be used to 
047   endorse or promote products derived from this software without specific 
048   prior written permission.
049
050THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
051ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
052WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
053IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
054INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
055NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
056PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
057WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
058ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
059POSSIBILITY OF SUCH DAMAGE.
060
061*/
062
063import java.io.File;
064import java.io.FileInputStream;
065import java.io.FileOutputStream;
066import java.io.IOException;
067import java.util.HashMap;
068import java.util.Map;
069
070import org.apache.commons.io.IOUtils;
071import org.hl7.fhir.exceptions.FHIRFormatError;
072import org.hl7.fhir.r5.context.IWorkerContext;
073import org.hl7.fhir.r5.formats.IParser.OutputStyle;
074import org.hl7.fhir.r5.formats.JsonParser;
075import org.hl7.fhir.r5.formats.XmlParser;
076import org.hl7.fhir.r5.model.CanonicalResource;
077import org.hl7.fhir.r5.model.OperationOutcome;
078import org.hl7.fhir.r5.model.Parameters;
079import org.hl7.fhir.r5.model.Resource;
080import org.hl7.fhir.r5.model.ValueSet;
081import org.hl7.fhir.r5.terminologies.ValueSetExpander.TerminologyServiceErrorClass;
082import org.hl7.fhir.r5.terminologies.ValueSetExpander.ValueSetExpansionOutcome;
083import org.hl7.fhir.r5.utils.ToolingExtensions;
084import org.hl7.fhir.utilities.Utilities;
085import org.hl7.fhir.utilities.xhtml.XhtmlComposer;
086
087public class ValueSetExpansionCache implements ValueSetExpanderFactory {
088
089  public class CacheAwareExpander implements ValueSetExpander {
090
091          @Override
092          public ValueSetExpansionOutcome expand(ValueSet source, Parameters expParams) throws ETooCostly, IOException {
093            String cacheKey = makeCacheKey(source, expParams);
094                if (expansions.containsKey(cacheKey))
095                        return expansions.get(cacheKey);
096                ValueSetExpander vse = new ValueSetExpanderSimple(context);
097                ValueSetExpansionOutcome vso = vse.expand(source, expParams);
098                if (vso.getError() != null) {
099                  // well, we'll see if the designated server can expand it, and if it can, we'll cache it locally
100                        vso = context.expandVS(source, false, expParams == null || !expParams.getParameterBool("excludeNested"));
101                        if (cacheFolder != null) {
102                          FileOutputStream s = new FileOutputStream(Utilities.path(cacheFolder, makeFileName(source.getUrl())));
103                          new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(s, vso.getValueset());
104                          s.close();
105                        }
106                }
107                if (vso.getValueset() != null)
108                  expansions.put(cacheKey, vso);
109                return vso;
110          }
111
112    private String makeCacheKey(ValueSet source, Parameters expParams) throws IOException {
113      if (expParams == null)
114        return source.getUrl();
115      JsonParser p = new JsonParser();
116      String r = p.composeString(expParams);
117      return source.getUrl() + " " + r.hashCode(); 
118    }
119
120  }
121
122  private static final String VS_ID_EXT = "http://tools/cache";
123
124  private final Map<String, ValueSetExpansionOutcome> expansions = new HashMap<String, ValueSetExpansionOutcome>();
125  private final Map<String, CanonicalResource> canonicals = new HashMap<String, CanonicalResource>();
126  private final IWorkerContext context;
127  private final String cacheFolder;
128
129  private Object lock;
130        
131        public ValueSetExpansionCache(IWorkerContext context, Object lock) {
132    super();
133    cacheFolder = null;
134    this.lock = lock;
135    this.context = context;
136  }
137  
138        public ValueSetExpansionCache(IWorkerContext context, String cacheFolder, Object lock) throws FHIRFormatError, IOException {
139    super();
140    this.context = context;
141    this.cacheFolder = cacheFolder;
142    this.lock = lock;
143    if (this.cacheFolder != null)
144      loadCache();
145  }
146  
147  private String makeFileName(String url) {
148    return url.replace("$", "").replace(":", "").replace("|", ".").replace("//", "/").replace("/", "_")+".xml";
149  }
150  
151  private void loadCache() throws FHIRFormatError, IOException {
152    File[] files = new File(cacheFolder).listFiles();
153    for (File f : files) {
154      if (f.getName().endsWith(".xml")) {
155        final FileInputStream is = new FileInputStream(f);
156        try {      
157          Resource r = new XmlParser().setOutputStyle(OutputStyle.PRETTY).parse(is);
158          if (r instanceof OperationOutcome) {
159            OperationOutcome oo = (OperationOutcome) r;
160            expansions.put(ToolingExtensions.getExtension(oo,VS_ID_EXT).getValue().toString(),
161                new ValueSetExpansionOutcome(new XhtmlComposer(XhtmlComposer.XML, false).composePlainText(oo.getText().getDiv()), TerminologyServiceErrorClass.UNKNOWN));
162          } else if (r instanceof ValueSet) {
163            ValueSet vs = (ValueSet) r;
164            if (vs.hasExpansion())
165              expansions.put(vs.getUrl(), new ValueSetExpansionOutcome(vs));
166            else {
167              canonicals.put(vs.getUrl(), vs);
168              if (vs.hasVersion())
169                canonicals.put(vs.getUrl()+"|"+vs.getVersion(), vs);
170            }
171          } else if (r instanceof CanonicalResource) {
172            CanonicalResource md = (CanonicalResource) r;
173            canonicals.put(md.getUrl(), md);
174            if (md.hasVersion())
175              canonicals.put(md.getUrl()+"|"+md.getVersion(), md);
176          }
177        } finally {
178          IOUtils.closeQuietly(is);
179        }
180      }
181    }
182  }
183
184  @Override
185        public ValueSetExpander getExpander() {
186                return new CacheAwareExpander();
187                // return new ValueSetExpander(valuesets, codesystems);
188        }
189
190  public CanonicalResource getStoredResource(String canonicalUri) {
191    synchronized (lock) {
192    return canonicals.get(canonicalUri);
193    }
194  }
195
196  public void storeResource(CanonicalResource md) throws IOException {
197    synchronized (lock) {
198      canonicals.put(md.getUrl(), md);
199      if (md.hasVersion())
200        canonicals.put(md.getUrl()+"|"+md.getVersion(), md);    
201    }
202    if (cacheFolder != null) {
203      FileOutputStream s = new FileOutputStream(Utilities.path(cacheFolder, makeFileName(md.getUrl()+"|"+md.getVersion())));
204      new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(s, md);
205      s.close();
206    }
207  }
208
209
210}