001package org.hl7.fhir.utilities.npm;
002
003import java.io.File;
004import java.io.IOException;
005import java.sql.Connection;
006import java.sql.DriverManager;
007import java.sql.PreparedStatement;
008import java.sql.SQLException;
009import java.sql.Statement;
010
011import com.fasterxml.jackson.core.JsonFactory;
012import com.fasterxml.jackson.core.JsonToken;
013import org.hl7.fhir.exceptions.FHIRException;
014import org.hl7.fhir.utilities.FileUtilities;
015import org.hl7.fhir.utilities.Utilities;
016import org.hl7.fhir.utilities.filesystem.ManagedFileAccess;
017import org.hl7.fhir.utilities.json.model.JsonArray;
018import org.hl7.fhir.utilities.json.model.JsonObject;
019import org.hl7.fhir.utilities.json.parser.JsonParser;
020
021/**
022 * This class builds the .index.json for a package 
023 * 
024 * it also builds a .index.db since that may provide faster access
025 * 
026 * @author grahame
027 *
028 */
029public class NpmPackageIndexBuilder {
030  
031  public static final Integer CURRENT_INDEX_VERSION = 2;
032  private JsonObject index;
033  private JsonArray files;
034  private Connection conn;
035  private PreparedStatement psql;
036  private String dbFilename;
037  
038  public void start(String filename) {
039    index = new JsonObject();
040    index.add("index-version", CURRENT_INDEX_VERSION);
041    files = new JsonArray();
042    index.add("files", files);
043
044    dbFilename = filename;
045    if (filename != null) {
046      try {
047        ManagedFileAccess.file(filename).delete();
048        conn = DriverManager.getConnection("jdbc:sqlite:"+filename); 
049        Statement stmt = conn.createStatement();
050        stmt.execute("CREATE TABLE ResourceList (\r\n"+
051            "FileName       nvarchar NOT NULL,\r\n"+
052            "ResourceType   nvarchar NOT NULL,\r\n"+
053            "Id             nvarchar NULL,\r\n"+
054            "Url            nvarchar NULL,\r\n"+
055            "Version        nvarchar NULL,\r\n"+
056            "Kind           nvarchar NULL,\r\n"+
057            "Type           nvarchar NULL,\r\n"+
058            "Supplements    nvarchar NULL,\r\n"+
059            "Content        nvarchar NULL,\r\n"+
060            "ValueSet       nvarchar NULL,\r\n"+
061            "Derivation     nvarchar NULL,\r\n"+
062            "PRIMARY KEY (FileName))\r\n");
063
064        psql = conn.prepareStatement("Insert into ResourceList (FileName, ResourceType, Id, Url, Version, Kind, Type, Supplements, Content, ValueSet) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
065      } catch (Exception e) {
066        if (conn != null) { 
067          try {
068            conn.close();
069          } catch (SQLException e1) {
070          }
071        }
072        conn = null;
073      }
074    }
075  }
076
077  public boolean seeFile(String name, byte[] content) {
078    if (name.endsWith(".json")) {
079      /* We are only interested in some string fields on the first level of the JSON file.
080       * We can then use a streaming parser to get the values of these fields instead of parsing the whole file and
081       * allocating memory for everything in it.
082       */
083      try (final var parser = new JsonFactory().createParser(content)) {
084        final var fi = new JsonObject();
085        int level = 0;
086
087        while (parser.nextToken() != null) {
088          if (parser.currentToken() == JsonToken.START_OBJECT || parser.currentToken() == JsonToken.START_ARRAY) {
089            level++;
090          } else if (parser.currentToken() == JsonToken.END_OBJECT || parser.currentToken() == JsonToken.END_ARRAY) {
091            level--;
092          }
093          if (level != 1) {
094            continue;
095          }
096
097          String fieldName = parser.currentName();
098
099          if ("resourceType".equals(fieldName)) {
100            parser.nextToken();
101            files.add(fi);
102            fi.add("filename", name);
103            fi.add(fieldName, parser.getText());
104          }
105
106          if ("id".equals(fieldName)
107              || "url".equals(fieldName)
108              || "version".equals(fieldName)
109              || "kind".equals(fieldName)
110              || "type".equals(fieldName)
111              || "supplements".equals(fieldName)
112              || "content".equals(fieldName)
113              || "valueSet".equals(fieldName)
114              || "derivation".equals(fieldName)) {
115            parser.nextToken();
116            fi.add(fieldName, parser.getText());
117          }
118        }
119
120        if (!fi.has("resourceType")) {
121          // We haven't seen the 'resourceType' key, it's not a FHIR resource
122          return true;
123        }
124
125        if (psql != null) {
126          psql.setString(1, name); // FileName);
127          psql.setString(2, fi.asString("resourceType")); // ResourceType");
128          psql.setString(3, fi.asString("id")); // Id");
129          psql.setString(4, fi.asString("url")); // Url");
130          psql.setString(5, fi.asString("version")); // Version");
131          psql.setString(6, fi.asString("kind")); // Kind");
132          psql.setString(7, fi.asString("type")); // Type");
133          psql.setString(8, fi.asString("supplements")); // Supplements");
134          psql.setString(9, fi.asString("content")); // Content");
135          psql.setString(10, fi.asString("valueSet")); // ValueSet");
136          psql.setString(10, fi.asString("derivation")); // Derivation");
137          psql.execute();
138        }
139      } catch (Exception e) {
140//        System.out.println("Error parsing "+name+": "+e.getMessage());
141        if (name.contains("openapi")) {
142          return false;
143        }
144      }
145    }
146    return true;
147  }
148
149  public String build() {
150    try {
151      if (conn != null) {
152        conn.close();
153      }
154    } catch (Exception e) {
155      // nothing
156    }
157    String res = JsonParser.compose(index, true);
158    index = null;
159    files = null;
160    return res;
161  }
162  
163//  private Map<String, List<String>> types = new HashMap<>();
164//  private Map<String, String> canonicalMap = new HashMap<>();
165
166
167  public void executeWithStatus(String folder) throws IOException {
168    System.out.print("Index Package "+folder+" ... ");
169    execute(folder);
170    System.out.println("done");
171  }
172  
173  public void execute(String folder) throws IOException {
174    if (existsFolder(folder, "package")) {
175      folder = Utilities.path(folder, "package"); 
176    }
177    if (!existsFile(folder, "package.json")) {
178      throw new FHIRException("Not a proper package? (can't find package.json)");
179    }
180    start(Utilities.path(folder, ".index.db"));
181    File dir = ManagedFileAccess.file(folder);
182    for (File f : dir.listFiles()) {
183      seeFile(f.getName(), FileUtilities.fileToBytes(f));
184    }
185    FileUtilities.stringToFile(build(), Utilities.path(folder, ".index.json"));
186  }
187
188  private boolean existsFolder(String... args) throws IOException {
189    File f = ManagedFileAccess.file(Utilities.path(args));
190    return f.exists() && f.isDirectory();
191  }
192
193  private boolean existsFile(String... args) throws IOException {
194    File f = ManagedFileAccess.file(Utilities.path(args));
195    return f.exists() && !f.isDirectory();
196  }
197
198  public static void main(String[] args) throws IOException {
199    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.r4.core");
200    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.r4.examples");
201    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.r4.expansions");
202    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.r4.elements");
203    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.r3.core");
204    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.r3.examples");
205    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.r3.expansions");
206    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.r3.elements");
207    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.r2b.core");
208    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.r2b.examples");
209    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.r2b.expansions");
210    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.r2.core");
211    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.r2.examples");
212    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.r2.expansions");
213    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.r2.elements");
214    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\fhir.test.data\\fhir.test.data.r2");
215    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\fhir.test.data\\fhir.test.data.r3");
216    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\fhir.test.data\\fhir.test.data.r4");
217    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\fhir.tx.support\\fhir.tx.support.r2");
218    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\fhir.tx.support\\fhir.tx.support.r3");
219    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\fhir.tx.support\\fhir.tx.support.r4");
220    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.core#1.0.2");
221    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.core#1.4.0");
222    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.core#3.0.2");
223    new NpmPackageIndexBuilder().executeWithStatus("C:\\work\\org.hl7.fhir\\packages\\hl7.fhir.rX\\hl7.fhir.core#4.0.1");
224  }
225
226  public String getDbFilename() {
227    return dbFilename;
228  }
229
230
231}