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