001package org.hl7.fhir.utilities;
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.BufferedInputStream;
035import java.io.BufferedOutputStream;
036import java.io.ByteArrayInputStream;
037import java.io.File;
038import java.io.FileInputStream;
039import java.io.FileNotFoundException;
040import java.io.FileOutputStream;
041import java.io.IOException;
042import java.io.InputStream;
043import java.util.HashSet;
044import java.util.Set;
045import java.util.zip.CRC32;
046import java.util.zip.Deflater;
047import java.util.zip.ZipEntry;
048import java.util.zip.ZipInputStream;
049import java.util.zip.ZipOutputStream;
050
051import lombok.extern.slf4j.Slf4j;
052import org.hl7.fhir.utilities.filesystem.CSFile;
053import org.hl7.fhir.utilities.filesystem.ManagedFileAccess;
054
055@Slf4j
056public class ZipGenerator {
057
058  private Set<String> names = new HashSet<String>();
059        FileOutputStream dest;
060        ZipOutputStream out;
061
062        public ZipGenerator(String filename) throws IOException  {
063                dest = ManagedFileAccess.outStream(filename);
064                out = new ZipOutputStream(new BufferedOutputStream(dest));
065    out.setLevel(Deflater.BEST_COMPRESSION);
066        }
067
068        public void close() throws IOException  {
069                out.close();
070        }
071
072        static final int BUFFER = 2048;
073
074        public void addFromZip(String zipFilename) throws IOException {
075                byte[] buf = new byte[1024];
076
077                ZipInputStream zin = new ZipInputStream(
078                                ManagedFileAccess.inStream(zipFilename));
079
080                try {
081                        ZipEntry entry = zin.getNextEntry();
082                        while (entry != null) {
083                                String name = entry.getName();
084
085                                names.add(name);
086                                // Add ZIP entry to output stream.
087                                out.putNextEntry(new ZipEntry(name));
088                                // Transfer bytes from the ZIP file to the output file
089                                int len;
090                                while ((len = zin.read(buf)) > 0) {
091                                        out.write(buf, 0, len);
092                                }
093
094                                entry = zin.getNextEntry();
095                        }
096                } finally {
097                        zin.close();
098                }
099        }
100
101        public void addFolder(String actualDir, String statedDir, boolean omitIfExists) throws IOException  {
102          File fd = ManagedFileAccess.csfile(actualDir);
103          String files[] = fd.list();
104          for (String f : files) {
105            if (!".DS_Store".equals(f)) {
106              if (ManagedFileAccess.csfile(Utilities.path(actualDir, f)).isDirectory())
107                addFolder(Utilities.path(actualDir, f), Utilities.pathURL(statedDir, f), omitIfExists);
108              else
109                addFileName(Utilities.pathURL(statedDir, f), Utilities.path(actualDir, f), omitIfExists);
110            }
111          }
112        }
113
114  public void addFolder(String actualDir, String statedDir, boolean omitIfExists, String noExt) throws IOException  {
115    File fd = ManagedFileAccess.csfile(actualDir);
116    String files[] = fd.list();
117    for (String f : files) {
118      if (!".DS_Store".equals(f)) {
119        if (ManagedFileAccess.csfile(Utilities.path(actualDir, f)).isDirectory())
120          addFolder(Utilities.path(actualDir, f), Utilities.pathURL(statedDir, f), omitIfExists, noExt);
121        else if (noExt == null || !f.endsWith(noExt))
122          addFileName(Utilities.pathURL(statedDir, f), Utilities.path(actualDir, f), omitIfExists);
123      }
124    }
125  }
126
127  public void addFiles(String actualDir, String statedDir, String ext, String noExt) throws FileNotFoundException, IOException {
128    byte data[] = new byte[BUFFER];
129    statedDir = statedDir.replace("\\", "/");
130    File f = ManagedFileAccess.csfile(actualDir);
131
132    String files[] = f.list();
133    if (files == null) {
134      log.info("no files found in "+f.getName());
135    } else {
136      for (int i = 0; i < files.length; i++) {
137        if (!".DS_Store".equals(files[i])) {
138          String fn = Utilities.path(actualDir, files[i]);
139          if ( ManagedFileAccess.csfile(fn).isFile() && ((ext == null || files[i].endsWith(ext)) && (noExt == null || !files[i].endsWith(noExt)))) {
140            FileInputStream fi = ManagedFileAccess.inStream(fn);
141            BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
142            ZipEntry entry = new ZipEntry(statedDir + files[i]);
143            names.add(statedDir + files[i]);
144            out.putNextEntry(entry);
145            int count;
146            while ((count = origin.read(data, 0, BUFFER)) != -1) {
147              out.write(data, 0, count);
148            }
149            origin.close();
150          }
151        }
152      }
153    }
154  }
155
156  public void addFilesFiltered(String actualDir, String statedDir, String ext, String[] noExt) throws FileNotFoundException, IOException {
157    byte data[] = new byte[BUFFER];
158    statedDir = statedDir.replace("\\", "/");
159    File f = ManagedFileAccess.csfile(actualDir);
160
161    String files[] = f.list();
162    for (int i = 0; i < files.length; i++) {
163      if (!".DS_Store".equals(files[i])) {
164        if ( ManagedFileAccess.csfile(actualDir + files[i]).isFile() && ((ext == null || files[i].endsWith(ext)))) {
165          boolean ok = true;
166          for (String n : noExt) {
167            ok = ok && !files[i].endsWith(n);
168          }
169          if (ok) {
170            FileInputStream fi = ManagedFileAccess.inStream(actualDir + files[i]);
171            BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
172            ZipEntry entry = new ZipEntry(statedDir + files[i]);
173            names.add(statedDir + files[i]);
174            out.putNextEntry(entry);
175            int count;
176            while ((count = origin.read(data, 0, BUFFER)) != -1) {
177              out.write(data, 0, count);
178            }
179            origin.close();
180          }
181        }
182      }
183    }
184  }
185
186  public void addFileSource(String path, String cnt, boolean omitIfExists) throws IOException  {
187                File tmp = FileUtilities.createTempFile("tmp", ".tmp");
188                FileUtilities.stringToFile(cnt, tmp.getAbsolutePath());
189                addFileName(path, tmp.getAbsolutePath(), omitIfExists);
190                tmp.delete();
191        }
192
193        public void addFileName(String statedPath, String actualPath, boolean omitIfExists) throws IOException  {
194          if (!omitIfExists || !names.contains(statedPath)) {
195            byte data[] = new byte[BUFFER];
196            FileInputStream fi = ManagedFileAccess.inStream(actualPath);
197            BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
198            ZipEntry entry = new ZipEntry(statedPath);
199            names.add(statedPath);
200            out.putNextEntry(entry);
201            int count;
202            while ((count = origin.read(data, 0, BUFFER)) != -1) {
203              out.write(data, 0, count);
204            }
205            origin.close();
206          }
207        }
208
209  public void addBytes(String statedPath, byte[] content, boolean omitIfExists) throws IOException  {
210    if (!omitIfExists || !names.contains(statedPath)) {
211      byte data[] = new byte[BUFFER];
212      InputStream fi = new ByteArrayInputStream(content);
213      BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
214      ZipEntry entry = new ZipEntry(statedPath);
215      names.add(statedPath);
216      out.putNextEntry(entry);
217      int count;
218      while ((count = origin.read(data, 0, BUFFER)) != -1) {
219        out.write(data, 0, count);
220      }
221      origin.close();
222    }
223  }
224
225  public void addMimeTypeFile(String statedPath, String actualPath) throws IOException  {
226  //  byte data[] = new byte[BUFFER];
227    CRC32 crc = new CRC32();
228    
229  //  FileInputStream fi = ManagedFileAccess.inStream(actualPath);
230  //  BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
231    out.setLevel(0);
232    ZipEntry entry = new ZipEntry(statedPath);
233    entry.setExtra(null);
234    names.add(statedPath);
235    String contents = "application/epub+zip";
236    crc.update(contents.getBytes());
237    entry.setCompressedSize(contents.length());
238    entry.setSize(contents.length());
239    entry.setCrc(crc.getValue());
240    entry.setMethod(ZipEntry.STORED);
241    out.putNextEntry(entry);
242 //   int count;
243//    while ((count = origin.read(data, 0, BUFFER)) != -1) {
244//      out.write(data, 0, count);
245//    }
246  //  origin.close();
247    out.write(contents.getBytes(),0,contents.length());
248    out.setLevel(Deflater.BEST_COMPRESSION);
249  }
250
251  public void addStream(String statedPath, InputStream fi, boolean omitIfExists) throws IOException  {
252    if (!omitIfExists || !names.contains(statedPath)) {
253      byte data[] = new byte[BUFFER];
254      BufferedInputStream origin = new BufferedInputStream(fi, BUFFER);
255      ZipEntry entry = new ZipEntry(statedPath);
256      names.add(statedPath);
257      out.putNextEntry(entry);
258      int count;
259      while ((count = origin.read(data, 0, BUFFER)) != -1) {
260        out.write(data, 0, count);
261      }
262      origin.close();
263    }
264  }
265
266}