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