View Javadoc

1   package com.atlassian.plugin.util.zip;
2   
3   import java.io.File;
4   import java.io.InputStream;
5   import java.io.IOException;
6   import java.util.zip.ZipInputStream;
7   import java.util.zip.ZipEntry;
8   
9   import org.apache.commons.io.IOUtils;
10  import org.apache.commons.lang.StringUtils;
11  
12  /**
13   * Stream based ZIP extractor
14   */
15  public class StreamUnzipper extends AbstractUnzipper
16  {
17      private ZipInputStream zis;
18  
19      /**
20       * Construct a stream unzipper
21       * @param zipStream Inputstream to use for ZIP archive reading
22       * @param destDir Directory to unpack stream contents
23       */
24      public StreamUnzipper(InputStream zipStream, File destDir)
25      {
26          if (zipStream == null)
27              throw new IllegalArgumentException("zip stream cannot be null");
28          this.zis = new ZipInputStream(zipStream);
29          this.destDir = destDir;
30      }
31  
32      public void unzip() throws IOException
33      {
34         ZipEntry zipEntry = zis.getNextEntry();
35         try
36         {
37             while (zipEntry != null)
38             {
39                 saveEntry(zis, zipEntry);
40                 zis.closeEntry();
41                 zipEntry = zis.getNextEntry();
42             }
43         }
44         finally
45         {
46              IOUtils.closeQuietly(zis);
47         }
48      }
49  
50      public File unzipFileInArchive(String fileName) throws IOException
51      {
52          File result = null;
53  
54          try
55          {
56              ZipEntry zipEntry = zis.getNextEntry();
57              while (zipEntry != null)
58              {
59                  String entryName = zipEntry.getName();
60  
61                  // os-dependent zips contain a leading back slash "\" character. we want to strip this off first
62                  if (StringUtils.isNotEmpty(entryName) && entryName.startsWith("/"))
63                      entryName = entryName.substring(1);
64  
65                  if (fileName.equals(entryName))
66                  {
67                      result = saveEntry(zis, zipEntry);
68                      break;
69                  }
70                  zis.closeEntry();
71                  zipEntry = zis.getNextEntry();
72              }
73          }
74          finally
75          {
76              IOUtils.closeQuietly(zis);
77          }
78  
79          return result;
80      }
81  
82      public ZipEntry[] entries() throws IOException
83      {
84          return entries(zis);
85      }
86  }