01: // Copyright 2006, 2007 The Apache Software Foundation
02: //
03: // Licensed under the Apache License, Version 2.0 (the "License");
04: // you may not use this file except in compliance with the License.
05: // You may obtain a copy of the License at
06: //
07: // http://www.apache.org/licenses/LICENSE-2.0
08: //
09: // Unless required by applicable law or agreed to in writing, software
10: // distributed under the License is distributed on an "AS IS" BASIS,
11: // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12: // See the License for the specific language governing permissions and
13: // limitations under the License.
14:
15: package org.apache.tapestry.internal.services;
16:
17: import java.io.BufferedInputStream;
18: import java.io.IOException;
19: import java.io.InputStream;
20: import java.net.URL;
21: import java.security.MessageDigest;
22:
23: import org.apache.commons.codec.binary.Hex;
24: import org.apache.tapestry.internal.TapestryInternalUtils;
25: import org.apache.tapestry.services.ResourceDigestGenerator;
26:
27: /**
28: * Implementation of {@link ResourceDigestGenerator} that generates MD5 digests.
29: */
30: public class ResourceDigestGeneratorImpl implements
31: ResourceDigestGenerator {
32: private static final int BUFFER_SIZE = 5000;
33:
34: public String generateDigest(URL url) {
35: InputStream stream = null;
36:
37: try {
38: MessageDigest digest = MessageDigest.getInstance("MD5");
39:
40: stream = new BufferedInputStream(url.openStream());
41:
42: digestStream(digest, stream);
43:
44: stream.close();
45: stream = null;
46:
47: byte[] bytes = digest.digest();
48: char[] encoded = Hex.encodeHex(bytes);
49:
50: return new String(encoded);
51: } catch (Exception ex) {
52: throw new RuntimeException(ex);
53: } finally {
54: TapestryInternalUtils.close(stream);
55: }
56: }
57:
58: private void digestStream(MessageDigest digest, InputStream stream)
59: throws IOException {
60: byte[] buffer = new byte[BUFFER_SIZE];
61:
62: while (true) {
63: int length = stream.read(buffer);
64:
65: if (length < 0)
66: return;
67:
68: digest.update(buffer, 0, length);
69: }
70: }
71:
72: /** Current implementation: any path that ends with ".class", but this will expand in the future. */
73: public boolean requiresDigest(String path) {
74: return path.endsWith(".class");
75: }
76:
77: }
|