Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: c90f1e9c9350804d126db56f351d1f9e22e4d760 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
/***************************************************************************
 * Copyright (c) 2004 - 2007 Eike Stepper, Germany.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * 
 * Contributors:
 *    Eike Stepper - initial API and implementation
 **************************************************************************/
package org.eclipse.net4j.util.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * @author Eike Stepper
 */
public final class ZIPUtil
{
  public static final int DEFALULT_BUFFER_SIZE = 4096;

  private static final int ORDER_KEEP = -1;

  private static final int ORDER_SWAP = 1;

  private ZIPUtil()
  {
  }

  public static void zip(ZipEntryHandler handler, File zipFile) throws IORuntimeException
  {
    final byte[] buffer = new byte[DEFALULT_BUFFER_SIZE];
    final EntryContext context = new EntryContext();

    FileOutputStream fos = IOUtil.openOutputStream(zipFile);
    ZipOutputStream zos = null;
    InputStream input = null;
    ZipEntry entry = null;

    try
    {
      zos = new ZipOutputStream(new BufferedOutputStream(fos, DEFALULT_BUFFER_SIZE));
      for (;;)
      {
        handler.handleEntry(context);
        if (context.isEmpty())
        {
          break;
        }

        try
        {
          String name = context.getName().replace(File.separatorChar, '/');
          entry = new ZipEntry(name);
          zos.putNextEntry(entry);

          if (!context.isDirectory())
          {
            input = context.getInputStream();
            if (input == null)
            {
              throw new IllegalStateException("Input is null for zip entry " + name);
            }

            IOUtil.copy(input, zos, buffer);
          }
        }
        finally
        {
          IOUtil.closeSilent(input);
          if (entry != null)
          {
            zos.closeEntry();
          }

          context.reset();
        }
      }
    }
    catch (IOException ex)
    {
      throw new IORuntimeException(ex);
    }
    finally
    {
      IOUtil.closeSilent(zos);
      IOUtil.closeSilent(fos);
    }
  }

  public static void zip(File sourceFolder, boolean excludeRoot, File zipFile)
  {
    zip(new FileSystemZipHandler(sourceFolder, excludeRoot), zipFile);
  }

  public static void unzip(File zipFile, UnzipHandler handler) throws IORuntimeException
  {
    FileInputStream fis = IOUtil.openInputStream(zipFile);
    ZipInputStream zis = null;

    try
    {
      zis = new ZipInputStream(new BufferedInputStream(fis, DEFALULT_BUFFER_SIZE));

      ZipEntry entry;
      while ((entry = zis.getNextEntry()) != null)
      {
        if (entry.isDirectory())
        {
          handler.unzipDirectory(entry.getName());
        }
        else
        {
          // TODO Provide delegating InputStream that ignores close()
          handler.unzipFile(entry.getName(), zis);
        }
      }
    }
    catch (IOException ex)
    {
      throw new IORuntimeException(ex);
    }
    finally
    {
      IOUtil.closeSilent(zis);
      IOUtil.closeSilent(fis);
    }
  }

  public static void unzip(File zipFile, File targetFolder) throws IORuntimeException
  {
    unzip(zipFile, new FileSystemUnzipHandler(targetFolder, DEFALULT_BUFFER_SIZE));
  }

  /**
   * @author Eike Stepper
   */
  public interface ZipEntryHandler
  {
    public void handleEntry(EntryContext context) throws IOException;
  }

  /**
   * @author Eike Stepper
   */
  public interface UnzipHandler
  {
    public void unzipDirectory(String name) throws IOException;

    public void unzipFile(String name, InputStream zipStream) throws IOException;
  }

  /**
   * @author Eike Stepper
   */
  public static final class EntryContext
  {
    private static final String EMPTY = new String();

    private String name = EMPTY;

    private InputStream inputStream;

    private boolean directory;

    EntryContext()
    {
    }

    void reset()
    {
      name = null;
      inputStream = null;
    }

    boolean isEmpty()
    {
      return name == null;
    }

    boolean isDirectory()
    {
      return directory;
    }

    String getName()
    {
      return name;
    }

    InputStream getInputStream()
    {
      return inputStream;
    }

    public void setName(String name, boolean directory)
    {
      this.name = name + (directory ? "/" : "");
      this.directory = directory;
    }

    public void setInputStream(InputStream inputStream)
    {
      this.inputStream = inputStream;
    }
  }

  /**
   * @author Eike Stepper
   */
  public static final class FileSystemZipHandler implements ZipEntryHandler
  {
    private int sourceFolderLength;

    private transient Iterator<File> files;

    public FileSystemZipHandler(File sourceFolder, boolean excludeRoot)
    {
      File root = excludeRoot ? sourceFolder : sourceFolder.getParentFile();
      sourceFolderLength = root.getAbsolutePath().length();
      if (excludeRoot)
      {
        ++sourceFolderLength;
      }

      final int baseLength = sourceFolder.getAbsolutePath().length();
      List<File> list = IOUtil.listBreadthFirst(sourceFolder);
      Collections.sort(list, new Comparator<File>()
      {
        public int compare(File f1, File f2)
        {
          String path1 = getPath(f1, baseLength);
          String path2 = getPath(f2, baseLength);
          if (path1.length() == 0) return ORDER_KEEP;
          if (path2.length() == 0) return ORDER_SWAP;

          if (f1.isDirectory())
          {
            if (f2.isDirectory())
            {
              // f1=dir, f2=dir
              if (path1.equalsIgnoreCase("/META-INF"))
              {
                return ORDER_KEEP;
              }

              if (path2.equalsIgnoreCase("/META-INF"))
              {
                return ORDER_SWAP;
              }

              return path1.compareTo(path2);
            }
            else
            {
              // f1=dir, f2=file
              if (path1.equalsIgnoreCase("/META-INF"))
              {
                return ORDER_KEEP;
              }

              if (path2.equalsIgnoreCase("/META-INF/MANIFEST.MF"))
              {
                return ORDER_SWAP;
              }

              return ORDER_KEEP;
            }
          }
          else
          {
            if (f2.isDirectory())
            {
              // f1=file, f2=dir
              if (path2.equalsIgnoreCase("/META-INF"))
              {
                return ORDER_SWAP;
              }

              if (path1.equalsIgnoreCase("/META-INF/MANIFEST.MF"))
              {
                return ORDER_KEEP;
              }

              return ORDER_SWAP;
            }
            else
            {
              // f1=file, f2=file
              if (path1.equalsIgnoreCase("/META-INF/MANIFEST.MF"))
              {
                return ORDER_KEEP;
              }

              if (path2.equalsIgnoreCase("/META-INF/MANIFEST.MF"))
              {
                return ORDER_SWAP;
              }

              return path1.compareTo(path2);
            }
          }
        }

        private String getPath(File file, int baseLength)
        {
          String absolutePath = file.getAbsolutePath();
          String substring = absolutePath.substring(baseLength);
          String replace = substring.replace(File.separatorChar, '/');
          return replace;
        }
      });

      files = list.iterator();
      if (excludeRoot)
      {
        files.next();
      }
    }

    public void handleEntry(EntryContext context) throws IOException
    {
      if (files.hasNext())
      {
        File file = files.next();
        String name = getName(file);
        if (name.length() != 0)
        {
          context.setName(name, file.isDirectory());

          if (file.isFile())
          {
            context.setInputStream(IOUtil.openInputStream(file));
          }
        }
      }
    }

    protected String getName(File file)
    {
      return file.getAbsolutePath().substring(sourceFolderLength);
    }
  }

  /**
   * @author Eike Stepper
   */
  public static final class FileSystemUnzipHandler implements UnzipHandler
  {
    private File targetFolder;

    private transient byte[] buffer;

    public FileSystemUnzipHandler(File targetFolder, int bufferSize)
    {
      this.targetFolder = targetFolder;
      buffer = new byte[bufferSize];
    }

    public File getTargetFolder()
    {
      return targetFolder;
    }

    public void unzipDirectory(String name)
    {
      File directory = new File(targetFolder, name);
      if (!directory.exists())
      {
        directory.mkdirs();
      }
    }

    public void unzipFile(String name, InputStream zipStream)
    {
      File targetFile = new File(targetFolder, name);
      if (!targetFile.getParentFile().exists())
      {
        targetFile.getParentFile().mkdirs();
      }

      FileOutputStream out = IOUtil.openOutputStream(targetFile);

      try
      {
        IOUtil.copy(zipStream, out, buffer);
      }
      finally
      {
        IOUtil.closeSilent(out);
      }
    }
  }
}

Back to the top