001package org.hl7.fhir.utilities.npm;
002
003import java.io.File;
004import java.io.FileInputStream;
005import java.io.IOException;
006import java.io.InputStream;
007import java.util.Date;
008import java.util.List;
009
010import org.hl7.fhir.utilities.TextFile;
011import org.hl7.fhir.utilities.Utilities;
012
013/**
014 * Implementation of a package client that keeps a local disk cache of downloaded artifacts
015 * in order to avoid re-downloading things
016 */
017public class CachingPackageClient extends PackageClient {
018
019  private String cacheFolder;
020
021
022  public CachingPackageClient(String address) {
023    super(address);
024    try {
025      cacheFolder = Utilities.path(System.getProperty("user.home"), ".fhir", "package-client");
026      Utilities.createDirectory(cacheFolder);
027    } catch (IOException e) {
028    }
029  }
030
031  public boolean exists(String id, String ver) throws IOException {
032    List<PackageInfo> vl = getVersions(id);
033    for (PackageInfo pi : vl) {
034      if (ver.equals(pi.getVersion())) {
035        return true;
036      }
037    }
038    return false;
039  }
040
041  public InputStream fetchCached(String url) throws IOException {
042    File cacheFile = new File(Utilities.path(cacheFolder, fn(url)));
043    if (cacheFile.exists()) {
044      return new FileInputStream(cacheFile);
045    }
046    InputStream fetchedPackage = super.fetchCached(url);
047    TextFile.bytesToFile(TextFile.streamToBytes(fetchedPackage), cacheFile);
048    return new FileInputStream(cacheFile);
049  }
050
051
052  public Date getNewPackages(Date lastCalled, List<PackageInfo> updates) {
053    return null;
054  }
055
056
057
058}