001: /*
002: * @(#)JarLoader.java 1.2 04/12/06
003: *
004: * Copyright (c) 1997-2003 Sun Microsystems, Inc. All Rights Reserved.
005: *
006: * See the file "LICENSE.txt" for information on usage and redistribution
007: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
008: */
009: package pnuts.lib;
010:
011: import java.net.*;
012: import java.io.*;
013: import java.util.*;
014: import java.util.zip.*;
015:
016: class JarLoader implements Loader {
017: private final static boolean DEBUG = false;
018: private ZipFile jar;
019: private URL csu;
020: private URL base;
021:
022: JarLoader(URL url) throws IOException {
023: base = new URL("jar", "", -1, url + "!/");
024: jar = getJarFile(url);
025: csu = url;
026: }
027:
028: private ZipFile getJarFile(URL url) throws IOException {
029: if ("file".equals(url.getProtocol())) {
030: String path = url.getFile()
031: .replace('/', File.separatorChar);
032: File file = new File(path);
033: if (!file.exists()) {
034: throw new FileNotFoundException(path);
035: }
036: return new ZipFile(path);
037: }
038: return null;
039: }
040:
041: public Resource getResource(final String name) {
042: if (jar != null) {
043: ZipEntry entry = jar.getEntry(name);
044:
045: if (entry != null) {
046: final URL url;
047: final ZipEntry ze = entry;
048: try {
049: url = new URL(base, name);
050: } catch (MalformedURLException e) {
051: return null;
052: } catch (IOException e) {
053: return null;
054: }
055: return new Resource() {
056: public URL getURL() {
057: return url;
058: }
059:
060: public InputStream getInputStream()
061: throws IOException {
062: return jar.getInputStream(ze);
063: }
064:
065: public int getContentLength() {
066: return (int) ze.getSize();
067: }
068: };
069: }
070: return null;
071: } else {
072: try {
073: if (DEBUG) {
074: System.out.println("name = " + name);
075: }
076: final ZipInputStream zin = new ZipInputStream(csu
077: .openStream());
078: ZipEntry entry = null;
079: while ((entry = zin.getNextEntry()) != null) {
080: if (DEBUG) {
081: System.out.println(entry.getName());
082: }
083: if (name.equals(entry.getName())) {
084: final URL url;
085: final ZipEntry ze = entry;
086: try {
087: url = new URL(base, name);
088: } catch (MalformedURLException e) {
089: if (DEBUG) {
090: e.printStackTrace();
091: }
092: return null;
093: } catch (IOException e) {
094: if (DEBUG) {
095: e.printStackTrace();
096: }
097: return null;
098: }
099: return new Resource() {
100: public URL getURL() {
101: return url;
102: }
103:
104: public InputStream getInputStream()
105: throws IOException {
106: return zin;
107: }
108:
109: public int getContentLength() {
110: return -1;
111: }
112: };
113: }
114: }
115: } catch (IOException e) {
116: if (DEBUG) {
117: e.printStackTrace();
118: }
119: }
120: return null;
121: }
122: }
123: }
|