1 36 package org.ungoverned.moduleloader; 37 38 import java.io.*; 39 import java.util.jar.JarFile ; 40 import java.util.zip.ZipEntry ; 41 42 50 public class JarResourceSource implements ResourceSource 51 { 52 private static final int BUFSIZE = 4096; 53 54 private File m_file = null; 55 private JarFile m_jarFile = null; 56 private boolean m_opened = false; 57 58 65 public JarResourceSource(String fileName) 66 { 67 m_file = new File (fileName); 68 } 69 70 77 public JarResourceSource(File file) 78 { 79 m_file = file; 80 } 81 82 87 protected void finalize() 88 { 89 if (m_jarFile != null) 90 { 91 try { 92 m_jarFile.close(); 93 } catch (IOException ex) { 94 } 96 } 97 } 98 99 107 public void open() 108 { 109 m_opened = true; 110 } 111 112 118 public synchronized void close() 119 { 120 try { 121 if (m_jarFile != null) 122 { 123 m_jarFile.close(); 124 } 125 } catch (Exception ex) { 126 System.err.println("JarResourceSource: " + ex); 127 } 128 129 m_jarFile = null; 130 m_opened = false; 131 } 132 133 public synchronized boolean hasResource(String name) throws IllegalStateException 135 { 136 if (!m_opened) 137 { 138 throw new IllegalStateException ("JarResourceSource is not open"); 139 } 140 141 if (m_jarFile == null) 143 { 144 try { 145 openJarFile(); 146 } catch (IOException ex) { 147 System.err.println("JarResourceSource: " + ex); 148 return false; 149 } 150 } 151 152 try { 153 ZipEntry ze = m_jarFile.getEntry(name); 154 return ze != null; 155 } catch (Exception ex) { 156 return false; 157 } finally { 158 } 159 } 160 161 public synchronized byte[] getBytes(String name) throws IllegalStateException 163 { 164 if (!m_opened) 165 { 166 throw new IllegalStateException ("JarResourceSource is not open"); 167 } 168 169 if (m_jarFile == null) 171 { 172 try { 173 openJarFile(); 174 } catch (IOException ex) { 175 System.err.println("JarResourceSource: " + ex); 176 return null; 177 } 178 } 179 180 InputStream is = null; 182 ByteArrayOutputStream baos = null; 183 184 try { 185 ZipEntry ze = m_jarFile.getEntry(name); 186 if (ze == null) 187 { 188 return null; 189 } 190 is = m_jarFile.getInputStream(ze); 191 if (is == null) 192 { 193 return null; 194 } 195 baos = new ByteArrayOutputStream(BUFSIZE); 196 byte[] buf = new byte[BUFSIZE]; 197 int n = 0; 198 while ((n = is.read(buf, 0, buf.length)) >= 0) 199 { 200 baos.write(buf, 0, n); 201 } 202 return baos.toByteArray(); 203 204 } catch (Exception ex) { 205 return null; 206 } finally { 207 try { 208 if (baos != null) baos.close(); 209 } catch (Exception ex) { 210 } 211 try { 212 if (is != null) is.close(); 213 } catch (Exception ex) { 214 } 215 } 216 } 217 218 private void openJarFile() throws IOException 219 { 220 if (m_jarFile == null) 221 { 222 m_jarFile = new JarFile (m_file); 223 } 224 } 225 226 public String toString() 227 { 228 return "JAR " + m_file.getPath(); 229 } 230 } | Popular Tags |