-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
UrlResource.java
389 lines (335 loc) · 12.3 KB
/
UrlResource.java
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.core.io.impl;
import java.io.Externalizable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.drools.core.util.StringUtils;
import org.drools.core.io.internal.InternalResource;
import org.drools.core.util.codec.Base64;
import org.kie.api.io.Resource;
import org.kie.api.io.ResourceType;
/**
* Borrowed gratuitously from Spring under ASL2.0.
*
* Added in local file cache ability for http and https urls.
*
* Set the system property: "drools.resource.urlcache" to a directory which can be written to and read from
* as a cache - so remote resources will be cached with last known good copies.
*/
public class UrlResource extends BaseResource
implements
InternalResource,
Externalizable {
private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;
public static File CACHE_DIR = getCacheDir();
private URL url;
private long lastRead = -1;
private static final String DROOLS_RESOURCE_URLCACHE = "drools.resource.urlcache";
private String basicAuthentication = "disabled";
private String username = "";
private String password = "";
public UrlResource() {
}
public UrlResource(URL url) {
this.url = getCleanedUrl(url,
url.toString());
setSourcePath(this.url.getPath());
setResourceType(ResourceType.determineResourceType(this.url.getPath()));
}
public UrlResource(String path) {
try {
this.url = getCleanedUrl(new URL(path),
path);
setSourcePath(this.url.getPath());
setResourceType(ResourceType.determineResourceType(this.url.getPath()));
} catch (MalformedURLException e) {
throw new IllegalArgumentException("'" + path + "' path is malformed",
e);
}
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(this.url);
}
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
this.url = (URL) in.readObject();
}
public String getBasicAuthentication() {
return basicAuthentication;
}
public void setBasicAuthentication(String basicAuthentication) {
this.basicAuthentication = basicAuthentication;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
/**
* This implementation opens an InputStream for the given URL.
* It sets the "UseCaches" flag to <code>false</code>,
* mainly to avoid jar file locking on Windows.
* @see java.net.URL#openConnection()
* @see java.net.URLConnection#setUseCaches(boolean)
* @see java.net.URLConnection#getInputStream()
*/
public InputStream getInputStream() throws IOException {
try {
long lastMod = grabLastMod();
if (lastMod == 0) {
//we will try the cache...
if (cacheFileExists())
return fromCache();
}
if (lastMod > 0 && lastMod > lastRead) {
if (CACHE_DIR != null && (url.getProtocol().equals("http") || url.getProtocol().equals("https"))) {
//lets grab a copy and cache it in case we need it in future...
cacheStream();
lastMod = getCacheFile().lastModified();
this.lastRead = lastMod;
return fromCache();
}
}
this.lastRead = lastMod;
return grabStream();
} catch (IOException e) {
if (cacheFileExists()) {
return fromCache();
} else {
throw e;
}
}
}
private boolean cacheFileExists() {
return CACHE_DIR != null && getCacheFile().exists();
}
private InputStream fromCache() throws FileNotFoundException, UnsupportedEncodingException {
File fi = getCacheFile();
return new FileInputStream(fi);
}
private File getCacheFile() {
try {
return new File(CACHE_DIR, URLEncoder.encode(this.url.toString(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
private File getTemproralCacheFile() {
try {
return new File(CACHE_DIR, URLEncoder.encode(this.url.toString(), "UTF-8") + "_tmp");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* Save a copy in the local cache - in case remote source is not available in future.
*/
private void cacheStream() {
try {
File fi = getTemproralCacheFile();
if (fi.exists())
fi.delete();
FileOutputStream fout = new FileOutputStream(fi);
InputStream in = grabStream();
byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
int n;
while (-1 != (n = in.read(buffer))) {
fout.write(buffer, 0, n);
}
fout.flush();
fout.close();
in.close();
File cacheFile = getCacheFile();
fi.renameTo(cacheFile);
} catch (Exception e) {
e.printStackTrace();
}
}
private InputStream grabStream() throws IOException {
URLConnection con = this.url.openConnection();
con.setUseCaches(false);
if (con instanceof HttpURLConnection) {
if ("enabled".equalsIgnoreCase(basicAuthentication)) {
String userpassword = username + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(userpassword.getBytes());
((HttpURLConnection) con).setRequestProperty("Authorization",
"Basic " + new String(authEncBytes));
}
}
return con.getInputStream();
}
public Reader getReader() throws IOException {
return new InputStreamReader(getInputStream());
}
/**
* Determine a cleaned URL for the given original URL.
* @param originalUrl the original URL
* @param originalPath the original URL path
* @return the cleaned URL
*/
private URL getCleanedUrl(URL originalUrl,
String originalPath) {
try {
return new URL(StringUtils.cleanPath(originalPath));
} catch (MalformedURLException ex) {
// Cleaned URL path cannot be converted to URL
// -> take original URL.
return originalUrl;
}
}
public URL getURL() throws IOException {
return this.url;
}
public boolean hasURL() {
return true;
}
public File getFile() throws IOException {
try {
return new File(StringUtils.toURI(url.toString()).getSchemeSpecificPart());
} catch (Exception e) {
throw new RuntimeException("Unable to get File for url " + this.url, e);
}
}
public long getLastModified() {
try {
long lm = grabLastMod();
//try the cache.
if (lm == 0 && cacheFileExists()) {
//OK we will return it from the local cached copy, as remote one isn't available..
return getCacheFile().lastModified();
}
return lm;
} catch (IOException e) {
//try the cache...
if (cacheFileExists()) {
//OK we will return it from the local cached copy, as remote one isn't available..
return getCacheFile().lastModified();
} else {
throw new RuntimeException("Unable to get LastMofified for ClasspathResource",
e);
}
}
}
private long grabLastMod() throws IOException {
// use File if possible, as http rounds milliseconds on some machines, this fine level of granularity is only really an issue for testing
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4504473
if ("file".equals(url.getProtocol())) {
File file = getFile();
return file.lastModified();
} else {
URLConnection conn = getURL().openConnection();
if (conn instanceof HttpURLConnection) {
((HttpURLConnection) conn).setRequestMethod("HEAD");
if ("enabled".equalsIgnoreCase(basicAuthentication)) {
String userpassword = username + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(userpassword.getBytes());
((HttpURLConnection) conn).setRequestProperty("Authorization",
"Basic " + new String(authEncBytes));
}
}
long date = conn.getLastModified();
if (date == 0) {
try {
date = Long.parseLong(conn.getHeaderField("lastModified"));
} catch (Exception e) { /* well, we tried ... */
}
}
return date;
}
}
public long getLastRead() {
return this.lastRead;
}
public boolean isDirectory() {
try {
URL url = getURL();
if ("file".equals(url.getProtocol())) {
File file = new File(StringUtils.toURI(url.toString()).getSchemeSpecificPart());
return file.isDirectory();
}
} catch (Exception e) {
// swallow as returned false
}
return false;
}
public Collection<Resource> listResources() {
try {
URL url = getURL();
if ("file".equals(url.getProtocol())) {
File dir = getFile();
List<Resource> resources = new ArrayList<Resource>();
for (File file : dir.listFiles()) {
resources.add(new FileSystemResource(file));
}
return resources;
}
} catch (Exception e) {
// swallow as we'll throw an exception anyway
}
throw new RuntimeException("This Resource cannot be listed, or is not a directory");
}
/**
* This implementation compares the underlying URL references.
*/
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
return (obj == this || (obj instanceof UrlResource && this.url.equals(((UrlResource) obj).url)));
}
/**
* This implementation returns the hash code of the underlying URL reference.
*/
public int hashCode() {
return this.url.hashCode();
}
public String toString() {
return "[UrlResource path='" + this.url.toString() + "']";
}
private static File getCacheDir() {
String root = System.getProperty(DROOLS_RESOURCE_URLCACHE, "NONE");
if (root.equals("NONE")) {
return null;
} else {
return new File(root);
}
}
}