001package org.hl7.fhir.utilities.npm;
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
034import java.io.BufferedOutputStream;
035import java.io.ByteArrayInputStream;
036import java.io.ByteArrayOutputStream;
037import java.io.File;
038import java.io.FileInputStream;
039import java.io.FileNotFoundException;
040import java.io.FileOutputStream;
041import java.io.IOException;
042import java.io.InputStream;
043import java.io.OutputStream;
044import java.nio.charset.StandardCharsets;
045import java.text.ParseException;
046import java.text.SimpleDateFormat;
047import java.time.LocalDate;
048import java.util.*;
049import java.util.zip.Deflater;
050import java.util.zip.ZipEntry;
051import java.util.zip.ZipInputStream;
052
053import javax.annotation.Nonnull;
054
055import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
056import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
057import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
058import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
059import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
060import org.apache.commons.compress.compressors.gzip.GzipParameters;
061import org.hl7.fhir.exceptions.FHIRException;
062import org.hl7.fhir.utilities.ByteProvider;
063import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
064import org.hl7.fhir.utilities.StringPair;
065import org.hl7.fhir.utilities.FileUtilities;
066import org.hl7.fhir.utilities.Utilities;
067import org.hl7.fhir.utilities.filesystem.ManagedFileAccess;
068import org.hl7.fhir.utilities.http.HTTPResult;
069import org.hl7.fhir.utilities.http.ManagedWebAccess;
070import org.hl7.fhir.utilities.json.JsonException;
071import org.hl7.fhir.utilities.json.model.JsonArray;
072import org.hl7.fhir.utilities.json.model.JsonElement;
073import org.hl7.fhir.utilities.json.model.JsonObject;
074import org.hl7.fhir.utilities.json.model.JsonProperty;
075import org.hl7.fhir.utilities.json.parser.JsonParser;
076import org.hl7.fhir.utilities.npm.PackageGenerator.PackageType;
077
078/**
079 * info and loader for a package 
080 * 
081 * Packages may exist on disk in the cache, or purely in memory when they are loaded on the fly
082 * 
083 * Packages are contained in subfolders (see the package spec). The FHIR resources will be in "package"
084 * 
085 * @author Grahame Grieve
086 *
087 */
088public class NpmPackage {
089
090  public interface ITransformingLoader {
091
092    byte[] load(File f);
093
094  }
095
096  public class PackageResourceInformationSorter implements Comparator<PackageResourceInformation> {
097    @Override
098    public int compare(PackageResourceInformation o1, PackageResourceInformation o2) {
099      return o1.filename.compareTo(o2.filename);
100    }
101  }
102  
103  public class PackageResourceInformation {
104    private String id;
105    private String resourceType;
106    private String url;
107    private String version;
108    private String filename;
109    private String supplements;
110    private String stype;
111    private String derivation;
112    private String content;
113    
114    public PackageResourceInformation(String root, JsonObject fi) throws IOException {
115      super();
116      id = fi.asString("id");
117      resourceType = fi.asString("resourceType");
118      url = fi.asString("url");
119      version = fi.asString("version");
120      filename = Utilities.path(root, fi.asString("filename"));
121      supplements = fi.asString("supplements");
122      stype = fi.asString("type");
123      derivation = fi.asString("derivation");
124      content = fi.asString("content");
125    }
126    public String getId() {
127      return id;
128    }
129    public String getResourceType() {
130      return resourceType;
131    }
132    public String getStatedType() {
133      return stype;
134    }
135    public String getUrl() {
136      return url;
137    }
138    public String getVersion() {
139      return version;
140    }
141    public String getFilename() {
142      return filename;
143    }
144    public String getSupplements() {
145      return supplements;
146    }
147    public boolean hasId() {
148      return !Utilities.noString(id);
149    }
150    public String getDerivation() {
151      return derivation;
152    }
153    public String getContent() {
154      return content;
155    }
156    
157  }
158  public class IndexVersionSorter implements Comparator<JsonObject> {
159
160    @Override
161    public int compare(JsonObject o0, JsonObject o1) {
162      String v0 = o0.asString("version"); 
163      String v1 = o1.asString("version"); 
164      return v0.compareTo(v1);
165    }
166  }
167
168  public static class PackagedResourceFile {
169    private String folder;
170    private String filename;
171    private String resourceType;
172    protected PackagedResourceFile(String folder, String filename, String resourceType) {
173      super();
174      this.folder = folder;
175      this.filename = filename;
176      this.resourceType = resourceType;
177    }
178    public String getFolder() {
179      return folder;
180    }
181    public String getFilename() {
182      return filename;
183    }
184    public String getResourceType() {
185      return resourceType;
186    }
187    public static class Sorter implements Comparator<PackagedResourceFile> {
188
189      @Override
190      public int compare(PackagedResourceFile o1, PackagedResourceFile o2) {
191        int res = o1.folder.compareTo(o2.folder);
192        if (res == 0) {
193          res = o1.filename.compareTo(o2.filename);
194        }
195        return res;
196      }
197      
198    }
199  }
200  
201  public static boolean isValidName(String pid) {
202    return pid.matches("^[a-z][a-zA-Z0-9]*(\\.[a-z][a-zA-Z0-9\\-]*)+$");
203  }
204
205  public static boolean isValidVersion(String ver) {
206    return ver.matches("^[0-9]+\\.[0-9]+\\.[0-9]+$");
207  }
208
209  public class NpmPackageFolder {
210    private String folderName;
211    private Map<String, List<String>> types;
212    private Map<String, byte[]> content;
213    private JsonObject cachedIndex;
214    private File folder;
215
216    public NpmPackageFolder(String folderName) {
217      super();
218      this.folderName = folderName;
219      if (!minimalMemory) {
220        types = new HashMap<>();
221        content = new HashMap<>();
222      }
223    }
224
225    private String fn(String name) throws IOException {
226      return Utilities.path(folder.getAbsolutePath(), name);
227    }
228
229    public Map<String, List<String>> getTypes() throws JsonException, IOException {
230      if (minimalMemory) {
231        Map<String, List<String>> typeMap = new HashMap<>();
232        readIndex(JsonParser.parseObjectFromFile(fn(".index.json")), typeMap);
233        return typeMap;
234      } else {
235        return types;
236      }
237    }
238
239    public String getFolderName() {
240      return folderName;
241    }
242
243    public String getFolderPath() {
244      return folder == null ? null : folder.getAbsolutePath();
245    }
246    
247    public boolean readIndex(JsonObject index, Map<String, List<String>> typeMap) {
248      if (!index.has("index-version") || (index.asInteger("index-version") != NpmPackageIndexBuilder.CURRENT_INDEX_VERSION)) {
249        return false;
250      }
251      if (!minimalMemory) {
252        this.cachedIndex = index;
253      }
254      for (JsonObject file : index.getJsonObjects("files")) {
255        String type = file.asString("resourceType");
256        String name = file.asString("filename");
257        if (!typeMap.containsKey(type))
258          typeMap.put(type, new ArrayList<>());
259        typeMap.get(type).add(name);
260      }
261      return true;
262    }
263
264    public List<String> listFiles() {
265      List<String> res = new ArrayList<>();
266      if (folder != null) {
267        if (folder.exists()) {
268          for (File f : folder.listFiles()) {
269            if (!f.isDirectory() && !Utilities.existsInList(f.getName(), "package.json", ".index.json", ".index.db", ".oids.json", ".oids.db")) {
270              res.add(f.getName());
271            }
272          }
273        }
274      } else {
275        for (String s : content.keySet()) {
276          if (!Utilities.existsInList(s, "package.json", ".index.json", ".index.db", ".oids.json", ".oids.db")) {
277            res.add(s);
278          }
279        }
280      }
281      Collections.sort(res);
282      return res;
283    }
284
285    public Map<String, byte[]> getContent() {
286      assert !minimalMemory;
287      
288      return content;
289    }
290
291    public byte[] fetchFile(String file) throws FileNotFoundException, IOException {
292      if (folder != null) {
293        File f = ManagedFileAccess.file(Utilities.path(folder.getAbsolutePath(), file));
294        if (f.exists()) {
295          return FileUtilities.fileToBytes(f);
296        } else {
297          return null;
298        }
299      } else {
300        return content.get(file);
301      }
302    }
303
304    public ByteProvider getProvider(String file) throws FileNotFoundException, IOException {
305      if (folder != null) {
306        File f = ManagedFileAccess.file(Utilities.path(folder.getAbsolutePath(), file));
307        if (f.exists()) {
308          return ByteProvider.forFile(f);
309        } else {
310          return null;
311        }
312      } else {
313        return ByteProvider.forBytes(content.get(file));
314      }
315    }
316
317    public boolean hasFile(String file) throws IOException {
318      if (folder != null) {
319        return ManagedFileAccess.file(Utilities.path(folder.getAbsolutePath(), file)).exists();
320      } else {
321        return content.containsKey(file);
322      }
323
324    }
325
326    public String dump() {
327      return folderName + " ("+ (folder == null ? "null" : folder.toString())+")"+(minimalMemory ? "" : " | "+Boolean.toString(cachedIndex != null)+" | "+content.size()+" | "+types.size());
328    }
329
330    public void removeFile(String n) throws IOException {
331      if (folder != null) {
332        ManagedFileAccess.file(Utilities.path(folder.getAbsolutePath(), n)).delete();
333      } else {
334        content.remove(n);
335      }
336      changedByLoader = true;      
337    }
338
339    public JsonObject index() throws IOException {
340      if (cachedIndex != null) {
341        return cachedIndex;
342      } else if (folder == null) {
343        return null;
344      } else {
345        File ij = ManagedFileAccess.file(fn(".index.json"));
346        if (ij.exists()) {
347          return JsonParser.parseObject(ij);
348        } else {
349          return null;
350        }
351      }
352    }
353    public JsonObject oidIndex() throws IOException {
354      if (folder == null) {
355        return null;
356      } else {
357        File ij = ManagedFileAccess.file(fn(".oids.json"));
358        if (ij.exists()) {
359          return JsonParser.parseObject(ij);
360        } else {
361          return null;
362        }
363      }
364    }
365
366
367  }
368
369
370  private String path;
371  private JsonObject npm;
372  private Map<String, NpmPackageFolder> folders = new HashMap<>();
373  private boolean changedByLoader; // internal qa only!
374  private Map<String, Object> userData;
375  private boolean minimalMemory;
376  private int size;
377  private boolean warned = false;
378  private static boolean loadCustomResources;
379
380  /**
381   * Constructor
382   */
383  private NpmPackage() {
384    super();
385  }
386
387  /**
388   * Factory method that parses a package from an extracted folder
389   */
390  public static NpmPackage fromFolder(String path) throws IOException {
391    return fromFolder(path, true);
392  }
393
394  public static NpmPackage fromFolder(String path, boolean checkIndexed) throws IOException {
395    NpmPackage res = new NpmPackage();
396    res.loadFiles(path, ManagedFileAccess.file(path));
397    if (checkIndexed) {
398     res.checkIndexed(path);
399    }
400    return res;
401  }
402
403  /**
404   * Factory method that parses a package from an extracted folder
405   */
406  public static NpmPackage fromFolderMinimal(String path) throws IOException {
407    return fromFolderMinimal(path, true);
408  }
409
410  public static NpmPackage fromFolderMinimal(String path, boolean checkIndexed) throws IOException {
411    NpmPackage res = new NpmPackage();
412    res.minimalMemory = true;
413    res.loadFiles(path, ManagedFileAccess.file(path));
414    if (checkIndexed) {
415    res.checkIndexed(path);}
416    return res;
417  }
418
419  /**
420   * Factory method that starts a new empty package using the given PackageGenerator to create the manifest
421   */
422  public static NpmPackage empty(PackageGenerator thePackageGenerator) {
423    NpmPackage retVal = new NpmPackage();
424    retVal.npm = thePackageGenerator.getRootJsonObject();
425    return retVal;
426  }
427
428  /**
429   * Factory method that starts a new empty package using the given PackageGenerator to create the manifest
430   */
431  public static NpmPackage empty() {
432    NpmPackage retVal = new NpmPackage();
433    return retVal;
434  }
435
436  public Map<String, Object> getUserData() {
437    if (userData == null) {
438      userData = new HashMap<>();
439    }
440    return userData;
441  }
442
443  public void loadFiles(String path, File source, String... exemptions) throws FileNotFoundException, IOException {
444    this.npm = JsonParser.parseObject(FileUtilities.fileToString(Utilities.path(path, "package", "package.json")));
445    this.path = path;
446
447    File dir = ManagedFileAccess.file(path);
448    for (File f : dir.listFiles()) {
449      if (!isInternalExemptFile(f) && !Utilities.existsInList(f.getName(), exemptions)) {
450        if (f.isDirectory()) {
451          String d = f.getName();
452          if (!d.equals("package")) {
453            d = Utilities.path("package", d);
454          }
455          File ij = ManagedFileAccess.file(Utilities.path(f.getAbsolutePath(), ".index.json"));
456          NpmPackageFolder folder = this.new NpmPackageFolder(d);
457          folder.folder = f;
458          this.folders.put(d, folder);
459          if (ij.exists() || !minimalMemory) {
460            if (!minimalMemory) {
461              try {
462                if (!ij.exists() || !folder.readIndex(JsonParser.parseObject(ij), folder.getTypes())) {
463                  indexFolder(folder.getFolderName(), folder);
464                }
465              } catch (Exception e) {
466                throw new IOException("Error parsing "+ij.getAbsolutePath()+": "+e.getMessage(), e);
467              }
468            }
469          }
470          loadSubFolders(dir.getAbsolutePath(), f);
471
472        } else {
473          NpmPackageFolder folder = this.new NpmPackageFolder(Utilities.path("package", "$root"));
474          folder.folder = dir;
475          this.folders.put(Utilities.path("package", "$root"), folder);        
476        }
477      }
478    }
479  }
480
481  public static boolean isInternalExemptFile(File f) {
482    return Utilities.existsInList(f.getName(), ".git", ".svn", ".DS_Store") || Utilities.existsInList(f.getName(), "package-list.json") ||
483        Utilities.endsWithInList(f.getName(), ".tgz");
484  }
485
486  private void loadSubFolders(String rootPath, File dir) throws IOException {
487    for (File f : dir.listFiles()) {
488      if (f.isDirectory()) {
489        if (!"custom".equals(f.getName()) || loadCustomResources) {
490          String d = f.getAbsolutePath().substring(rootPath.length()+1);
491          if (!d.startsWith("package")) {
492            d = Utilities.path("package", d);
493          }
494          NpmPackageFolder folder = this.new NpmPackageFolder(d);
495          folder.folder = f;
496          this.folders.put(d, folder);
497          File ij = ManagedFileAccess.file(Utilities.path(f.getAbsolutePath(), ".index.json"));
498          if (ij.exists() || !minimalMemory) {
499            try {
500              if (!ij.exists() || !folder.readIndex(JsonParser.parseObject(ij), folder.getTypes())) {
501                indexFolder(folder.getFolderName(), folder);
502              }
503            } catch (Exception e) {
504              throw new IOException("Error parsing "+ij.getAbsolutePath()+": "+e.getMessage(), e);
505            }
506          }
507          loadSubFolders(rootPath, f); 
508        }
509      }
510    }    
511  }
512
513  public static NpmPackage fromFolder(String folder, PackageType defType, String... exemptions) throws IOException {
514    NpmPackage res = new NpmPackage();
515    res.loadFiles(folder, ManagedFileAccess.file(folder), exemptions);
516    if (!res.folders.containsKey("package")) {
517      res.folders.put("package", res.new NpmPackageFolder("package"));
518    }
519    if (!res.folders.get("package").hasFile("package.json") && defType != null) {
520      FileUtilities.stringToFile("{ \"type\" : \""+defType.getCode()+"\"}", Utilities.path(res.folders.get("package").folder.getAbsolutePath(), "package.json"));
521    }
522    res.npm = JsonParser.parseObject(new String(res.folders.get("package").fetchFile("package.json")));
523    return res;
524  }
525
526  private static final int BUFFER_SIZE = 1024;
527
528  public static @Nonnull NpmPackage fromPackage(InputStream tgz) throws IOException {
529    return fromPackage(tgz, null, false);
530  }
531
532  public static NpmPackage fromPackage(InputStream tgz, String desc) throws IOException {
533    return fromPackage(tgz, desc, false);
534  }
535
536  public static NpmPackage fromPackage(InputStream tgz, String desc, boolean progress) throws IOException {
537    NpmPackage res = new NpmPackage();
538    res.readStream(tgz, desc, progress);
539    return res;
540  }
541  
542  public static NpmPackage extractFromTgz(InputStream tgz, String desc, String tempDir, boolean minimal) throws IOException {
543    FileUtilities.createDirectory(tempDir);
544
545    int size = 0;
546    
547    GzipCompressorInputStream gzipIn;
548    try {
549      gzipIn = new GzipCompressorInputStream(tgz);
550    } catch (Exception e) {
551      throw new IOException("Error reading "+(desc == null ? "package" : desc)+": "+e.getMessage(), e);      
552    }
553    try (TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn)) {
554      TarArchiveEntry entry;
555
556      while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {
557        String n = entry.getName();
558        if (n.contains("/..") || n.contains("../")) {
559          throw new RuntimeException("Entry with an illegal name: " + n);
560        }
561        if (entry.isDirectory()) {
562          if (!Utilities.noString(n)) {
563            String dir = n.substring(0, n.length()-1);
564            FileUtilities.createDirectory(Utilities.path(tempDir, dir));
565          }
566        } else {
567          int count;
568          byte data[] = new byte[BUFFER_SIZE];
569          String filename = Utilities.path(tempDir, n);
570          String folder = FileUtilities.getDirectoryForFile(filename);
571          FileUtilities.createDirectory(folder);
572          FileOutputStream fos = ManagedFileAccess.outStream(filename);
573          try (BufferedOutputStream dst = new BufferedOutputStream(fos, BUFFER_SIZE)) {
574            while ((count = tarIn.read(data, 0, BUFFER_SIZE)) != -1) {
575              dst.write(data, 0, count);
576              size = size + count;
577            }
578          }
579          fos.close();
580        }
581      }
582    } 
583    try {
584      NpmPackage npm = NpmPackage.fromFolderMinimal(tempDir);
585      npm.setSize(size);
586      if (!minimal) {
587        npm.checkIndexed(desc);
588      }
589      return npm;
590    } catch (Exception e) {
591      throw new IOException("Error parsing "+(desc == null ? "" : desc+"#")+"package/package.json: "+e.getMessage(), e);
592    } 
593  }
594  
595  public void readStream(InputStream tgz, String desc, boolean progress) throws IOException {
596    GzipCompressorInputStream gzipIn;
597    try {
598      gzipIn = new GzipCompressorInputStream(tgz);
599    } catch (Exception e) {
600      throw new IOException("Error reading "+(desc == null ? "package" : desc)+": "+e.getMessage(), e);      
601    }
602    try (TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn)) {
603      TarArchiveEntry entry;
604
605      int i = 0;
606      int c = 12;
607      while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {
608        i++;
609        String n = entry.getName();
610        if (n.contains("..")) {
611          throw new RuntimeException("Entry with an illegal name: " + n);
612        }
613        if (entry.isDirectory()) {
614          String dir = n.substring(0, n.length()-1);
615          if (dir.startsWith("package/")) {
616            dir = dir.substring(8);
617          }
618          folders.put(dir, new NpmPackageFolder(dir));
619        } else {
620          int count;
621          byte data[] = new byte[BUFFER_SIZE];
622          ByteArrayOutputStream fos = new ByteArrayOutputStream();
623          try (BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) {
624            while ((count = tarIn.read(data, 0, BUFFER_SIZE)) != -1) {
625              dest.write(data, 0, count);
626            }
627          }
628          fos.close();
629          loadFile(n, fos.toByteArray());
630        }
631        if (progress && i % 50 == 0) {
632          c++;
633          System.out.print(".");
634          if (c == 120) {
635            System.out.println("");
636            System.out.print("  ");
637            c = 2;
638          }
639        }
640      }
641    } 
642    try {
643      npm = JsonParser.parseObject(folders.get("package").fetchFile("package.json"));
644    } catch (Exception e) {
645      throw new IOException("Error parsing "+(desc == null ? "" : desc+"#")+"package/package.json: "+e.getMessage(), e);
646    }
647    checkIndexed(desc);
648  }
649
650  public void loadFile(String n, byte[] data) throws IOException {
651    // work around a bug: 
652    n = n.replace("//", "/");
653    String dir = n.contains("/") ? n.substring(0, n.lastIndexOf("/")) : "$root";
654    if (dir.startsWith("package/")) {
655      dir = dir.substring(8);
656    }
657    n = n.substring(n.lastIndexOf("/")+1);
658    NpmPackageFolder index = folders.get(dir);
659    if (index == null) {
660      index = new NpmPackageFolder(dir);
661      folders.put(dir, index);
662    }
663    index.content.put(n, data);
664  }
665
666  public boolean isIndexed() throws IOException {
667    for (NpmPackageFolder folder : folders.values()) {
668      JsonObject index = folder.index();
669      if (folder.index() == null || index.forceArray("files").size() == 0) {
670        return false;
671      }
672    }
673    return true;
674  }
675
676
677  public void checkIndexed(String path) throws IOException {
678    for (NpmPackageFolder folder : folders.values()) {
679      JsonObject index = folder.index();
680      if (index == null || index.forceArray("files").size() == 0) {
681        indexFolder(path, folder);
682      }  
683    }
684  }
685
686
687  /**
688   * Create a package .index.json file for a package folder.
689   * <p>
690   * See <a href="https://hl7.org/fhir/packages.html#2.1.10.4">the FHIR specification</a> for details on .index.json
691   * format and usage.
692   *
693   * @param path
694   * @param folder
695   * @throws FileNotFoundException
696   * @throws IOException
697   */
698  public void indexFolder(String path, NpmPackageFolder folder) throws FileNotFoundException, IOException {
699    List<String> remove = new ArrayList<>();
700    NpmPackageIndexBuilder indexer = new NpmPackageIndexBuilder();
701    indexer.start(folder.folder != null ? Utilities.path(folder.folder.getAbsolutePath(), ".index.db") : null);
702    for (String file : folder.listFiles()) {
703      if (!indexer.seeFile(file, folder.fetchFile(file))) {
704        remove.add(file);
705      }
706    } 
707    for (String n : remove) {
708      folder.removeFile(n);
709    }
710    String json = indexer.build();
711    
712    try {
713      if (!minimalMemory) {
714        folder.readIndex(JsonParser.parseObject(json), folder.getTypes());
715      }
716      if (folder.folder != null) {
717        FileUtilities.stringToFile(json, Utilities.path(folder.folder.getAbsolutePath(), ".index.json"));
718      }
719    } catch (Exception e) {
720      FileUtilities.stringToFile(json, Utilities.path("[tmp]", ".index.json"));
721      throw new IOException("Error parsing "+(path == null ? "" : path+"#")+"package/"+folder.folderName+"/.index.json: "+e.getMessage(), e);
722    }
723  }
724
725
726  public static NpmPackage fromZip(InputStream stream, boolean dropRootFolder, String desc) throws IOException {
727    NpmPackage res = new NpmPackage();
728    ZipInputStream zip = new ZipInputStream(stream);
729    ZipEntry ze;
730    while ((ze = zip.getNextEntry()) != null) {
731      int size;
732      byte[] buffer = new byte[2048];
733
734      ByteArrayOutputStream bytes = new ByteArrayOutputStream();
735      BufferedOutputStream bos = new BufferedOutputStream(bytes, buffer.length);
736
737      while ((size = zip.read(buffer, 0, buffer.length)) != -1) {
738        bos.write(buffer, 0, size);
739      }
740      bos.flush();
741      bos.close();
742      if (bytes.size() > 0) {
743        if (dropRootFolder) {
744          res.loadFile(ze.getName().substring(ze.getName().indexOf("/")+1), bytes.toByteArray());
745        } else {
746          res.loadFile(ze.getName(), bytes.toByteArray());
747        }
748      }
749      zip.closeEntry();
750    }
751    zip.close();         
752    try {
753      res.npm = JsonParser.parseObject(res.folders.get("package").fetchFile("package.json"));
754    } catch (Exception e) {
755      throw new IOException("Error parsing "+(desc == null ? "" : desc+"#")+"package/package.json: "+e.getMessage(), e);
756    }
757    res.checkIndexed(desc);
758    return res;
759  }
760
761
762  /**
763   * Accessing the contents of the package - get a list of files in a subfolder of the package 
764   *
765   * @param folder
766   * @return
767   * @throws IOException 
768   */
769  public List<String> list(String folder) throws IOException {
770    List<String> res = new ArrayList<String>();
771    if (folders.containsKey(folder)) {
772      for (String s : folders.get(folder).listFiles()) {
773        if (!s.startsWith(".")) {
774          res.add(s);
775        }
776      }
777    } else if (folders.containsKey(Utilities.path("package", folder))) {
778      for (String s : folders.get(Utilities.path("package", folder)).listFiles()) {
779        if (!s.startsWith(".")) {
780          res.add(s);
781        }
782      }
783    }
784    return res;
785  }
786
787  public List<String> listResources(String... types) throws IOException {
788    return listResources(Utilities.strings(types));
789  }
790  
791  public List<String> listResourcesinFolder(String folder, String... types) throws IOException {
792    return listResourcesInFolder(folder, Utilities.strings(types));
793  }
794  
795  public List<String> listResources(List<String> types) throws IOException {
796    return listResourcesInFolder("package", types);
797  }
798  
799  public List<String> listResourcesInFolder(String folderName, List<String> types) throws IOException {
800    List<String> res = new ArrayList<String>();
801    NpmPackageFolder folder = folders.get(folderName);
802    if (types.size() == 0) {
803      for (String s : folder.types.keySet()) {
804        if (folder.types.containsKey(s)) {
805          res.addAll(folder.types.get(s));
806        }
807      }
808    } else {
809      for (String s : types) {
810        if (folder.types.containsKey(s)) {
811          res.addAll(folder.types.get(s));
812        }
813      }
814    }
815    Collections.sort(res);
816    return res;
817  }
818
819  public List<PackagedResourceFile> listAllResources(Collection<String> types) throws IOException {
820    List<PackagedResourceFile> res = new ArrayList<PackagedResourceFile>();
821    for (NpmPackageFolder folder : folders.values()) {
822      if (types.size() == 0) {
823        for (String s : folder.types.keySet()) {
824          if (folder.types.containsKey(s)) {
825            for (String n : folder.types.get(s)) {
826              res.add(new PackagedResourceFile(folder.folderName, n, s));
827            }
828          }
829        }
830      } else {
831        for (String s : types) {
832          if (folder.types.containsKey(s)) {
833            for (String n : folder.types.get(s)) {
834              res.add(new PackagedResourceFile(folder.folderName, n, s));
835            }
836          }
837        }
838      }
839    }
840    Collections.sort(res, new PackagedResourceFile.Sorter());
841    return res;
842  }
843
844  public List<PackageResourceInformation> listIndexedResources(String... types) throws IOException {
845    return listIndexedResources(Utilities.strings(types));
846  }
847  
848  public List<PackageResourceInformation> listIndexedResources(List<String> types) throws IOException {
849    List<PackageResourceInformation> res = new ArrayList<PackageResourceInformation>();
850    for (NpmPackageFolder folder : folders.values()) {
851      JsonObject index = folder.index();
852      if (index != null) {
853        for (JsonObject fi : index.getJsonObjects("files")) {
854          if (Utilities.existsInList(fi.asString("resourceType"), types) || types.isEmpty()) {
855            res.add(new PackageResourceInformation(folder.folder == null ? "@"+folder.getFolderName() : folder.folder.getAbsolutePath(), fi));
856          }
857        }
858      }
859    } 
860    //    Collections.sort(res, new PackageResourceInformationSorter());
861    return res;
862  }
863
864  /**
865   * use the name from listResources()
866   * 
867   * @param file
868   * @return
869   * @throws IOException
870   */
871  public InputStream loadResource(String file) throws IOException {
872    NpmPackageFolder folder = folders.get("package");
873    return new ByteArrayInputStream(folder.fetchFile(file));
874  }
875
876  /**
877   * get a stream that contains the contents of a resource in the base folder, by it's canonical URL
878   * 
879   * @param canonical - the canonical URL of the resource (exact match only)
880   * @return null if it is not found
881   * @throws IOException
882   */
883  public InputStream loadByCanonical(String canonical) throws IOException {
884    return loadByCanonicalVersion("package", canonical, null);    
885  }
886  
887  /**
888   * get a stream that contains the contents of a resource in the nominated folder, by it's canonical URL
889   * 
890   * @param folder - one of the folders in the package (main folder is "package")
891   * @param canonical - the canonical URL of the resource (exact match only)
892   * @return null if it is not found
893   * @throws IOException
894   */
895  public InputStream loadByCanonical(String folder, String canonical) throws IOException {
896    return loadByCanonicalVersion(folder, canonical, null);    
897  }
898    
899  /**
900   * get a stream that contains the contents of a resource in the base folder, by it's canonical URL
901   * 
902   * @param canonical - the canonical URL of the resource (exact match only)
903   * @param version - the specified version (or null if the most recent)
904   * 
905   * @return null if it is not found
906   * @throws IOException
907   */
908  public InputStream loadByCanonicalVersion(String canonical, String version) throws IOException {
909    return loadByCanonicalVersion("package", canonical, version);
910  }
911  
912  /**
913   * get a stream that contains the contents of a resource in the nominated folder, by it's canonical URL
914   * 
915   * @param folder - one of the folders in the package (main folder is "package")
916   * @param canonical - the canonical URL of the resource (exact match only)
917   * @param version - the specified version (or null if the most recent)
918   * 
919   * @return null if it is not found
920   * @throws IOException
921   */
922  public InputStream loadByCanonicalVersion(String folder, String canonical, String version) throws IOException {
923    NpmPackageFolder f = folders.get(folder);
924    List<JsonObject> matches = new ArrayList<>();
925    for (JsonObject file : f.index().getJsonObjects("files")) {
926      if (canonical.equals(file.asString("url"))) {
927        if (version != null && version.equals(file.asString("version"))) {
928          return load("package", file.asString("filename"));
929        } else if (version == null) {
930          matches.add(file);
931        }
932      }
933      if (matches.size() > 0) {
934        if (matches.size() == 1) {
935          return load("package", matches.get(0).asString("filename"));          
936        } else {
937          Collections.sort(matches, new IndexVersionSorter());
938          return load("package", matches.get(matches.size()-1).asString("filename"));          
939        }
940      }
941    }
942    return null;        
943  }
944    
945  /**
946   * get a stream that contains the contents of one of the files in the base package
947   * 
948   * @param file
949   * @return
950   * @throws IOException
951   */
952  public InputStream load(String file) throws IOException {
953    return load("package", file);
954  }
955  
956  /**
957   * get a stream that contains the contents of one of the files in a folder
958   * 
959   * @param folder
960   * @param file
961   * @return
962   * @throws IOException
963   */
964  public InputStream load(String folder, String file) throws IOException {
965    NpmPackageFolder f = folders.get(folder);
966    if (f == null) {
967      f = folders.get(Utilities.path("package", folder));
968    }
969    if (f != null && f.hasFile(file)) {
970      return new ByteArrayInputStream(f.fetchFile(file));
971    } else {
972      throw new IOException("Unable to find the file "+folder+"/"+file+" in the package "+name());
973    }
974  }
975
976  /**
977   * get a stream that contains the contents of one of the files in a folder
978   * 
979   * @param folder
980   * @param file
981   * @return
982   * @throws IOException
983   */
984  public ByteProvider getProvider(String folder, String file) throws IOException {
985    NpmPackageFolder f = folders.get(folder);
986    if (f == null) {
987      f = folders.get(Utilities.path("package", folder));
988    }
989    if (f != null && f.hasFile(file)) {
990      return f.getProvider(file);
991    } else {
992      throw new IOException("Unable to find the file "+folder+"/"+file+" in the package "+name());
993    }
994  }
995
996  
997  public boolean hasFile(String folder, String file) throws IOException {
998    NpmPackageFolder f = folders.get(folder);
999    if (f == null) {
1000      f = folders.get(Utilities.path("package", folder));
1001    }
1002    return f != null && f.hasFile(file);
1003  }
1004
1005
1006  /**
1007   * Handle to the package json file
1008   * 
1009   * @return
1010   */
1011  public JsonObject getNpm() {
1012    return npm;
1013  }
1014
1015  /**
1016   *  should only use this when npm == null
1017   * 
1018   * @param npm
1019   */
1020  public void setNpm(JsonObject npm) {
1021    this.npm = npm;
1022  }
1023
1024  /**
1025   * convenience method for getting the package name
1026   * @return
1027   */
1028  public String name() {
1029    return npm.asString("name");
1030  }
1031
1032  /**
1033   * convenience method for getting the package id (which in NPM language is the same as the name)
1034   * @return
1035   */
1036  public String id() {
1037    return npm.asString("name");
1038  }
1039
1040  public String date() {
1041    return npm.asString("date");
1042  }
1043
1044  public String canonical() {
1045    return npm.asString("canonical");
1046  }
1047
1048  /**
1049   * convenience method for getting the package version
1050   * @return
1051   */
1052  public String version() {
1053    return npm.asString("version");
1054  }
1055
1056  /**
1057   * convenience method for getting the package fhir version
1058   * @return
1059   */
1060  public String fhirVersion() {
1061    if ("hl7.fhir.core".equals(npm.asString("name")))
1062      return npm.asString("version");
1063    else if (
1064        Utilities.existsInList(npm.asString("type"), "fhir.core", "fhir.examples") &&
1065        Utilities.startsWithInList( npm.asString("name"), "hl7.fhir.r2.", "hl7.fhir.r2b.", "hl7.fhir.r3.", 
1066             "hl7.fhir.r4.", "hl7.fhir.r4b.", "hl7.fhir.r5.")) {
1067      return npm.asString("version");
1068    } else {
1069      JsonObject dep = null;
1070      if (npm.hasObject("dependencies")) {
1071        dep = npm.getJsonObject("dependencies");
1072        if (dep != null) {
1073          for (JsonProperty e : dep.getProperties()) {
1074            if (Utilities.existsInList(e.getName(), "hl7.fhir.r2.core", "hl7.fhir.r2b.core", "hl7.fhir.r3.core", "hl7.fhir.r4.core"))
1075              return e.getValue().asString();
1076            if (Utilities.existsInList(e.getName(), "hl7.fhir.core")) // while all packages are updated
1077              return e.getValue().asString();
1078          }
1079        }
1080      }
1081      if (npm.hasArray("fhirVersions")) {
1082        JsonArray e = npm.getJsonArray("fhirVersions");
1083        if (e.size() > 0) {
1084          return e.getItems().get(0).asString();
1085        }
1086      }
1087      if (dep != null) {
1088        // legacy simplifier support:
1089        if (dep.has("simplifier.core.r4"))
1090          return "4.0";
1091        if (dep.has("simplifier.core.r3"))
1092          return "3.0";
1093        if (dep.has("simplifier.core.r2"))
1094          return "2.0";
1095      }
1096      throw new FHIRException("no core dependency or FHIR Version found in the Package definition");
1097    }
1098  }
1099
1100  public String summary() {
1101    if (path != null)
1102      return path;
1103    else
1104      return "memory";
1105  }
1106
1107  public boolean isType(PackageType template) {
1108    return template.getCode().equals(type()) || template.getOldCode().equals(type()) ;
1109  }
1110
1111  public String type() {
1112    return npm.asString("type");
1113  }
1114
1115  public String description() {
1116    return npm.asString("description");
1117  }
1118
1119  public String getPath() {
1120    return path;
1121  }
1122
1123  public List<String> dependencies() {
1124    List<String> res = new ArrayList<>();
1125    if (npm.has("dependencies")) {
1126      for (JsonProperty e : npm.getJsonObject("dependencies").getProperties()) {
1127        res.add(e.getName()+"#"+e.getValue().asString());
1128      }
1129    }
1130    return res;
1131  }
1132
1133  public String homepage() {
1134    return npm.asString("homepage");
1135  }
1136
1137  public String url() {
1138    return npm.asString("url");
1139  }
1140
1141
1142  public String title() {
1143    return npm.asString("title");
1144  }
1145
1146  public String toolsVersion() {
1147    return npm.asString("tools-version");
1148  }
1149
1150  public String license() {
1151    return npm.asString("license");
1152  }
1153
1154  //  /**
1155  //   * only for use by the package manager itself
1156  //   * 
1157  //   * @param path
1158  //   */
1159  //  public void setPath(String path) {
1160  //    this.path = path;
1161  //  }
1162
1163  public String getWebLocation() {
1164    if (npm.hasPrimitive("url")) {
1165      return PackageHacker.fixPackageUrl(npm.asString("url"));
1166    } else {
1167      return npm.asString("canonical");
1168    }
1169  }
1170
1171  public InputStream loadResource(String type, String id) throws IOException {
1172    NpmPackageFolder f = folders.get("package");
1173    JsonArray files = f.index().getJsonArray("files");
1174    for (JsonElement e : files.getItems()) {
1175      JsonObject i = (JsonObject) e;
1176      if (type.equals(i.asString("resourceType")) && id.equals(i.asString("id"))) {
1177        return load("package", i.asString("filename"));
1178      }
1179    }
1180    return null;
1181  }
1182
1183  public InputStream loadExampleResource(String type, String id) throws IOException {
1184    NpmPackageFolder f = folders.get("example");
1185    if (f == null) {
1186      f = folders.get("package/example");      
1187    }
1188    if (f != null) {
1189      JsonArray files = f.index().getJsonArray("files");
1190      for (JsonElement e : files.getItems()) {
1191        JsonObject i = (JsonObject) e;
1192        if (type.equals(i.asString("resourceType")) && id.equals(i.asString("id"))) {
1193          return load("example", i.asString("filename"));
1194        }
1195      }
1196    }
1197    return null;
1198  }
1199
1200  /** special case when playing around inside the package **/
1201  public Map<String, NpmPackageFolder> getFolders() {
1202    return folders;
1203  }
1204
1205  public void save(File directory) throws IOException {
1206    assert !minimalMemory;
1207    File dir = ManagedFileAccess.file(Utilities.path(directory.getAbsolutePath(), name()));
1208    if (!dir.exists()) {
1209      FileUtilities.createDirectory(dir.getAbsolutePath());
1210    } else {
1211      FileUtilities.clearDirectory(dir.getAbsolutePath());
1212    }
1213    
1214    for (NpmPackageFolder folder : folders.values()) {
1215      String n = folder.folderName;
1216
1217      File pd = ManagedFileAccess.file(Utilities.path(dir.getAbsolutePath(), n));
1218      if (!pd.exists()) {
1219        FileUtilities.createDirectory(pd.getAbsolutePath());
1220      }
1221      NpmPackageIndexBuilder indexer = new NpmPackageIndexBuilder();
1222      indexer.start(Utilities.path(dir.getAbsolutePath(), n, ".index.db"));
1223      for (String s : folder.content.keySet()) {
1224        byte[] b = folder.content.get(s);
1225        indexer.seeFile(s, b);
1226        if (!s.equals(".index.json") && !s.equals("package.json")) {
1227          FileUtilities.bytesToFile(b, Utilities.path(dir.getAbsolutePath(), n, s));
1228        }
1229      }
1230      byte[] cnt = indexer.build().getBytes(StandardCharsets.UTF_8);
1231      FileUtilities.bytesToFile(cnt, Utilities.path(dir.getAbsolutePath(), n, ".index.json"));
1232    }
1233    byte[] cnt = FileUtilities.stringToBytes(JsonParser.compose(npm, true));
1234    FileUtilities.bytesToFile(cnt, Utilities.path(dir.getAbsolutePath(), "package", "package.json"));
1235  }
1236  
1237  public void save(OutputStream stream) throws IOException {
1238    assert !minimalMemory;
1239    TarArchiveOutputStream tar;
1240//    ByteArrayOutputStream OutputStream;
1241//    BufferedOutputStream bufferedOutputStream;
1242    GzipCompressorOutputStream gzipOutputStream;
1243
1244//    OutputStream = new ByteArrayOutputStream();
1245//    bufferedOutputStream = new BufferedOutputStream(OutputStream);
1246    GzipParameters gp = new GzipParameters();
1247    gp.setCompressionLevel(Deflater.BEST_COMPRESSION);
1248    gzipOutputStream = new GzipCompressorOutputStream(stream, gp);
1249    tar = new TarArchiveOutputStream(gzipOutputStream);
1250
1251
1252    for (NpmPackageFolder folder : folders.values()) {
1253      String n = folder.folderName;
1254      if (!"package".equals(n) && !(n.startsWith("package/") || n.startsWith("package\\"))) {
1255        n = "package/"+n;
1256      }
1257      NpmPackageIndexBuilder indexer = new NpmPackageIndexBuilder();
1258      String filename = Utilities.path("[tmp]", "tmp-"+UUID.randomUUID().toString()+".db");
1259      indexer.start(filename);
1260      for (String s : folder.content.keySet()) {
1261        byte[] b = folder.content.get(s);
1262        String name = n+"/"+s;
1263        if (b == null) {
1264          System.out.println(name+" is null");
1265        } else {
1266          indexer.seeFile(s, b);
1267          if (!s.equals(".index.json") && !s.equals(".index.db") && !s.equals("package.json")) {
1268            TarArchiveEntry entry = new TarArchiveEntry(name);
1269            entry.setSize(b.length);
1270            tar.putArchiveEntry(entry);
1271            tar.write(b);
1272            tar.closeArchiveEntry();
1273          }
1274        }
1275      }
1276      byte[] cnt = indexer.build().getBytes(StandardCharsets.UTF_8);
1277      TarArchiveEntry entry = new TarArchiveEntry(n+"/.index.json");
1278      entry.setSize(cnt.length);
1279      tar.putArchiveEntry(entry);
1280      tar.write(cnt);
1281      tar.closeArchiveEntry();
1282      var file = ManagedFileAccess.file(filename);
1283      if (file.exists()) {
1284        cnt = FileUtilities.fileToBytes(file);
1285        file.delete();
1286        entry = new TarArchiveEntry(n+"/.index.db");
1287        entry.setSize(cnt.length);
1288        tar.putArchiveEntry(entry);
1289        tar.write(cnt);
1290        tar.closeArchiveEntry();
1291      }
1292    }
1293    byte[] cnt = FileUtilities.stringToBytes(JsonParser.compose(npm, true));
1294    TarArchiveEntry entry = new TarArchiveEntry("package/package.json");
1295    entry.setSize(cnt.length);
1296    tar.putArchiveEntry(entry);
1297    tar.write(cnt);
1298    tar.closeArchiveEntry();
1299
1300    tar.finish();
1301    tar.close();
1302    gzipOutputStream.close();
1303//    bufferedOutputStream.close();
1304//    OutputStream.close();
1305//    byte[] b = OutputStream.toByteArray();
1306//    stream.write(b);
1307  }
1308
1309  /**
1310   * Keys are resource type names, values are filenames
1311   */
1312  public Map<String, List<String>> getTypes() {
1313    return folders.get("package").types;
1314  }
1315
1316  public String fhirVersionList() {
1317    if (npm.has("fhirVersions")) {
1318      CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
1319      if (npm.hasArray("fhirVersions")) {
1320        for (String n : npm.getJsonArray("fhirVersions").asStrings()) {
1321          b.append(n);
1322        }
1323      }
1324      if (npm.hasPrimitive("fhirVersions")) {
1325        b.append(npm.asString("fhirVersions"));
1326      }
1327      return b.toString();
1328    } else
1329      return "";
1330  }
1331
1332  public String dependencySummary() {
1333    if (npm.has("dependencies")) {
1334      CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
1335      for (JsonProperty e : npm.getJsonObject("dependencies").getProperties()) {
1336        b.append(e.getName()+"#"+e.getValue().asString());
1337      }
1338      return b.toString();
1339    } else
1340      return "";
1341  }
1342
1343  public void unPack(String dir) throws IOException {
1344    unPack (dir, false, new ArrayList<>());
1345  }
1346
1347  public void unPackWithAppend(String dir, List<String> files) throws IOException {
1348    unPack (dir, true, files);
1349  }
1350
1351  public void unPack(String dir, boolean withAppend) throws IOException {
1352    unPack (dir, withAppend, new ArrayList<>());
1353  }
1354  
1355  public void unPack(String dir, boolean withAppend, List<String> files) throws IOException {
1356    assert !minimalMemory;
1357    
1358    for (NpmPackageFolder folder : folders.values()) {
1359      String dn = folder.getFolderName();
1360      if (!dn.equals("package") && (dn.startsWith("package/") || dn.startsWith("package\\"))) {
1361        dn = dn.substring(8);
1362      }
1363      if (dn.equals("$root")) {
1364        dn = dir;
1365      } else {
1366         dn = Utilities.path(dir, dn);
1367      }
1368      FileUtilities.createDirectory(dn);
1369      for (String s : folder.listFiles()) {
1370        String fn = Utilities.path(dn, s);
1371        File f = ManagedFileAccess.file(fn);
1372        if (withAppend && f.getName().startsWith("_append.")) {
1373          String appendFn = Utilities.path(dn, s.substring(8));
1374          f = ManagedFileAccess.file(appendFn);
1375          files.add(f.getAbsolutePath());
1376          if (f.exists())
1377            FileUtilities.appendBytesToFile(folder.fetchFile(s), appendFn);        
1378          else
1379            FileUtilities.bytesToFile(folder.fetchFile(s), appendFn);        
1380        } else
1381          files.add(f.getAbsolutePath());
1382          FileUtilities.bytesToFile(folder.fetchFile(s), fn);
1383      }      
1384    }
1385  }
1386
1387  public void debugDump(String purpose) {
1388//    System.out.println("Debug Dump of Package for '"+purpose+"'. Path = "+path);
1389//    System.out.println("  npm = "+name()+"#"+version()+", canonical = "+canonical());
1390//    System.out.println("  folders = "+folders.size());
1391//    for (String s : sorted(folders.keySet())) {
1392//      NpmPackageFolder folder = folders.get(s);
1393//      System.out.println("    "+folder.dump());
1394//    }
1395  }
1396
1397  private List<String> sorted(Set<String> keys) {
1398    List<String> res = new ArrayList<String>();
1399    res.addAll(keys);
1400    Collections.sort(res);
1401    return res ;
1402  }
1403
1404  public void clearFolder(String folderName) {
1405    NpmPackageFolder folder = folders.get(folderName);
1406    folder.content.clear();
1407    folder.types.clear();    
1408  }
1409
1410  public void deleteFolder(String folderName) {
1411    folders.remove(folderName);
1412  }
1413
1414  public void addFile(String folderName, String name, byte[] cnt, String type) {
1415    assert !minimalMemory;
1416    
1417    if (!folders.containsKey(folderName)) {
1418      folders.put(folderName, new NpmPackageFolder(folderName));
1419    }
1420    NpmPackageFolder folder = folders.get(folderName);
1421    folder.content.put(name, cnt);
1422    if (!folder.types.containsKey(type))
1423      folder.types.put(type, new ArrayList<>());
1424    folder.types.get(type).add(name);
1425    if ("package".equals(folderName) && "package.json".equals(name)) {
1426      try {
1427        npm = JsonParser.parseObject(cnt);
1428      } catch (IOException e) {
1429      }
1430    }
1431  }
1432
1433  public void loadAllFiles() throws IOException {
1434    for (String folder : folders.keySet()) {
1435      NpmPackageFolder pf = folders.get(folder);
1436      String p = folder.contains("$") ? path : Utilities.path(path, folder);
1437      File file = ManagedFileAccess.file(p);
1438      if (file.exists()) {
1439        for (File f : file.listFiles()) {
1440          if (!f.isDirectory() && !isInternalExemptFile(f)) {
1441            pf.getContent().put(f.getName(), FileUtilities.fileToBytes(f));
1442          }
1443        }
1444      }
1445    }
1446  }
1447
1448  public void loadAllFiles(ITransformingLoader loader) throws IOException {
1449    for (String folder : folders.keySet()) {
1450      NpmPackageFolder pf = folders.get(folder);
1451      String p = folder.contains("$") ? path : Utilities.path(path, folder);
1452      for (File f : ManagedFileAccess.file(p).listFiles()) {
1453        if (!f.isDirectory() && !isInternalExemptFile(f)) {
1454          pf.getContent().put(f.getName(), loader.load(f));
1455        }
1456      }
1457    }
1458  }
1459
1460  public boolean isChangedByLoader() {
1461    return changedByLoader;
1462  }
1463
1464  public boolean isCore() {
1465    return Utilities.existsInList(npm.asString("type"), "fhir.core", "Core");
1466  }
1467
1468  public boolean isCoreExamples() {
1469    return name().startsWith("hl7.fhir.r") && name().endsWith(".examples");
1470  }
1471  
1472  
1473  public boolean isTx() {
1474    return npm.asString("name").startsWith("hl7.terminology");
1475  }
1476
1477  public boolean hasCanonical(String url) throws IOException {
1478    if (url == null) {
1479      return false;
1480    }
1481    String u = url.contains("|") ?  url.substring(0, url.indexOf("|")) : url;
1482    String v = url.contains("|") ?  url.substring(url.indexOf("|")+1) : null;
1483    NpmPackageFolder folder = folders.get("package");
1484    if (folder != null) {
1485      for (JsonObject o : folder.index().getJsonObjects("files")) {
1486        if (u.equals(o.asString("url"))) {
1487          if (v == null || v.equals(o.asString("version"))) {
1488            return true;
1489          }
1490        }
1491      }
1492    }
1493    return false;
1494  }
1495
1496  public boolean canLazyLoad() throws IOException {
1497    for (NpmPackageFolder folder : folders.values()) {
1498      if (folder.folder == null) {        
1499        return false;
1500      }
1501    }
1502    if (Utilities.existsInList(name(), "fhir.test.data.r2", "fhir.test.data.r3", "fhir.test.data.r4", "fhir.tx.support.r2", "fhir.tx.support.r3", "fhir.tx.support.r4", "us.nlm.vsac")) {
1503      return true;
1504    }
1505    if (npm.asBoolean("lazy-load")) {
1506      return true;
1507    }
1508    if (!hasFile("other", "spec.internals") && folders.get("package").cachedIndex == null) {
1509      return false;
1510    }
1511    return true;
1512  }
1513
1514  public boolean isNotForPublication() {
1515    return npm.asBoolean("notForPublication");
1516 }
1517
1518  public InputStream load(PackageResourceInformation p) throws IOException {
1519    if (p.filename.startsWith("@")) {
1520      String[] pl = p.filename.substring(1).split("\\/");
1521      return new ByteArrayInputStream(folders.get(pl[0]).content.get(pl[1]));
1522    } else {
1523      return ManagedFileAccess.inStream(p.filename);
1524    }
1525  }
1526
1527  public Date dateAsDate() {
1528    try {
1529      String d = date();
1530      if (d == null) {
1531        switch (name()) {
1532        case "hl7.fhir.r2.core":  d = "20151024000000"; break;
1533        case "hl7.fhir.r2b.core": d = "20160330000000"; break;
1534        case "hl7.fhir.r3.core":  d = "20191024000000"; break;
1535        case "hl7.fhir.r4.core":  d = "20191030000000"; break;
1536        case "hl7.fhir.r4b.core": d = "202112200000000"; break;
1537        case "hl7.fhir.r5.core":  d = "20211219000000"; break;
1538        default:
1539          return new Date();
1540        }
1541      }
1542      return new SimpleDateFormat("yyyyMMddHHmmss").parse(d);
1543    } catch (ParseException e) {
1544      // this really really shouldn't happen
1545      return new Date();
1546    }
1547  }
1548
1549  public static NpmPackage fromUrl(String source) throws IOException {
1550    HTTPResult res = ManagedWebAccess.get(Arrays.asList("npm-package", "fhir-package"), source+"?nocache=" + System.currentTimeMillis());
1551    res.checkThrowException();
1552    return fromPackage(new ByteArrayInputStream(res.getContent()));
1553  }
1554
1555  @Override
1556  public String toString() {
1557    return "NpmPackage "+name()+"#"+version()+" [path=" + path + "]";
1558  }
1559
1560  public String getFilePath(String d) throws IOException {
1561    return Utilities.path(path, "package", d);
1562  }
1563
1564  public boolean isMinimalMemory() {
1565    return minimalMemory;
1566  }
1567
1568  public int getSize() {
1569    return size;
1570  }
1571
1572  public void setSize(int size) {
1573    this.size = size;
1574  }
1575
1576  public boolean isWarned() {
1577    return warned;
1578  }
1579
1580  public void setWarned(boolean warned) {
1581    this.warned = warned;
1582  }
1583
1584  public String vid() {
1585    return id()+"#"+version();
1586  }
1587
1588  public static boolean isLoadCustomResources() {
1589    return loadCustomResources;
1590  }
1591
1592  public static void setLoadCustomResources(boolean loadCustomResources) {
1593    NpmPackage.loadCustomResources = loadCustomResources;
1594  }
1595
1596  public LocalDate dateAsLocalDate() {
1597    String date = date();
1598    String d = date.substring(0, 4)+"-"+date.substring(4, 6)+"-"+date.substring(6, 8);
1599    return LocalDate.parse(d);
1600  }
1601
1602}