1
2
3
4
5
6
7
8
9
10
11 package org.opensync.tools;
12
13 import java.io.*;
14 import java.util.*;
15 import javax.xml.transform.*;
16 import javax.xml.transform.stream.*;
17
18 /***
19 * A utility class that caches XSLT stylesheets in memory.
20 *
21 */
22 public class StylesheetCache {
23
24
25 private static Map cache = new HashMap();
26
27 /***
28 * Flush all cached stylesheets from memory, emptying the cache.
29 */
30 public static synchronized void flushAll() {
31 cache.clear();
32 }
33
34 /***
35 * Flush a specific cached stylesheet from memory.
36 *
37 * @param xsltFileName the file name of the stylesheet to remove.
38 */
39 public static synchronized void flush(String xsltFileName) {
40 cache.remove(xsltFileName);
41 }
42
43 /***
44 * Obtain a new Transformer instance for the specified XSLT file name.
45 * A new entry will be added to the cache if this is the first request
46 * for the specified file name.
47 *
48 * @param xsltFileName the file name of an XSLT stylesheet.
49 * @return a transformation context for the given stylesheet.
50 */
51 public static synchronized Transformer newTransformer(String xsltFileName)
52 throws TransformerConfigurationException, java.net.MalformedURLException {
53 File xsltFile = new File(xsltFileName);
54
55
56 long xslLastModified = xsltFile.lastModified();
57 MapEntry entry = (MapEntry) cache.get(xsltFileName);
58
59 if (entry != null) {
60
61
62 if (xslLastModified > entry.lastModified) {
63 entry = null;
64 }
65 }
66
67
68 if (entry == null) {
69 Source xslSource=null;
70 if(xsltFile.exists()){
71 xslSource = new StreamSource(xsltFile.toURL().toExternalForm());
72 }else{
73 xslSource = new StreamSource(xsltFileName);
74 }
75
76 TransformerFactory transFact = TransformerFactory.newInstance();
77 Templates templates = transFact.newTemplates(xslSource);
78
79 entry = new MapEntry(xslLastModified, templates);
80 cache.put(xsltFileName, entry);
81 }
82
83 return entry.templates.newTransformer();
84 }
85
86
87 private StylesheetCache() {
88 }
89
90 /***
91 * This class represents a value in the cache Map.
92 */
93 static class MapEntry {
94 long lastModified;
95 Templates templates;
96
97 MapEntry(long lastModified, Templates templates) {
98 this.lastModified = lastModified;
99 this.templates = templates;
100 }
101 }
102 }