001package org.hl7.fhir.dstu3.utils;
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.File;
035import java.io.FileInputStream;
036import java.io.FileNotFoundException;
037import java.io.IOException;
038import java.text.SimpleDateFormat;
039import java.util.Date;
040import java.util.UUID;
041
042import org.hl7.fhir.dstu3.formats.IParser;
043import org.hl7.fhir.dstu3.formats.JsonParser;
044import org.hl7.fhir.dstu3.formats.XmlParser;
045import org.hl7.fhir.dstu3.model.Bundle;
046import org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent;
047import org.hl7.fhir.dstu3.model.Bundle.BundleType;
048import org.hl7.fhir.dstu3.model.Bundle.HTTPVerb;
049import org.hl7.fhir.dstu3.model.Resource;
050import org.hl7.fhir.dstu3.utils.client.FHIRToolingClient;
051import org.hl7.fhir.exceptions.FHIRException;
052import org.hl7.fhir.exceptions.FHIRFormatError;
053import org.hl7.fhir.utilities.IniFile;
054import org.hl7.fhir.utilities.Utilities;
055
056public class BatchLoader {
057
058  public static void main(String[] args) throws IOException, Exception {
059    if (args.length < 3) {
060      System.out.println("Batch uploader takes 3 parameters in order: server base url, file/folder to upload, and batch size");
061    } else {
062      String server = args[0];
063      String file = args[1];
064      int size = Integer.parseInt(args[2]);
065      if (file.endsWith(".xml")) {
066        throw new FHIRException("Unimplemented file type "+file);
067      } else if (file.endsWith(".json")) {
068        throw new FHIRException("Unimplemented file type "+file);
069//      } else if (file.endsWith(".zip")) {
070//        LoadZipFile(server, file, p, size, 0, -1);
071      } else if (new File(file).isDirectory()) {
072        LoadDirectory(server, file, size);
073      } else 
074        throw new FHIRException("Unknown file type "+file);
075    }
076  }
077
078  private static void LoadDirectory(String server, String folder, int size) throws IOException, Exception {
079    System.out.print("Connecting to "+server+".. ");
080    FHIRToolingClient client = new FHIRToolingClient(server, "fhir/batch-loader");
081    System.out.println("Done");
082    
083    IniFile ini = new IniFile(Utilities.path(folder, "batch-load-progress.ini"));
084    for (File f : new File(folder).listFiles()) {
085      if (f.getName().endsWith(".json") || f.getName().endsWith(".xml")) {
086        if (!ini.getBooleanProperty("finished", f.getName())) {
087          sendFile(client, f, size, ini);
088        }
089      }
090    }
091  }
092
093  
094  private static void sendFile(FHIRToolingClient client, File f, int size, IniFile ini) throws FHIRFormatError, FileNotFoundException, IOException {
095    long ms = System.currentTimeMillis();
096    System.out.print("Loading "+f.getName()+".. ");
097    IParser parser = f.getName().endsWith(".json") ? new JsonParser() : new XmlParser();
098    Resource res = parser.parse(new FileInputStream(f));
099    System.out.println("  done: ("+Long.toString(System.currentTimeMillis()-ms)+" ms)");
100    
101    if (res instanceof Bundle) {
102      Bundle bnd = (Bundle) res;
103      int cursor = ini.hasProperty("progress", f.getName()) ? ini.getIntegerProperty("progress", f.getName()) : 0;
104      while (cursor < bnd.getEntry().size()) {
105        Bundle bt = new Bundle();
106        bt.setType(BundleType.BATCH);     
107        bt.setId(UUID.randomUUID().toString().toLowerCase());
108        for (int i = cursor; i < Math.min(bnd.getEntry().size(), cursor+size); i++) {
109          if (i >=0 && i < bnd.getEntry().size()) {
110            BundleEntryComponent be = bt.addEntry();
111            be.setResource(bnd.getEntry().get(i).getResource());
112            be.getRequest().setMethod(HTTPVerb.PUT);
113            be.getRequest().setUrl(be.getResource().getResourceType().toString()+"/"+be.getResource().getId());
114          }
115        }
116        System.out.print(f.getName()+" ("+cursor+"/"+bnd.getEntry().size()+"): ");
117        ms = System.currentTimeMillis();
118        Bundle resp = client.transaction(bt);
119
120        int ncursor = cursor+size;
121        for (int i = 0; i < resp.getEntry().size(); i++) {
122          BundleEntryComponent t = resp.getEntry().get(i);
123          if (!t.getResponse().getStatus().startsWith("2")) { 
124            System.out.println("failed status at "+Integer.toString(i)+": "+t.getResponse().getStatus());
125            ncursor = cursor+i-1;
126            break;
127          }
128        }
129        cursor = ncursor;
130        System.out.println("  .. done: ("+Long.toString(System.currentTimeMillis()-ms)+" ms) "+SimpleDateFormat.getInstance().format(new Date()));
131        ini.setIntegerProperty("progress", f.getName(), cursor, null);
132        ini.save();
133      }
134      ini.setBooleanProperty("finished", f.getName(), true, null);
135      ini.save();
136    } else {
137      client.update(res);
138      ini.setBooleanProperty("finished", f.getName(), true, null);
139      ini.save();
140    }    
141  }
142//
143//  private static void LoadZipFile(String server, String file, IParser p, int size, int start, int end) throws IOException, Exception {
144//    System.out.println("Load Zip file "+file);
145//    Bundle b = new Bundle();
146//    b.setType(BundleType.COLLECTION);
147//    b.setId(UUID.randomUUID().toString().toLowerCase());
148//    ZipInputStream zip = new ZipInputStream(new FileInputStream(file));
149//    ZipEntry entry;
150//    while((entry = zip.getNextEntry())!=null)
151//    {
152//      try {
153//        Resource r = p.parse(zip);
154//        b.addEntry().setResource(r);
155//      } catch (Exception e) {
156//        throw new Exception("Error parsing "+entry.getName()+": "+e.getMessage(), e);
157//      }
158//    }
159//    loadBundle(server, b, size, start, end);
160//  }
161//
162//  
163//  private static int loadBundle(String server, Bundle b, int size, int start, int end) throws URISyntaxException {
164//    System.out.println("Post to "+server+". size = "+Integer.toString(size)+", start = "+Integer.toString(start)+", total = "+Integer.toString(b.getEntry().size()));
165//    FHIRToolingClient client = new FHIRToolingClient(server);
166//    int c = start;
167//    if (end == -1)
168//      end = b.getEntry().size();
169//    while (c < end) {
170//      Bundle bt = new Bundle();
171//      bt.setType(BundleType.BATCH);     
172//      bt.setId(UUID.randomUUID().toString().toLowerCase());
173//      for (int i = c; i < Math.min(b.getEntry().size(), c+size); i++) {
174//        BundleEntryComponent be = bt.addEntry();
175//        be.setResource(b.getEntry().get(i).getResource());
176//        be.getRequest().setMethod(HTTPVerb.PUT);
177//        be.getRequest().setUrl(be.getResource().getResourceType().toString()+"/"+be.getResource().getId());
178//      }
179//      System.out.print("  posting..");
180//      long ms = System.currentTimeMillis();
181//      Bundle resp = client.transaction(bt);
182//      
183//      for (int i = 0; i < resp.getEntry().size(); i++) {
184//        BundleEntryComponent t = resp.getEntry().get(i);
185//        if (!t.getResponse().getStatus().startsWith("2")) { 
186//          System.out.println("failed status at "+Integer.toString(i)+": "+t.getResponse().getStatus());
187//          return c+i;
188//        }
189//      }
190//      c = c + size;
191//      System.out.println("  ..done: "+Integer.toString(c)+". ("+Long.toString(System.currentTimeMillis()-ms)+" ms)");
192//    }
193//    System.out.println(" done");
194//    return c;
195//  }
196
197}