1 package org.apache.velocity.runtime.resource.loader;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.net.JarURLConnection;
25 import java.net.URL;
26 import java.util.Enumeration;
27 import java.util.jar.JarEntry;
28 import java.util.jar.JarFile;
29 import java.util.Hashtable;
30
31 import org.apache.velocity.runtime.RuntimeServices;
32 import org.apache.velocity.runtime.log.Log;
33 import org.apache.velocity.exception.ResourceNotFoundException;
34 import org.apache.velocity.exception.VelocityException;
35
36
37
38
39
40
41
42 public class JarHolder
43 {
44 private String urlpath = null;
45 private JarFile theJar = null;
46 private JarURLConnection conn = null;
47
48 private Log log = null;
49
50
51
52
53
54 public JarHolder( RuntimeServices rs, String urlpath )
55 {
56 this.log = rs.getLog();
57
58 this.urlpath=urlpath;
59 init();
60
61 if (log.isDebugEnabled())
62 {
63 log.debug("JarHolder: initialized JAR: " + urlpath);
64 }
65 }
66
67
68
69
70 public void init()
71 {
72 try
73 {
74 if (log.isDebugEnabled())
75 {
76 log.debug("JarHolder: attempting to connect to " + urlpath);
77 }
78 URL url = new URL( urlpath );
79 conn = (JarURLConnection) url.openConnection();
80 conn.setAllowUserInteraction(false);
81 conn.setDoInput(true);
82 conn.setDoOutput(false);
83 conn.connect();
84 theJar = conn.getJarFile();
85 }
86 catch (IOException ioe)
87 {
88 String msg = "JarHolder: error establishing connection to JAR at \""
89 + urlpath + "\"";
90 log.error(msg, ioe);
91 throw new VelocityException(msg, ioe);
92 }
93 }
94
95
96
97
98 public void close()
99 {
100 try
101 {
102 theJar.close();
103 }
104 catch ( Exception e )
105 {
106 String msg = "JarHolder: error closing the JAR file";
107 log.error(msg, e);
108 throw new VelocityException(msg, e);
109 }
110 theJar = null;
111 conn = null;
112
113 log.trace("JarHolder: JAR file closed");
114 }
115
116
117
118
119
120
121 public InputStream getResource( String theentry )
122 throws ResourceNotFoundException {
123 InputStream data = null;
124
125 try
126 {
127 JarEntry entry = theJar.getJarEntry( theentry );
128
129 if ( entry != null )
130 {
131 data = theJar.getInputStream( entry );
132 }
133 }
134 catch(Exception fnfe)
135 {
136 log.error("JarHolder: getResource() error", fnfe);
137 throw new ResourceNotFoundException(fnfe);
138 }
139
140 return data;
141 }
142
143
144
145
146 public Hashtable getEntries()
147 {
148 Hashtable allEntries = new Hashtable(559);
149
150 Enumeration all = theJar.entries();
151 while ( all.hasMoreElements() )
152 {
153 JarEntry je = (JarEntry)all.nextElement();
154
155
156 if ( !je.isDirectory() )
157 {
158 allEntries.put( je.getName(), this.urlpath );
159 }
160 }
161 return allEntries;
162 }
163
164
165
166
167 public String getUrlPath()
168 {
169 return urlpath;
170 }
171 }
172
173
174
175
176
177
178