Debian Codegraph @

rhino/src/org/mozilla/javascript/commonjs/module/provider/UrlModuleSourceProvider.java

raw symbols SCIP
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 package org.mozilla.javascript.commonjs.module.provider;
6
7 import java.io.FileNotFoundException;
8 import java.io.IOException;
9 import java.io.InputStreamReader;
10 import java.io.Reader;
11 import java.io.Serializable;
12 import java.net.HttpURLConnection;
13 import java.net.URI;
14 import java.net.URISyntaxException;
15 import java.net.URL;
16 import java.net.URLConnection;
17 import java.util.Iterator;
18 import java.util.List;
19
20
21 /**
22 * A URL-based script provider that can load modules against a set of base
23 * privileged and fallback URIs. It is deliberately not named "URI provider"
24 * but a "URL provider" since it actually only works against those URIs that
25 * are URLs (and the JRE has a protocol handler for them). It creates cache
26 * validators that are suitable for use with both file: and http: URL
27 * protocols. Specifically, it is able to use both last-modified timestamps and
28 * ETags for cache revalidation, and follows the HTTP cache expiry calculation
29 * model, and allows for fallback heuristic expiry calculation when no server
30 * specified expiry is provided.
31 * @author Attila Szegedi
32 * @version $Id: UrlModuleSourceProvider.java,v 1.4 2011/04/07 20:26:12 hannes%helma.at Exp $
33 */
34 public class UrlModuleSourceProvider extends ModuleSourceProviderBase
35 {
36 private static final long serialVersionUID = 1L;
37
38 private final Iterable<URI> privilegedUris;
39 private final Iterable<URI> fallbackUris;
40 private final UrlConnectionSecurityDomainProvider
41 urlConnectionSecurityDomainProvider;
42 private final UrlConnectionExpiryCalculator urlConnectionExpiryCalculator;
43
44 /**
45 * Creates a new module script provider that loads modules against a set of
46 * privileged and fallback URIs. It will use a fixed default cache expiry
47 * of 60 seconds, and provide no security domain objects for the resource.
48 * @param privilegedUris an iterable providing the privileged URIs. Can be
49 * null if no privileged URIs are used.
50 * @param fallbackUris an iterable providing the fallback URIs. Can be
51 * null if no fallback URIs are used.
52 */
53 public UrlModuleSourceProvider(Iterable<URI> privilegedUris,
54 Iterable<URI> fallbackUris)
55 {
56 this(privilegedUris, fallbackUris,
57 new DefaultUrlConnectionExpiryCalculator(), null);
58 }
59
60 /**
61 * Creates a new module script provider that loads modules against a set of
62 * privileged and fallback URIs. It will use the specified heuristic cache
63 * expiry calculator and security domain provider.
64 * @param privilegedUris an iterable providing the privileged URIs. Can be
65 * null if no privileged URIs are used.
66 * @param fallbackUris an iterable providing the fallback URIs. Can be
67 * null if no fallback URIs are used.
68 * @param urlConnectionExpiryCalculator the calculator object for heuristic
69 * calculation of the resource expiry, used when no expiry is provided by
70 * the server of the resource. Can be null, in which case the maximum age
71 * of cached entries without validation will be zero.
72 * @param urlConnectionSecurityDomainProvider object that provides security
73 * domain objects for the loaded sources. Can be null, in which case the
74 * loaded sources will have no security domain associated with them.
75 */
76 public UrlModuleSourceProvider(Iterable<URI> privilegedUris,
77 Iterable<URI> fallbackUris,
78 UrlConnectionExpiryCalculator urlConnectionExpiryCalculator,
79 UrlConnectionSecurityDomainProvider urlConnectionSecurityDomainProvider)
80 {
81 this.privilegedUris = privilegedUris;
82 this.fallbackUris = fallbackUris;
83 this.urlConnectionExpiryCalculator = urlConnectionExpiryCalculator;
84 this.urlConnectionSecurityDomainProvider =
85 urlConnectionSecurityDomainProvider;
86 }
87
88 @Override
89 protected ModuleSource loadFromPrivilegedLocations(
90 String moduleId, Object validator)
91 throws IOException, URISyntaxException
92 {
93 return loadFromPathList(moduleId, validator, privilegedUris);
94 }
95
96 @Override
97 protected ModuleSource loadFromFallbackLocations(
98 String moduleId, Object validator)
99 throws IOException, URISyntaxException
100 {
101 return loadFromPathList(moduleId, validator, fallbackUris);
102 }
103
104 private ModuleSource loadFromPathList(String moduleId,
105 Object validator, Iterable<URI> paths)
106 throws IOException, URISyntaxException
107 {
108 if(paths == null) {
109 return null;
110 }
111 for (URI path : paths) {
112 final ModuleSource moduleSource = loadFromUri(
113 path.resolve(moduleId), path, validator);
114 if (moduleSource != null) {
115 return moduleSource;
116 }
117 }
118 return null;
119 }
120
121 @Override
122 protected ModuleSource loadFromUri(URI uri, URI base, Object validator)
123 throws IOException, URISyntaxException
124 {
125 // We expect modules to have a ".js" file name extension ...
126 URI fullUri = new URI(uri + ".js");
127 ModuleSource source = loadFromActualUri(fullUri, base, validator);
128 // ... but for compatibility we support modules without extension,
129 // or ids with explicit extension.
130 return source != null ?
131 source : loadFromActualUri(uri, base, validator);
132 }
133
134 protected ModuleSource loadFromActualUri(URI uri, URI base, Object validator)
135 throws IOException
136 {
137 final URL url = new URL(base == null ? null : base.toURL(), uri.toString());
138 final long request_time = System.currentTimeMillis();
139 final URLConnection urlConnection = openUrlConnection(url);
140 final URLValidator applicableValidator;
141 if(validator instanceof URLValidator) {
142 final URLValidator uriValidator = ((URLValidator)validator);
143 applicableValidator = uriValidator.appliesTo(uri) ? uriValidator :
144 null;
145 }
146 else {
147 applicableValidator = null;
148 }
149 if(applicableValidator != null) {
150 applicableValidator.applyConditionals(urlConnection);
151 }
152 try {
153 urlConnection.connect();
154 if(applicableValidator != null &&
155 applicableValidator.updateValidator(urlConnection,
156 request_time, urlConnectionExpiryCalculator))
157 {
158 close(urlConnection);
159 return NOT_MODIFIED;
160 }
161
162 return new ModuleSource(getReader(urlConnection),
163 getSecurityDomain(urlConnection), uri, base,
164 new URLValidator(uri, urlConnection, request_time,
165 urlConnectionExpiryCalculator));
166 }
167 catch(FileNotFoundException e) {
168 return null;
169 }
170 catch(RuntimeException e) {
171 close(urlConnection);
172 throw e;
173 }
174 catch(IOException e) {
175 close(urlConnection);
176 throw e;
177 }
178 }
179
180 private static Reader getReader(URLConnection urlConnection)
181 throws IOException
182 {
183 return new InputStreamReader(urlConnection.getInputStream(),
184 getCharacterEncoding(urlConnection));
185 }
186
187 private static String getCharacterEncoding(URLConnection urlConnection) {
188 final ParsedContentType pct = new ParsedContentType(
189 urlConnection.getContentType());
190 final String encoding = pct.getEncoding();
191 if(encoding != null) {
192 return encoding;
193 }
194 final String contentType = pct.getContentType();
195 if(contentType != null && contentType.startsWith("text/")) {
196 return "8859_1";
197 }
198 else {
199 return "utf-8";
200 }
201 }
202
203 private Object getSecurityDomain(URLConnection urlConnection) {
204 return urlConnectionSecurityDomainProvider == null ? null :
205 urlConnectionSecurityDomainProvider.getSecurityDomain(
206 urlConnection);
207 }
208
209 private void close(URLConnection urlConnection) {
210 try {
211 urlConnection.getInputStream().close();
212 }
213 catch(IOException e) {
214 onFailedClosingUrlConnection(urlConnection, e);
215 }
216 }
217
218 /**
219 * Override if you want to get notified if the URL connection fails to
220 * close. Does nothing by default.
221 * @param urlConnection the connection
222 * @param cause the cause it failed to close.
223 */
224 protected void onFailedClosingUrlConnection(URLConnection urlConnection,
225 IOException cause) {
226 }
227
228 /**
229 * Can be overridden in subclasses to customize the URL connection opening
230 * process. By default, just calls {@link URL#openConnection()}.
231 * @param url the URL
232 * @return a connection to the URL.
233 * @throws IOException if an I/O error occurs.
234 */
235 protected URLConnection openUrlConnection(URL url) throws IOException {
236 return url.openConnection();
237 }
238
239 @Override
240 protected boolean entityNeedsRevalidation(Object validator) {
241 return !(validator instanceof URLValidator)
242 || ((URLValidator)validator).entityNeedsRevalidation();
243 }
244
245 private static class URLValidator implements Serializable {
246 private static final long serialVersionUID = 1L;
247
248 private final URI uri;
249 private final long lastModified;
250 private final String entityTags;
251 private long expiry;
252
253 public URLValidator(URI uri, URLConnection urlConnection,
254 long request_time, UrlConnectionExpiryCalculator
255 urlConnectionExpiryCalculator) {
256 this.uri = uri;
257 this.lastModified = urlConnection.getLastModified();
258 this.entityTags = getEntityTags(urlConnection);
259 expiry = calculateExpiry(urlConnection, request_time,
260 urlConnectionExpiryCalculator);
261 }
262
263 boolean updateValidator(URLConnection urlConnection, long request_time,
264 UrlConnectionExpiryCalculator urlConnectionExpiryCalculator)
265 throws IOException
266 {
267 boolean isResourceChanged = isResourceChanged(urlConnection);
268 if(!isResourceChanged) {
269 expiry = calculateExpiry(urlConnection, request_time,
270 urlConnectionExpiryCalculator);
271 }
272 return isResourceChanged;
273 }
274
275 private boolean isResourceChanged(URLConnection urlConnection)
276 throws IOException {
277 if(urlConnection instanceof HttpURLConnection) {
278 return ((HttpURLConnection)urlConnection).getResponseCode() ==
279 HttpURLConnection.HTTP_NOT_MODIFIED;
280 }
281 return lastModified == urlConnection.getLastModified();
282 }
283
284 private long calculateExpiry(URLConnection urlConnection,
285 long request_time, UrlConnectionExpiryCalculator
286 urlConnectionExpiryCalculator)
287 {
288 if("no-cache".equals(urlConnection.getHeaderField("Pragma"))) {
289 return 0L;
290 }
291 final String cacheControl = urlConnection.getHeaderField(
292 "Cache-Control");
293 if(cacheControl != null ) {
294 if(cacheControl.indexOf("no-cache") != -1) {
295 return 0L;
296 }
297 final int max_age = getMaxAge(cacheControl);
298 if(-1 != max_age) {
299 final long response_time = System.currentTimeMillis();
300 final long apparent_age = Math.max(0, response_time -
301 urlConnection.getDate());
302 final long corrected_received_age = Math.max(apparent_age,
303 urlConnection.getHeaderFieldInt("Age", 0) * 1000L);
304 final long response_delay = response_time - request_time;
305 final long corrected_initial_age = corrected_received_age +
306 response_delay;
307 final long creation_time = response_time -
308 corrected_initial_age;
309 return max_age * 1000L + creation_time;
310 }
311 }
312 final long explicitExpiry = urlConnection.getHeaderFieldDate(
313 "Expires", -1L);
314 if(explicitExpiry != -1L) {
315 return explicitExpiry;
316 }
317 return urlConnectionExpiryCalculator == null ? 0L :
318 urlConnectionExpiryCalculator.calculateExpiry(urlConnection);
319 }
320
321 private int getMaxAge(String cacheControl) {
322 final int maxAgeIndex = cacheControl.indexOf("max-age");
323 if(maxAgeIndex == -1) {
324 return -1;
325 }
326 final int eq = cacheControl.indexOf('=', maxAgeIndex + 7);
327 if(eq == -1) {
328 return -1;
329 }
330 final int comma = cacheControl.indexOf(',', eq + 1);
331 final String strAge;
332 if(comma == -1) {
333 strAge = cacheControl.substring(eq + 1);
334 }
335 else {
336 strAge = cacheControl.substring(eq + 1, comma);
337 }
338 try {
339 return Integer.parseInt(strAge);
340 }
341 catch(NumberFormatException e) {
342 return -1;
343 }
344 }
345
346 private String getEntityTags(URLConnection urlConnection) {
347 final List<String> etags = urlConnection.getHeaderFields().get("ETag");
348 if(etags == null || etags.isEmpty()) {
349 return null;
350 }
351 final StringBuilder b = new StringBuilder();
352 final Iterator<String> it = etags.iterator();
353 b.append(it.next());
354 while(it.hasNext()) {
355 b.append(", ").append(it.next());
356 }
357 return b.toString();
358 }
359
360 boolean appliesTo(URI uri) {
361 return this.uri.equals(uri);
362 }
363
364 void applyConditionals(URLConnection urlConnection) {
365 if(lastModified != 0L) {
366 urlConnection.setIfModifiedSince(lastModified);
367 }
368 if(entityTags != null && entityTags.length() > 0) {
369 urlConnection.addRequestProperty("If-None-Match", entityTags);
370 }
371 }
372
373 boolean entityNeedsRevalidation() {
374 return System.currentTimeMillis() > expiry;
375 }
376 }
377 }