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