1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package net.sf.jameleon.util;
20
21 import org.apache.tools.ant.launch.Locator;
22
23 import java.io.*;
24 import java.util.Enumeration;
25 import java.util.jar.JarFile;
26 import java.util.zip.ZipEntry;
27
28 /***
29 * Extracts contents from jar file to the defined directory.
30 */
31 public class JarResourceExtractor {
32
33 private JarFile jarFile;
34
35 /***
36 * Searches the classpath for the jameleon-core.jar file to use
37 * to find the desired resources.
38 * @throws IOException if a jar file containing the jameleon core version config
39 * file cannot be found.
40 */
41 public JarResourceExtractor() throws IOException {
42 File f = Locator.getResourceSource(Thread.currentThread().getContextClassLoader(),
43 JameleonDefaultValues.JAMELEON_VERSION_FILE);
44 if (f == null){
45 f = Locator.getResourceSource(getClass().getClassLoader(),
46 JameleonDefaultValues.JAMELEON_VERSION_FILE);
47 }
48 jarFile = new JarFile(f);
49 }
50
51 /***
52 * Gets the jar file that contains the desired resources
53 * @return
54 */
55 public JarFile getJarFile(){
56 return jarFile;
57 }
58
59 /***
60 * Extracts the files from the jar file to the desired directory.
61 * @param baseDirectory The directory that contains the files to extract
62 * @param directoryToExtractTo The directory to copy the files to
63 */
64 public void extractFilesInDirectory(String baseDirectory, File directoryToExtractTo)
65 throws IOException {
66 if (jarFile != null){
67 Enumeration entries = jarFile.entries();
68 ZipEntry entry; String name;
69 while(entries.hasMoreElements()){
70 entry = (ZipEntry)entries.nextElement();
71 name = entry.getName();
72 if (name.startsWith(baseDirectory+"/")){
73 if (entry.isDirectory()){
74 JameleonUtility.createDirStructure(new File(directoryToExtractTo, name));
75 }else{
76 extractFile(entry, directoryToExtractTo);
77 }
78 }
79 }
80 }
81 }
82
83 public void extractFile(ZipEntry entry, File extractDir)
84 throws IOException {
85 InputStream in = getJarFile().getInputStream(entry);
86 File outputFile = new File(extractDir, entry.getName());
87 OutputStream out = new FileOutputStream(outputFile);
88 try{
89 int c;
90 while ((c = in.read()) != -1){
91 out.write(c);
92 }
93 }finally{
94 in.close();
95 out.close();
96 }
97 }
98 }