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