001package org.hl7.fhir.utilities.npm;
002
003import java.io.File;
004import java.io.FileOutputStream;
005import java.io.IOException;
006
007import org.hl7.fhir.utilities.Utilities;
008import org.hl7.fhir.utilities.filesystem.ManagedFileAccess;
009import org.hl7.fhir.utilities.json.model.JsonObject;
010import org.hl7.fhir.utilities.json.parser.JsonParser;
011
012
013public class ResourceRenamer {
014
015  public static void main(String[] args) throws IOException {
016    new ResourceRenamer().processArg(ManagedFileAccess.file(args[0]));
017  }
018
019  private void processArg(File file) throws IOException {
020   if (file.isDirectory()) {
021     process(file);
022   } else {
023     unbundle(file);
024   }
025  }
026
027  private void unbundle(File f) throws IOException {
028    JsonObject j = JsonParser.parseObject(f);
029    for (JsonObject e : j.getJsonObjects("entry")) {
030      JsonObject r = e.getJsonObject("resource");
031      String rt = r.asString("resourceType");
032      String id = r.asString("id");
033      String nn = Utilities.path(Utilities.getDirectoryForFile(f.getAbsolutePath()), rt+"-"+id+".json");
034      FileOutputStream fs = ManagedFileAccess.outStream(nn);
035      try {
036        JsonParser.compose(r, fs, true);
037      } finally {
038        fs.close();
039      }
040    } 
041  }
042
043  private void process(File dir) {
044    
045    for (File f : dir.listFiles()) {
046      if (f.getName().endsWith(".json")) {
047        try {
048          JsonObject j = JsonParser.parseObject(f);
049          String rt = j.asString("resourceType");
050          String id = j.asString("id");
051          String nn = Utilities.path(Utilities.getDirectoryForFile(f.getAbsolutePath()), rt+"-"+id+".json");
052          File nf = ManagedFileAccess.file(nn);
053          if (!nn.equals(f.getAbsolutePath())) {
054            System.out.println("Rename "+f.getName()+" to "+nf.getName());
055            f.renameTo(nf);
056          }
057        } catch (Exception e) {
058          System.out.println("Error Processing "+f.getName()+" : "+e.getMessage());
059        }
060      }
061    }
062    
063  }
064
065}