001package org.hl7.fhir.r5.utils;
002
003/*-
004 * #%L
005 * org.hl7.fhir.r5
006 * %%
007 * Copyright (C) 2014 - 2019 Health Level 7
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 * 
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 * 
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023
024import java.io.BufferedOutputStream;
025import java.io.ByteArrayOutputStream;
026import java.io.File;
027import java.io.IOException;
028import java.io.UnsupportedEncodingException;
029import java.nio.charset.Charset;
030import java.text.SimpleDateFormat;
031import java.util.ArrayList;
032import java.util.Calendar;
033import java.util.Date;
034import java.util.GregorianCalendar;
035import java.util.HashMap;
036import java.util.HashSet;
037import java.util.List;
038import java.util.Locale;
039import java.util.Map;
040import java.util.Set;
041import java.util.TimeZone;
042
043import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
044import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
045import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
046import org.hl7.fhir.exceptions.FHIRException;
047import org.hl7.fhir.r5.model.ContactDetail;
048import org.hl7.fhir.r5.model.ContactPoint;
049import org.hl7.fhir.r5.model.ContactPoint.ContactPointSystem;
050import org.hl7.fhir.r5.model.Enumeration;
051import org.hl7.fhir.r5.model.Enumerations.FHIRVersion;
052import org.hl7.fhir.r5.model.ImplementationGuide;
053import org.hl7.fhir.r5.model.ImplementationGuide.ImplementationGuideDependsOnComponent;
054import org.hl7.fhir.utilities.CommaSeparatedStringBuilder;
055import org.hl7.fhir.utilities.TextFile;
056import org.hl7.fhir.utilities.Utilities;
057import org.hl7.fhir.utilities.cache.PackageGenerator.PackageType;
058import org.hl7.fhir.utilities.cache.NpmPackageIndexBuilder;
059import org.hl7.fhir.utilities.cache.ToolsVersion;
060import org.hl7.fhir.utilities.json.JsonTrackingParser;
061
062import com.google.gson.Gson;
063import com.google.gson.GsonBuilder;
064import com.google.gson.JsonArray;
065import com.google.gson.JsonObject;
066import com.google.gson.JsonPrimitive;
067
068public class NPMPackageGenerator {
069
070  public enum Category {
071    RESOURCE, EXAMPLE, OPENAPI, SCHEMATRON, RDF, OTHER, TOOL, TEMPLATE, JEKYLL;
072
073    private String getDirectory() {
074      switch (this) {
075      case RESOURCE: return "/package/";
076      case EXAMPLE: return "/example/";
077      case OPENAPI: return "/openapi/";
078      case SCHEMATRON: return "/xml/";
079      case RDF: return "/rdf/";      
080      case OTHER: return "/other/";      
081      case TEMPLATE: return "/other/";      
082      case JEKYLL: return "/jekyll/";      
083      case TOOL: return "/bin/";      
084      }
085      return "/";
086    }
087  }
088
089  private String destFile;
090  private Set<String> created = new HashSet<String>();
091  private TarArchiveOutputStream tar;
092  private ByteArrayOutputStream OutputStream;
093  private BufferedOutputStream bufferedOutputStream;
094  private GzipCompressorOutputStream gzipOutputStream;
095  private JsonObject packageJ;
096  private JsonObject packageManifest;
097  private NpmPackageIndexBuilder indexer;
098
099
100  public NPMPackageGenerator(String destFile, String canonical, String url, PackageType kind, ImplementationGuide ig, Date date) throws FHIRException, IOException {
101    super();
102    this.destFile = destFile;
103    start();
104    List<String> fhirVersion = new ArrayList<>();
105    for (Enumeration<FHIRVersion> v : ig.getFhirVersion())
106      fhirVersion.add(v.asStringValue());
107    buildPackageJson(canonical, kind, url, date, ig, fhirVersion);
108  }
109
110  public static NPMPackageGenerator subset(NPMPackageGenerator master, String destFile, String id, String name, Date date) throws FHIRException, IOException {
111    JsonObject p = master.packageJ.deepCopy();
112    p.remove("name");
113    p.addProperty("name", id);
114    p.remove("type");
115    p.addProperty("type", PackageType.SUBSET.getCode());    
116    p.remove("title");
117    p.addProperty("title", name);
118
119    return new NPMPackageGenerator(destFile, p, date);
120  }
121
122  public NPMPackageGenerator(String destFile, String canonical, String url, PackageType kind, ImplementationGuide ig, Date date, List<String> fhirVersion) throws FHIRException, IOException {
123    super();
124    this.destFile = destFile;
125    start();
126    buildPackageJson(canonical, kind, url, date, ig, fhirVersion);
127  }
128
129  public NPMPackageGenerator(String destFile, JsonObject npm, Date date) throws FHIRException, IOException {
130    super();
131    String dt = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
132    packageJ = npm;
133    packageManifest = new JsonObject();
134    packageManifest.addProperty("version", npm.get("version").getAsString());
135    packageManifest.addProperty("date", dt);
136    npm.addProperty("date", dt);
137    packageManifest.addProperty("name", npm.get("name").getAsString());
138    this.destFile = destFile;
139    start();
140    Gson gson = new GsonBuilder().setPrettyPrinting().create();
141    String json = gson.toJson(npm);
142    try {
143      addFile(Category.RESOURCE, "package.json", json.getBytes("UTF-8"));
144    } catch (UnsupportedEncodingException e) {
145    }
146  }
147
148  private void buildPackageJson(String canonical, PackageType kind, String web, Date date, ImplementationGuide ig, List<String> fhirVersion) throws FHIRException, IOException {
149    String dtHuman = new SimpleDateFormat("EEE, MMM d, yyyy HH:mmZ", new Locale("en", "US")).format(date);
150    String dt = new SimpleDateFormat("yyyyMMddHHmmss").format(date);
151
152    CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder();
153    if (!ig.hasPackageId())
154      b.append("packageId");
155    if (!ig.hasVersion())
156      b.append("version");
157    if (!ig.hasFhirVersion())
158      b.append("fhirVersion");
159    if (!ig.hasLicense())
160      b.append("license");
161    for (ImplementationGuideDependsOnComponent d : ig.getDependsOn()) {
162      if (!d.hasVersion()) {
163        b.append("dependsOn.version("+d.getUri()+")");
164      }
165    }
166
167    JsonObject npm = new JsonObject();
168    npm.addProperty("name", ig.getPackageId());
169    npm.addProperty("version", ig.getVersion());
170    npm.addProperty("tools-version", ToolsVersion.TOOLS_VERSION);
171    npm.addProperty("type", kind.getCode());
172    npm.addProperty("date", dt);
173    if (ig.hasLicense())
174      npm.addProperty("license", ig.getLicense().toCode());
175    npm.addProperty("canonical", canonical);
176    npm.addProperty("url", web);
177    if (ig.hasTitle())
178      npm.addProperty("title", ig.getTitle());
179    if (ig.hasDescription())
180      npm.addProperty("description", ig.getDescription()+ " (built "+dtHuman+timezone()+")");
181    JsonArray vl = new JsonArray();
182    
183    npm.add("fhirVersions", vl);
184    for (String v : fhirVersion) { 
185      vl.add(new JsonPrimitive(v));
186    }
187    
188    if (kind != PackageType.CORE) {
189      JsonObject dep = new JsonObject();
190      npm.add("dependencies", dep);
191      for (String v : fhirVersion) { 
192        String vp = packageForVersion(v);
193        if (vp != null ) {
194          dep.addProperty(vp, v);
195        }
196      }
197      for (ImplementationGuideDependsOnComponent d : ig.getDependsOn()) {
198        dep.addProperty(d.getPackageId(), d.getVersion());
199      }
200    }
201    if (ig.hasPublisher())
202      npm.addProperty("author", ig.getPublisher());
203    JsonArray m = new JsonArray();
204    for (ContactDetail t : ig.getContact()) {
205      String email = email(t.getTelecom());
206      String url = url(t.getTelecom());
207      if (t.hasName() & (email != null || url != null)) {
208        JsonObject md = new JsonObject();
209        m.add(md);
210        md.addProperty("name", t.getName());
211        if (email != null)
212          md.addProperty("email", email);
213        if (url != null)
214          md.addProperty("url", url);
215      }
216    }
217    if (m.size() > 0)
218      npm.add("maintainers", m);
219    if (ig.getManifest().hasRendering())
220      npm.addProperty("homepage", ig.getManifest().getRendering());
221    JsonObject dir = new JsonObject();
222    npm.add("directories", dir);
223    dir.addProperty("lib", "package");
224    dir.addProperty("example", "example");
225    Gson gson = new GsonBuilder().setPrettyPrinting().create();
226    String json = gson.toJson(npm);
227    try {
228      addFile(Category.RESOURCE, "package.json", json.getBytes("UTF-8"));
229    } catch (UnsupportedEncodingException e) {
230    }
231    packageJ = npm;
232
233    packageManifest = new JsonObject();
234    packageManifest.addProperty("version", ig.getVersion());
235    packageManifest.addProperty("fhirVersion", fhirVersion.toString());
236    packageManifest.addProperty("date", dt);
237    packageManifest.addProperty("name", ig.getPackageId());
238
239  }
240
241
242  private String packageForVersion(String v) {
243    if (v == null)
244      return null;
245    if (v.startsWith("1.0"))
246      return "hl7.fhir.r2.core";
247    if (v.startsWith("1.4"))
248      return "hl7.fhir.r2b.core";
249    if (v.startsWith("3.0"))
250      return "hl7.fhir.r3.core";
251    if (v.startsWith("4.0"))
252      return "hl7.fhir.r4.core";
253    return null;
254  }
255
256  private String timezone() {
257    TimeZone tz = TimeZone.getDefault();  
258    Calendar cal = GregorianCalendar.getInstance(tz);
259    int offsetInMillis = tz.getOffset(cal.getTimeInMillis());
260
261    String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
262    offset = (offsetInMillis >= 0 ? "+" : "-") + offset;
263
264    return offset;
265  }
266
267
268  private String url(List<ContactPoint> telecom) {
269    for (ContactPoint cp : telecom) {
270      if (cp.getSystem() == ContactPointSystem.URL)
271        return cp.getValue();
272    }
273    return null;
274  }
275
276
277  private String email(List<ContactPoint> telecom) {
278    for (ContactPoint cp : telecom) {
279      if (cp.getSystem() == ContactPointSystem.EMAIL)
280        return cp.getValue();
281    }
282    return null;
283  }
284
285  private void start() throws IOException {
286    OutputStream = new ByteArrayOutputStream();
287    bufferedOutputStream = new BufferedOutputStream(OutputStream);
288    gzipOutputStream = new GzipCompressorOutputStream(bufferedOutputStream);
289    tar = new TarArchiveOutputStream(gzipOutputStream);
290    indexer = new NpmPackageIndexBuilder();
291    indexer.start();
292  }
293
294
295  public void addFile(Category cat, String name, byte[] content) throws IOException {
296    String path = cat.getDirectory()+name;
297    if (created.contains(path)) 
298      System.out.println("Duplicate package file "+path);
299    else {
300      created.add(path);
301      TarArchiveEntry entry = new TarArchiveEntry(path);
302      entry.setSize(content.length);
303      tar.putArchiveEntry(entry);
304      tar.write(content);
305      tar.closeArchiveEntry();
306      if(cat == Category.RESOURCE) {
307        indexer.seeFile(name, content);
308      }
309    }
310  }
311
312  public void finish() throws IOException {
313    buildIndexJson();
314    tar.finish();
315    tar.close();
316    gzipOutputStream.close();
317    bufferedOutputStream.close();
318    OutputStream.close();
319    TextFile.bytesToFile(OutputStream.toByteArray(), destFile);
320    // also, for cache management on current builds, generate a little manifest
321    Gson gson = new GsonBuilder().setPrettyPrinting().create();
322    String json = gson.toJson(packageManifest);
323    TextFile.stringToFile(json, Utilities.changeFileExt(destFile, ".manifest.json"), false);
324  }
325
326  private void buildIndexJson() throws IOException {
327    byte[] content = indexer.build().getBytes(Charset.forName("UTF-8"));
328    addFile(Category.RESOURCE, ".index.json", content); 
329  }
330
331  public String filename() {
332    return destFile;
333  }
334
335  public void loadDir(String rootDir, String name) throws IOException {
336    loadFiles(rootDir, new File(Utilities.path(rootDir, name)));
337  }
338
339  public void loadFiles(String root, File dir, String... noload) throws IOException {
340    for (File f : dir.listFiles()) {
341      if (!Utilities.existsInList(f.getName(), noload)) {
342        if (f.isDirectory()) {
343          loadFiles(root, f);
344        } else {
345          String path = f.getAbsolutePath().substring(root.length()+1);
346          byte[] content = TextFile.fileToBytes(f);
347          if (created.contains(path)) 
348            System.out.println("Duplicate package file "+path);
349          else {
350            created.add(path);
351            TarArchiveEntry entry = new TarArchiveEntry(path);
352            entry.setSize(content.length);
353            tar.putArchiveEntry(entry);
354            tar.write(content);
355            tar.closeArchiveEntry();
356          }
357        }
358      }
359    }
360  }
361
362
363}