001package org.hl7.fhir.dstu3.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.dstu3.context.IWorkerContext;
072import org.hl7.fhir.dstu3.formats.IParser.OutputStyle;
073import org.hl7.fhir.dstu3.model.ExpansionProfile;
074import org.hl7.fhir.dstu3.model.OperationOutcome;
075import org.hl7.fhir.dstu3.model.Resource;
076import org.hl7.fhir.dstu3.model.ValueSet;
077import org.hl7.fhir.dstu3.terminologies.ValueSetExpander.TerminologyServiceErrorClass;
078import org.hl7.fhir.dstu3.terminologies.ValueSetExpander.ValueSetExpansionOutcome;
079import org.hl7.fhir.dstu3.utils.ToolingExtensions;
080import org.hl7.fhir.exceptions.FHIRFormatError;
081import org.hl7.fhir.utilities.Utilities;
082import org.hl7.fhir.utilities.xhtml.XhtmlComposer;
083
084public class ValueSetExpansionCache implements ValueSetExpanderFactory {
085
086  public class CacheAwareExpander implements ValueSetExpander {
087
088          @Override
089          public ValueSetExpansionOutcome expand(ValueSet source, ExpansionProfile profile) throws ETooCostly, IOException {
090            String cacheKey = makeCacheKey(source, profile);
091                if (expansions.containsKey(cacheKey))
092                        return expansions.get(cacheKey);
093                ValueSetExpander vse = new ValueSetExpanderSimple(context, ValueSetExpansionCache.this);
094                ValueSetExpansionOutcome vso = vse.expand(source, profile);
095                if (vso.getError() != null) {
096                  // well, we'll see if the designated server can expand it, and if it can, we'll cache it locally
097                        vso = context.expandVS(source, false, profile == null || !profile.getExcludeNested());
098                        if (cacheFolder != null) {
099                        FileOutputStream s = new FileOutputStream(Utilities.path(cacheFolder, makeFile(source.getUrl())));
100                        context.newXmlParser().setOutputStyle(OutputStyle.PRETTY).compose(s, vso.getValueset());
101                        s.close();
102                }
103                }
104                if (vso.getValueset() != null)
105                  expansions.put(cacheKey, vso);
106                return vso;
107          }
108
109    private String makeCacheKey(ValueSet source, ExpansionProfile profile) {
110      return profile == null ? source.getUrl() : source.getUrl() + " " + profile.getUrl()+" "+profile.getExcludeNested(); 
111    }
112
113    private String makeFile(String url) {
114      return url.replace("$", "").replace(":", "").replace("//", "/").replace("/", "_")+".xml";
115    }
116  }
117
118  private static final String VS_ID_EXT = "http://tools/cache";
119
120  private final Map<String, ValueSetExpansionOutcome> expansions = new HashMap<String, ValueSetExpansionOutcome>();
121  private final IWorkerContext context;
122  private final String cacheFolder;
123        
124        public ValueSetExpansionCache(IWorkerContext context) {
125    super();
126    cacheFolder = null;
127    this.context = context;
128  }
129  
130        public ValueSetExpansionCache(IWorkerContext context, String cacheFolder) throws FHIRFormatError, IOException {
131    super();
132    this.context = context;
133    this.cacheFolder = cacheFolder;
134    if (this.cacheFolder != null)
135      loadCache();
136  }
137  
138        private void loadCache() throws FHIRFormatError, IOException {
139          File[] files = new File(cacheFolder).listFiles();
140    for (File f : files) {
141      if (f.getName().endsWith(".xml")) {
142        final FileInputStream is = new FileInputStream(f);
143        try {      
144        Resource r = context.newXmlParser().setOutputStyle(OutputStyle.PRETTY).parse(is);
145        if (r instanceof OperationOutcome) {
146          OperationOutcome oo = (OperationOutcome) r;
147          expansions.put(ToolingExtensions.getExtension(oo,VS_ID_EXT).getValue().toString(),
148            new ValueSetExpansionOutcome(new XhtmlComposer(XhtmlComposer.XML).composePlainText(oo.getText().getDiv()), TerminologyServiceErrorClass.UNKNOWN));
149        } else {
150          ValueSet vs = (ValueSet) r; 
151          expansions.put(vs.getUrl(), new ValueSetExpansionOutcome(vs));
152        }
153        } finally {
154          IOUtils.closeQuietly(is);
155        }
156      }
157    }
158  }
159
160  @Override
161        public ValueSetExpander getExpander() {
162                return new CacheAwareExpander();
163                // return new ValueSetExpander(valuesets, codesystems);
164        }
165
166}