KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > webwork > components > Include


1 package com.opensymphony.webwork.components;
2
3 import com.opensymphony.webwork.config.Configuration;
4 import com.opensymphony.webwork.util.FastByteArrayOutputStream;
5 import com.opensymphony.xwork.util.OgnlValueStack;
6 import org.apache.commons.logging.LogFactory;
7
8 import javax.servlet.RequestDispatcher JavaDoc;
9 import javax.servlet.ServletException JavaDoc;
10 import javax.servlet.ServletOutputStream JavaDoc;
11 import javax.servlet.ServletRequest JavaDoc;
12 import javax.servlet.http.HttpServletRequest JavaDoc;
13 import javax.servlet.http.HttpServletResponse JavaDoc;
14 import javax.servlet.http.HttpServletResponseWrapper JavaDoc;
15 import java.io.IOException JavaDoc;
16 import java.io.OutputStreamWriter JavaDoc;
17 import java.io.PrintWriter JavaDoc;
18 import java.io.Writer JavaDoc;
19 import java.net.URLEncoder JavaDoc;
20 import java.util.*;
21
22 /**
23  * Include a servlet's output (result of servlet or a JSP page).
24  *
25  * @author Rickard Oberg (rickard@dreambean.com)
26  * @author <a HREF="mailto:scott@atlassian.com">Scott Farquhar</a>
27  */

28 public class Include extends Component {
29     private static String JavaDoc encoding;
30     private static boolean encodingDefined = true;
31
32     protected String JavaDoc value;
33     private HttpServletRequest JavaDoc req;
34     private HttpServletResponse JavaDoc res;
35
36     public Include(OgnlValueStack stack, HttpServletRequest JavaDoc req, HttpServletResponse JavaDoc res) {
37         super(stack);
38         this.req = req;
39         this.res = res;
40     }
41
42     public void end(Writer JavaDoc writer) {
43         String JavaDoc page = findString(value);
44         StringBuffer JavaDoc urlBuf = new StringBuffer JavaDoc();
45
46         // Add URL
47
urlBuf.append(page);
48
49         // Add request parameters
50
if (parameters.size() > 0) {
51             urlBuf.append('?');
52
53             String JavaDoc concat = "";
54
55             // Set parameters
56
Iterator iter = parameters.entrySet().iterator();
57
58             while (iter.hasNext()) {
59                 Map.Entry entry = (Map.Entry) iter.next();
60                 Object JavaDoc name = entry.getKey();
61                 List values = (List) entry.getValue();
62
63                 for (int i = 0; i < values.size(); i++) {
64                     urlBuf.append(concat);
65                     urlBuf.append(name);
66                     urlBuf.append('=');
67
68                     try {
69                         urlBuf.append(URLEncoder.encode(values.get(i).toString()));
70                     } catch (Exception JavaDoc e) {
71                     }
72
73                     concat = "&";
74                 }
75             }
76         }
77
78         String JavaDoc result = urlBuf.toString();
79
80         // Include
81
try {
82             include(result, writer, req, res);
83         } catch (Exception JavaDoc e) {
84             LogFactory.getLog(getClass()).warn("Exception thrown during include of " + result, e);
85         }
86     }
87
88     public void setValue(String JavaDoc value) {
89         this.value = value;
90     }
91
92     public static String JavaDoc getContextRelativePath(ServletRequest JavaDoc request, String JavaDoc relativePath) {
93         String JavaDoc returnValue;
94
95         if (relativePath.startsWith("/")) {
96             returnValue = relativePath;
97         } else if (!(request instanceof HttpServletRequest JavaDoc)) {
98             returnValue = relativePath;
99         } else {
100             HttpServletRequest JavaDoc hrequest = (HttpServletRequest JavaDoc) request;
101             String JavaDoc uri = (String JavaDoc) request.getAttribute("javax.servlet.include.servlet_path");
102
103             if (uri == null) {
104                 uri = hrequest.getServletPath();
105             }
106
107             returnValue = uri.substring(0, uri.lastIndexOf('/')) + '/' + relativePath;
108         }
109
110         // .. is illegal in an absolute path according to the Servlet Spec and will cause
111
// known problems on Orion application servers.
112
if (returnValue.indexOf("..") != -1) {
113             Stack stack = new Stack();
114             StringTokenizer pathParts = new StringTokenizer(returnValue.replace('\\', '/'), "/");
115
116             while (pathParts.hasMoreTokens()) {
117                 String JavaDoc part = pathParts.nextToken();
118
119                 if (!part.equals(".")) {
120                     if (part.equals("..")) {
121                         stack.pop();
122                     } else {
123                         stack.push(part);
124                     }
125                 }
126             }
127
128             StringBuffer JavaDoc flatPathBuffer = new StringBuffer JavaDoc();
129
130             for (int i = 0; i < stack.size(); i++) {
131                 flatPathBuffer.append("/" + stack.elementAt(i));
132             }
133
134             returnValue = flatPathBuffer.toString();
135         }
136
137         return returnValue;
138     }
139
140     public static void include(String JavaDoc aResult, Writer JavaDoc writer, ServletRequest JavaDoc request, HttpServletResponse JavaDoc response) throws ServletException JavaDoc, IOException JavaDoc {
141         String JavaDoc resourcePath = getContextRelativePath(request, aResult);
142         RequestDispatcher JavaDoc rd = request.getRequestDispatcher(resourcePath);
143
144         if (rd == null) {
145             throw new ServletException JavaDoc("Not a valid resource path:" + resourcePath);
146         }
147
148         PageResponse pageResponse = new PageResponse(response);
149
150         // Include the resource
151
rd.include((HttpServletRequest JavaDoc) request, pageResponse);
152
153         //write the response back to the JspWriter, using the correct encoding.
154
String JavaDoc encoding = getEncoding();
155
156         if (encoding != null) {
157             //use the encoding specified in the property file
158
pageResponse.getContent().writeTo(writer, encoding);
159         } else {
160             //use the platform specific encoding
161
pageResponse.getContent().writeTo(writer, null);
162         }
163     }
164
165     /**
166      * Get the encoding specified by the property 'webwork.i18n.encoding' in webwork.properties,
167      * or return the default platform encoding if not specified.
168      * <p/>
169      * Note that if the property is not initially defined, this will return the system default,
170      * even if the property is later defined. This is mainly for performance reasons. Undefined
171      * properties throw exceptions, which are a costly operation.
172      * <p/>
173      * If the property is initially defined, it is read every time, until is is undefined, and then
174      * the system default is used.
175      * <p/>
176      * Why not cache it completely? Some applications will wish to be able to dynamically set the
177      * encoding at runtime.
178      *
179      * @return The encoding to be used.
180      */

181     private static String JavaDoc getEncoding() {
182         if (encodingDefined) {
183             try {
184                 encoding = Configuration.getString("webwork.i18n.encoding");
185             } catch (IllegalArgumentException JavaDoc e) {
186                 encoding = System.getProperty("file.encoding");
187                 encodingDefined = false;
188             }
189         }
190
191         return encoding;
192     }
193
194
195     /**
196      * Implementation of ServletOutputStream that stores all data written
197      * to it in a temporary buffer accessible from {@link #getBuffer()} .
198      *
199      * @author <a HREF="joe@truemesh.com">Joe Walnes</a>
200      * @author <a HREF="mailto:scott@atlassian.com">Scott Farquhar</a>
201      */

202     static final class PageOutputStream extends ServletOutputStream JavaDoc {
203         //~ Instance fields ////////////////////////////////////////////////////////
204

205         private FastByteArrayOutputStream buffer;
206
207         //~ Constructors ///////////////////////////////////////////////////////////
208

209         public PageOutputStream() {
210             buffer = new FastByteArrayOutputStream();
211         }
212
213         //~ Methods ////////////////////////////////////////////////////////////////
214

215         /**
216          * Return all data that has been written to this OutputStream.
217          */

218         public FastByteArrayOutputStream getBuffer() throws IOException JavaDoc {
219             flush();
220
221             return buffer;
222         }
223
224         public void close() throws IOException JavaDoc {
225             buffer.close();
226         }
227
228         public void flush() throws IOException JavaDoc {
229             buffer.flush();
230         }
231
232         public void write(byte[] b, int o, int l) throws IOException JavaDoc {
233             buffer.write(b, o, l);
234         }
235
236         public void write(int i) throws IOException JavaDoc {
237             buffer.write(i);
238         }
239
240         public void write(byte[] b) throws IOException JavaDoc {
241             buffer.write(b);
242         }
243     }
244
245
246     /**
247      * Simple wrapper to HTTPServletResponse that will allow getWriter()
248      * and getResponse() to be called as many times as needed without
249      * causing conflicts.
250      * <p/>
251      * The underlying outputStream is a wrapper around
252      * {@link PageOutputStream} which will store
253      * the written content to a buffer.
254      * <p/>
255      * This buffer can later be retrieved by calling {@link #getContent}.
256      *
257      * @author <a HREF="mailto:joe@truemesh.com">Joe Walnes</a>
258      * @author <a HREF="mailto:scott@atlassian.com">Scott Farquhar</a>
259      */

260     static final class PageResponse extends HttpServletResponseWrapper JavaDoc {
261         //~ Instance fields ////////////////////////////////////////////////////////
262

263         protected PrintWriter JavaDoc pagePrintWriter;
264         protected ServletOutputStream JavaDoc outputStream;
265         private PageOutputStream pageOutputStream = null;
266
267         //~ Constructors ///////////////////////////////////////////////////////////
268

269         /**
270          * Create PageResponse wrapped around an existing HttpServletResponse.
271          */

272         public PageResponse(HttpServletResponse JavaDoc response) {
273             super(response);
274         }
275
276         //~ Methods ////////////////////////////////////////////////////////////////
277

278         /**
279          * Return the content buffered inside the {@link PageOutputStream}.
280          *
281          * @return
282          * @throws IOException
283          */

284         public FastByteArrayOutputStream getContent() throws IOException JavaDoc {
285             //if we are using a writer, we need to flush the
286
//data to the underlying outputstream.
287
//most containers do this - but it seems Jetty 4.0.5 doesn't
288
if (pagePrintWriter != null) {
289                 pagePrintWriter.flush();
290             }
291
292             return ((PageOutputStream) getOutputStream()).getBuffer();
293         }
294
295         /**
296          * Return instance of {@link PageOutputStream}
297          * allowing all data written to stream to be stored in temporary buffer.
298          */

299         public ServletOutputStream JavaDoc getOutputStream() throws IOException JavaDoc {
300             if (pageOutputStream == null) {
301                 pageOutputStream = new PageOutputStream();
302             }
303
304             return pageOutputStream;
305         }
306
307         /**
308          * Return PrintWriter wrapper around PageOutputStream.
309          */

310         public PrintWriter JavaDoc getWriter() throws IOException JavaDoc {
311             if (pagePrintWriter == null) {
312                 pagePrintWriter = new PrintWriter JavaDoc(new OutputStreamWriter JavaDoc(getOutputStream(), getCharacterEncoding()));
313             }
314
315             return pagePrintWriter;
316         }
317     }
318 }
319
Popular Tags