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 package argos.deploy;
32
33 import java.io.File;
34 import java.io.FileInputStream;
35 import java.io.IOException;
36 import java.util.ArrayList;
37 import java.util.Collections;
38 import java.util.Enumeration;
39 import java.util.List;
40 import java.util.logging.Level;
41 import java.util.logging.Logger;
42 import java.util.zip.ZipEntry;
43 import java.util.zip.ZipFile;
44 import java.util.zip.ZipInputStream;
45
46
47
48
49
50
51
52
53
54 public final class JarResource {
55 private static final Logger logger = Logger.getLogger(JarResource.class.getName());
56 private List<String> content;
57 private File jarFile;
58
59
60
61
62
63
64
65
66 public JarResource(File jarFileName) {
67 super();
68 this.jarFile = jarFileName;
69 content = new ArrayList<String>();
70 init();
71 }
72
73 public synchronized void reload() {
74 content.clear();
75 init();
76 }
77
78
79
80
81
82
83
84 public byte[] getResource(String name) {
85 if(hasFile(name)) {
86 byte[] b = null;
87 ZipEntry ze = null;
88 FileInputStream fis = null;
89 ZipInputStream zis = null;
90 try {
91 fis = new FileInputStream(jarFile);
92 zis = new ZipInputStream(fis);
93 while((ze = zis.getNextEntry()) != null) {
94 if(ze.getName().equals(name)) {
95 int size = (int) ze.getSize();
96 b = new byte[size];
97 int rb = 0;
98 int chunk = 0;
99 while((size - rb) > 0) {
100 chunk = zis.read(b, rb, size - rb);
101 if(chunk == -1) {
102 break;
103 }
104 rb += chunk;
105 }
106 break;
107 }
108 }
109 zis.close();
110 fis.close();
111 return b;
112 }
113 catch (IOException e) {
114 logger.log(Level.WARNING, "JarResource couldnt read file " + jarFile, e);
115 }
116 finally {
117 if(zis != null) {
118 try {
119 zis.close();
120 } catch(IOException ignore) {}
121 }
122 if(fis != null) {
123 try {
124 fis.close();
125 } catch(IOException ignore) {}
126 }
127 }
128 }
129 return null;
130 }
131
132
133
134
135
136 private void init() {
137 try {
138 ZipFile zf = new ZipFile(jarFile);
139 Enumeration<? extends ZipEntry> e = zf.entries();
140 while(e.hasMoreElements()) {
141 ZipEntry entry = e.nextElement();
142 content.add(entry.getName());
143 }
144 zf.close();
145 } catch (IOException e) {
146 logger.log(Level.WARNING, "JarResource couldnt read file " + jarFile, e);
147 }
148 Collections.sort(content);
149 }
150
151 public boolean hasFile(String filename) {
152 return Collections.binarySearch(content, filename) >= 0;
153 }
154
155 public File getFile() {
156 return jarFile;
157 }
158 }