• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright 2007 Google Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.tonicsystems.jarjar.util;
18 
19 import java.util.jar.JarEntry;
20 import java.util.jar.JarFile;
21 import java.util.jar.JarOutputStream;
22 import java.util.Enumeration;
23 import java.io.*;
24 import java.util.*;
25 
26 public class StandaloneJarProcessor
27 {
run(File from, File to, JarProcessor proc)28     public static void run(File from, File to, JarProcessor proc) throws IOException {
29         byte[] buf = new byte[0x2000];
30 
31         JarFile in = new JarFile(from);
32         final File tmpTo = File.createTempFile("jarjar", ".jar");
33         JarOutputStream out = new JarOutputStream(new FileOutputStream(tmpTo));
34         Set<String> entries = new HashSet<String>();
35         try {
36             EntryStruct struct = new EntryStruct();
37             Enumeration<JarEntry> e = in.entries();
38             while (e.hasMoreElements()) {
39                 JarEntry entry = e.nextElement();
40                 struct.name = entry.getName();
41                 struct.time = entry.getTime();
42                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
43                 IoUtil.pipe(in.getInputStream(entry), baos, buf);
44                 struct.data = baos.toByteArray();
45                 if (proc.process(struct)) {
46                     if (entries.add(struct.name)) {
47                         entry = new JarEntry(struct.name);
48                         entry.setTime(struct.time);
49                         entry.setCompressedSize(-1);
50                         out.putNextEntry(entry);
51                         out.write(struct.data);
52                     } else if (struct.name.endsWith("/")) {
53                         // TODO(chrisn): log
54                     } else {
55                         throw new IllegalArgumentException("Duplicate jar entries: " + struct.name);
56                     }
57                 }
58             }
59 
60         }
61         finally {
62             in.close();
63             out.close();
64         }
65 
66          // delete the empty directories
67         IoUtil.copyZipWithoutEmptyDirectories(tmpTo, to);
68         tmpTo.delete();
69 
70     }
71 }
72