KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > webwork > views > xslt > XSLTResult


1 /*
2  * Copyright (c) 2002-2003 by OpenSymphony
3  * All rights reserved.
4  */

5 package com.opensymphony.webwork.views.xslt;
6
7 import com.opensymphony.webwork.ServletActionContext;
8 import com.opensymphony.webwork.config.Configuration;
9 import com.opensymphony.xwork.ActionContext;
10 import com.opensymphony.xwork.ActionInvocation;
11 import com.opensymphony.xwork.Result;
12 import com.opensymphony.xwork.util.OgnlValueStack;
13 import com.opensymphony.xwork.util.TextParseUtil;
14 import org.apache.commons.logging.Log;
15 import org.apache.commons.logging.LogFactory;
16
17 import javax.servlet.http.HttpServletResponse JavaDoc;
18 import javax.xml.transform.*;
19 import javax.xml.transform.dom.DOMSource JavaDoc;
20 import javax.xml.transform.stream.StreamResult JavaDoc;
21 import javax.xml.transform.stream.StreamSource JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.PrintWriter JavaDoc;
24 import java.io.Writer JavaDoc;
25 import java.net.URL JavaDoc;
26 import java.util.HashMap JavaDoc;
27 import java.util.Map JavaDoc;
28
29
30 /**
31  * @author <a HREF="mailto:meier@meisterbohne.de">Philipp Meier</a>
32  */

33 public class XSLTResult implements Result {
34     //~ Static fields/initializers /////////////////////////////////////////////
35

36     private static final Log log = LogFactory.getLog(XSLTResult.class);
37     public static final String JavaDoc DEFAULT_PARAM = "location";
38
39     //~ Instance fields ////////////////////////////////////////////////////////
40

41     protected boolean noCache = false;
42     private Map JavaDoc templatesCache;
43     private String JavaDoc location;
44     private boolean parse;
45
46     //~ Constructors ///////////////////////////////////////////////////////////
47

48     public XSLTResult() {
49         templatesCache = new HashMap JavaDoc();
50         noCache = Configuration.getString("webwork.xslt.nocache").trim().equalsIgnoreCase("true");
51     }
52
53     //~ Methods ////////////////////////////////////////////////////////////////
54

55     public void setLocation(String JavaDoc location) {
56         this.location = location;
57     }
58
59     public void setParse(boolean parse) {
60         this.parse = parse;
61     }
62
63     public void execute(ActionInvocation invocation) throws Exception JavaDoc {
64         long startTime = System.currentTimeMillis();
65
66         if (parse) {
67             OgnlValueStack stack = ActionContext.getContext().getValueStack();
68             location = TextParseUtil.translateVariables(location, stack);
69         }
70
71         try {
72             HttpServletResponse JavaDoc response = ServletActionContext.getResponse();
73
74             Writer JavaDoc writer = response.getWriter();
75
76             // Create a transformer for the stylesheet.
77
Templates templates = getTemplates(location);
78             Transformer transformer = templates.newTransformer();
79
80             String JavaDoc mimeType = templates.getOutputProperties().getProperty(OutputKeys.MEDIA_TYPE);
81
82             if (mimeType == null) {
83                 // guess (this is a servlet, so text/html might be the best guess)
84
mimeType = "text/html";
85             }
86
87             response.setContentType(mimeType);
88
89             Source JavaDoc xmlSource = getTraxSourceForStack(invocation.getAction());
90
91             // Transform the source XML to System.out.
92
PrintWriter JavaDoc out = response.getWriter();
93
94             transformer.transform(xmlSource, new StreamResult JavaDoc(out));
95
96             out.close(); // ...and flush...
97

98             if (log.isDebugEnabled()) {
99                 log.debug("Time:" + (System.currentTimeMillis() - startTime) + "ms");
100             }
101
102             writer.flush();
103         } catch (Exception JavaDoc e) {
104             log.error("Unable to render XSLT Template, '" + location + "'", e);
105             throw e;
106         }
107     }
108
109     private Templates getTemplates(String JavaDoc path) throws TransformerException, IOException JavaDoc {
110         String JavaDoc pathFromRequest = ServletActionContext.getRequest().getParameter("xslt.location");
111
112         if (pathFromRequest != null) {
113             path = pathFromRequest;
114         }
115
116         if (path == null) {
117             throw new TransformerException("Stylesheet path is null");
118         }
119
120         Templates templates = (Templates) templatesCache.get(path);
121
122         if (noCache || (templates == null)) {
123             synchronized (templatesCache) {
124                 URL JavaDoc resource = ServletActionContext.getServletContext().getResource(path);
125
126                 if (resource == null) {
127                     throw new TransformerException("Stylesheet " + path + " not found in resources.");
128                 }
129
130                 if (
131                 // This may result in the template being put into the cache multiple times
132
// if concurrent requests are made, but that's ok.
133
log.isDebugEnabled()) {
134                     // This may result in the template being put into the cache multiple times
135
// if concurrent requests are made, but that's ok.
136
log.debug("Preparing new XSLT stylesheet: " + path);
137                 }
138
139                 TransformerFactory factory = TransformerFactory.newInstance();
140                 log.trace("Uri-Resolver is: " + factory.getURIResolver());
141                 factory.setURIResolver(new ServletURIResolver(ServletActionContext.getServletContext()));
142                 log.trace("Uri-Resolver is: " + factory.getURIResolver());
143                 templates = factory.newTemplates(new StreamSource JavaDoc(resource.openStream()));
144                 templatesCache.put(path, templates);
145             }
146         }
147
148         return templates;
149     }
150
151     private Source JavaDoc getTraxSourceForStack(Object JavaDoc action) throws IllegalAccessException JavaDoc, InstantiationException JavaDoc {
152         return new DOMSource JavaDoc(new DOMAdapter().adapt(action));
153     }
154 }
155
Popular Tags