001package org.hl7.fhir.utilities.npm;
002
003import java.io.IOException;
004import java.io.InputStream;
005import java.util.ArrayList;
006import java.util.List;
007import java.util.function.Function;
008
009import javax.annotation.Nonnull;
010import javax.annotation.Nullable;
011
012import org.apache.commons.lang3.Validate;
013import org.hl7.fhir.exceptions.FHIRException;
014import org.hl7.fhir.utilities.Utilities;
015import org.slf4j.Logger;
016import org.slf4j.LoggerFactory;
017
018public abstract class BasePackageCacheManager implements IPackageCacheManager {
019
020  private static final Logger ourLog = LoggerFactory.getLogger(BasePackageCacheManager.class);
021  protected final List<PackageServer> myPackageServers;
022  private Function<PackageServer, PackageClient> myClientFactory = server -> new PackageClient(server);
023  protected boolean silent;
024
025  /**
026   * Constructor
027   */
028  public BasePackageCacheManager() {
029    super();
030    myPackageServers = new ArrayList<>();
031  }
032
033  protected BasePackageCacheManager(@Nonnull List<PackageServer> thePackageServers) {
034    myPackageServers = thePackageServers;
035  }
036  /**
037   * Provide a new client factory implementation
038   */
039  public void setClientFactory(Function<PackageServer, PackageClient> theClientFactory) {
040    Validate.notNull(theClientFactory, "theClientFactory must not be null");
041    myClientFactory = theClientFactory;
042  }
043
044  public List<PackageServer> getPackageServers() {
045    return myPackageServers;
046  }
047
048  /**
049   * Add a package server that can be used to fetch remote packages
050   */
051  public void addPackageServer(@Nonnull PackageServer thePackageServer) {
052    Validate.notNull(thePackageServer, "thePackageServer must not be null or empty");
053    if (!myPackageServers.contains(thePackageServer)) {
054      myPackageServers.add(thePackageServer);
055    }
056  }
057
058
059  /**
060   * Load the latest version of the identified package from the cache - it it exists
061   */
062  public NpmPackage loadPackageFromCacheOnly(String id) throws IOException {
063    return loadPackageFromCacheOnly(id, null);
064  }
065
066  /**
067   * Try to load a package from all registered package servers, and return <code>null</code>
068   * if it can not be found at any of them.
069   */
070  @Nullable
071  protected InputStreamWithSrc loadFromPackageServer(String id, String version) {
072
073    for (PackageServer nextPackageServer : getPackageServers()) {
074      if (okToUsePackageServer(nextPackageServer.getUrl(), id)) {
075        PackageClient packageClient = myClientFactory.apply(nextPackageServer);
076        try {
077          if (Utilities.noString(version)) {
078            version = packageClient.getLatestVersion(id);
079          }
080          if (version.endsWith(".x")) {
081            version = packageClient.getLatestVersion(id, version);
082            if (version == null) {
083              return null;
084            }
085          }
086
087          InputStream stream = packageClient.fetch(id, version);
088          String url = packageClient.url(id, version);
089          return new InputStreamWithSrc(stream, url, version);
090        } catch (IOException e) {
091          if (!silent) {
092            ourLog.info("Failed to resolve package {}#{} from server: {} ({})", id, version, nextPackageServer, e.getMessage());
093          }
094        }
095      }
096    }
097
098    return null;
099  }
100
101  // hack - we have a hacked 1.4.0 out there. Only packages2.fhir.org has it.
102  // this is not a long term thing, but it's not clear how to release patches for 
103  // 1.4.0
104  private boolean okToUsePackageServer(String server, String id) {
105    if (PackageServer.PRIMARY_SERVER.equals(server) && "hl7.fhir.r2b.core".equals(id)) {
106      return false;
107    }
108    return true;
109  }
110
111  public abstract NpmPackage loadPackageFromCacheOnly(String id, @Nullable String version) throws IOException;
112
113  @Override
114  public String getPackageUrl(String packageId) throws IOException {
115    String result = null;
116    NpmPackage npm = loadPackageFromCacheOnly(packageId);
117    if (npm != null) {
118      return npm.canonical();
119    }
120
121    for (PackageServer nextPackageServer : getPackageServers()) {
122      result = getPackageUrl(packageId, nextPackageServer);
123      if (result != null) {
124        return result;
125      }
126    }
127
128    return result;
129  }
130
131
132  private String getPackageUrl(String packageId, PackageServer server) throws IOException {
133    PackageClient pc = myClientFactory.apply(server);
134    List<PackageInfo> res = pc.search(packageId, null, null, false);
135    if (res.size() == 0) {
136      return null;
137    } else {
138      return res.get(0).getUrl();
139    }
140  }
141
142
143  @Override
144  public String getPackageId(String canonicalUrl) throws IOException {
145    String result = null;
146
147    for (PackageServer nextPackageServer : getPackageServers()) {
148      result = getPackageId(canonicalUrl, nextPackageServer);
149      if (result != null) {
150        break;
151      }
152    }
153
154    return result;
155  }
156
157  private String getPackageId(String canonical, PackageServer server) throws IOException {
158    if (canonical == null) {
159      return null;
160    }
161    PackageClient pc = myClientFactory.apply(server);
162    List<PackageInfo> res = pc.search(null, canonical, null, false);
163    if (res.size() == 0) {
164      return null;
165    } else {
166      // this is driven by HL7 Australia (http://hl7.org.au/fhir/ is the canonical url for the base package, and the root for all the others)
167      for (PackageInfo pi : res) {
168        if (canonical.equals(pi.getCanonical())) {
169          return pi.getId();
170        }
171      }
172      return res.get(0).getId();
173    }
174  }
175
176  public static class InputStreamWithSrc {
177
178    public InputStream stream;
179    public String url;
180    public String version;
181
182    public InputStreamWithSrc(InputStream stream, String url, String version) {
183      this.stream = stream;
184      this.url = url;
185      this.version = version;
186    }
187  }
188
189  public NpmPackage loadPackage(String idAndVer) throws FHIRException, IOException {
190    return loadPackage(idAndVer, null);
191  }
192
193
194  public void setSilent(boolean silent) {
195    this.silent = silent;    
196  }
197
198}