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