KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > jstl > el > ImportTag


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  * Free SoftwareFoundation, Inc.
23  * 59 Temple Place, Suite 330
24  * Boston, MA 02111-1307 USA
25  *
26  * @author Scott Ferguson
27  */

28
29 package com.caucho.jstl.el;
30
31 import com.caucho.el.Expr;
32 import com.caucho.jsp.BodyContentImpl;
33 import com.caucho.jsp.PageContextImpl;
34 import com.caucho.jstl.NameValueTag;
35 import com.caucho.server.connection.CauchoResponse;
36 import com.caucho.util.CharBuffer;
37 import com.caucho.util.L10N;
38 import com.caucho.vfs.FlushBuffer;
39 import com.caucho.vfs.ReadStream;
40 import com.caucho.vfs.Vfs;
41
42 import javax.el.ELContext;
43 import javax.el.ELException;
44 import javax.servlet.RequestDispatcher JavaDoc;
45 import javax.servlet.ServletContext JavaDoc;
46 import javax.servlet.ServletException JavaDoc;
47 import javax.servlet.ServletRequest JavaDoc;
48 import javax.servlet.jsp.JspException JavaDoc;
49 import javax.servlet.jsp.JspTagException JavaDoc;
50 import javax.servlet.jsp.JspWriter JavaDoc;
51 import javax.servlet.jsp.tagext.BodyTagSupport JavaDoc;
52 import java.io.FileNotFoundException JavaDoc;
53 import java.io.IOException JavaDoc;
54 import java.io.InputStream JavaDoc;
55 import java.io.Reader JavaDoc;
56 import java.net.HttpURLConnection JavaDoc;
57 import java.net.URL JavaDoc;
58 import java.net.URLConnection JavaDoc;
59
60 public class ImportTag extends BodyTagSupport JavaDoc implements NameValueTag {
61   private static L10N L = new L10N(ImportTag.class);
62   
63   private Expr _urlExpr;
64   private Expr _contextExpr;
65
66   private CharBuffer _query = new CharBuffer();
67
68   private Expr _charEncodingExpr;
69
70   private String JavaDoc _var;
71   private String JavaDoc _scope;
72   
73   private String JavaDoc _varReader;
74
75   private Reader JavaDoc _reader;
76
77   /**
78    * Sets the URL to be imported.
79    */

80   public void setURL(Expr url)
81   {
82     _urlExpr = url;
83   }
84   
85   /**
86    * Sets the external context for the import.
87    */

88   public void setContext(Expr context)
89   {
90     _contextExpr = context;
91   }
92
93   /**
94    * Adds a parameter.
95    */

96   public void addParam(String JavaDoc name, String JavaDoc value)
97   {
98     if (name == null)
99       return;
100
101     if (value == null)
102       value = "";
103     
104     if (_query.length() != 0)
105       _query.append('&');
106
107     _query.append(name);
108     _query.append('=');
109     int len = value.length();
110     for (int i = 0; i < len; i++) {
111       char ch = value.charAt(i);
112
113       switch (ch) {
114       case '&':
115     _query.append("%26");
116     break;
117     
118       case '%':
119     _query.append("%25");
120     break;
121     
122       case '+':
123     _query.append("%2b");
124     break;
125     
126       case '=':
127     _query.append("%3d");
128     break;
129     
130       default:
131     _query.append(ch);
132     break;
133       }
134     }
135   }
136   
137   /**
138    * Sets the external character encoding for the import.
139    */

140   public void setCharEncoding(Expr charEncoding)
141   {
142     _charEncodingExpr = charEncoding;
143   }
144
145   /**
146    * Sets the variable for the import.
147    */

148   public void setVar(String JavaDoc var)
149   {
150     _var = var;
151   }
152   
153   /**
154    * Sets the scope for the result variable for the output.
155    */

156   public void setScope(String JavaDoc scope)
157   {
158     _scope = scope;
159   }
160   
161   /**
162    * Sets the variable for the import.
163    */

164   public void setVarReader(String JavaDoc varReader)
165   {
166     _varReader = varReader;
167   }
168
169   /**
170    * Process the tag.
171    */

172   public int doStartTag()
173     throws JspException JavaDoc
174   {
175     JspWriter JavaDoc jspWriter = null;
176
177     _query.clear();
178
179     PageContextImpl pageContext = (PageContextImpl) this.pageContext;
180     
181     try {
182       if (_varReader != null) {
183         jspWriter = pageContext.pushBody();
184         
185         handleBody();
186
187         BodyContentImpl body = (BodyContentImpl) pageContext.getOut();
188
189         _reader = body.getReader();
190
191         pageContext.setAttribute(_varReader, _reader);
192
193         return EVAL_BODY_INCLUDE;
194       }
195       else
196         return EVAL_BODY_BUFFERED;
197     } catch (JspException JavaDoc e) {
198       throw e;
199     } catch (Exception JavaDoc e) {
200       throw new JspException JavaDoc(e);
201     } finally {
202       if (jspWriter != null)
203         pageContext.popBody();
204     }
205   }
206   
207   /**
208    * Process the end tag
209    */

210   public int doEndTag()
211     throws JspException JavaDoc
212   {
213     if (_varReader == null) {
214       try {
215     JspWriter JavaDoc jspWriter = pageContext.pushBody();
216           
217     handleBody();
218
219     BodyContentImpl body = (BodyContentImpl) pageContext.getOut();
220
221     if (_var != null) {
222       String JavaDoc value = body.getString();
223
224       pageContext.popBody();
225
226       CoreSetTag.setValue(pageContext, _var, _scope, value);
227         }
228     else {
229       body.writeOut(body.getEnclosingWriter());
230       
231       pageContext.popBody();
232     }
233       } catch (JspException JavaDoc e) {
234         throw e;
235       } catch (Exception JavaDoc e) {
236         throw new JspException JavaDoc(e);
237       }
238     }
239     
240     return EVAL_PAGE;
241   }
242
243   private void handleBody()
244     throws JspException JavaDoc, ServletException JavaDoc, IOException JavaDoc, ELException
245   {
246     PageContextImpl pageContext = (PageContextImpl) this.pageContext;
247     ELContext env = pageContext.getELContext();
248     
249     String JavaDoc url = _urlExpr.evalString(env);
250
251     if (url == null || url.equals(""))
252       throw new JspTagException JavaDoc(L.l("URL may not be null for `{0}'",
253                     _urlExpr));
254
255     if (_query == null || _query.getLength() == 0) {
256     }
257     else if (url.indexOf('?') > 0)
258       url = url + '&' + _query;
259     else
260       url = url + '?' + _query;
261
262     JspWriter JavaDoc out = pageContext.getOut();
263     if (out instanceof FlushBuffer)
264       ((FlushBuffer) out).flushBuffer();
265     else
266       out.flush();
267
268     if (_contextExpr != null) {
269       String JavaDoc context = _contextExpr.evalString(env);
270
271       if (! url.startsWith("/"))
272     throw new JspException JavaDoc(L.l("URL `{0}' must start with `/' with context `{0}'", url, context));
273         
274       if (context != null && context.startsWith("/")) {
275     ServletContext JavaDoc app = pageContext.getServletContext().getContext(context);
276
277     try {
278       RequestDispatcher JavaDoc disp = app.getRequestDispatcher(url);
279
280       if (disp == null)
281         throw new JspException JavaDoc(L.l("URL `{0}' does not map to any servlet",
282                        url));
283       
284       CauchoResponse response = (CauchoResponse) pageContext.getResponse();
285       response.getResponseStream().setEncoding(null);
286
287       disp.include(pageContext.getRequest(), response);
288     } catch (FileNotFoundException JavaDoc e) {
289       throw new JspException JavaDoc(L.l("`{0}' is an unknown file or servlet.",
290                      url));
291     }
292       }
293       else
294     handleExternalBody(context + url);
295       
296       return;
297     }
298
299     int colon = url.indexOf(':');
300     int slash = url.indexOf('/');
301     if (slash == 0 || colon < 0 || slash < 0 || slash < colon) {
302       ServletRequest JavaDoc request = pageContext.getRequest();
303
304       try {
305     RequestDispatcher JavaDoc disp = request.getRequestDispatcher(url);
306
307     if (disp == null)
308       throw new JspException JavaDoc(L.l("URL `{0}' does not map to any servlet",
309                      url));
310       
311     CauchoResponse response = (CauchoResponse) pageContext.getResponse();
312     response.getResponseStream().setEncoding(null);
313
314     disp.include(pageContext.getRequest(), response);
315       } catch (FileNotFoundException JavaDoc e) {
316     throw new JspException JavaDoc(L.l("URL `{0}' is an unknown file or servlet.",
317                    url));
318       }
319     }
320     else
321       handleExternalBody(url);
322   }
323
324   private void handleExternalBody(String JavaDoc url)
325     throws JspException JavaDoc, ServletException JavaDoc, IOException JavaDoc, ELException
326   {
327     PageContextImpl pageContext = (PageContextImpl) this.pageContext;
328     ELContext env = pageContext.getELContext();
329     
330     URL JavaDoc netURL = new URL JavaDoc(url);
331
332     URLConnection JavaDoc conn = netURL.openConnection();
333
334     if (conn instanceof HttpURLConnection JavaDoc)
335       ((HttpURLConnection JavaDoc) conn).setFollowRedirects(true);
336
337     InputStream JavaDoc is = conn.getInputStream();
338     try {
339       ReadStream in = Vfs.openRead(is);
340       String JavaDoc encoding = conn.getContentEncoding();
341       String JavaDoc contentType = conn.getContentType();
342
343       if (_charEncodingExpr != null) {
344         encoding = _charEncodingExpr.evalString(env);
345         if (encoding != null && ! encoding.equals(""))
346           in.setEncoding(encoding);
347       }
348       else if (encoding != null)
349         in.setEncoding(encoding);
350       else if (contentType != null) {
351         int p = contentType.indexOf("charset=");
352         if (p > 0) {
353           CharBuffer cb = new CharBuffer();
354           for (int i = p + 8; i < contentType.length(); i++) {
355             int ch = contentType.charAt(i);
356             if (ch == '"' || ch == '\'') {
357             }
358             else if (ch >= 'a' && ch <= 'z')
359               cb.append((char) ch);
360             else if (ch >= 'A' && ch <= 'Z')
361               cb.append((char) ch);
362             else if (ch >= '0' && ch <= '9')
363               cb.append((char) ch);
364             else if (ch == '-' || ch == '_')
365               cb.append((char) ch);
366             else
367               break;
368           }
369           encoding = cb.toString();
370
371           in.setEncoding(encoding);
372         }
373       }
374       
375       JspWriter JavaDoc out = pageContext.getOut();
376
377       int ch;
378       while ((ch = in.readChar()) >= 0)
379         out.print((char) ch);
380     } finally {
381       is.close();
382     }
383   }
384 }
385
Popular Tags