KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jasper > tagplugins > jstl > Util


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. See the NOTICE file distributed with
4  * this work for additional information regarding copyright ownership.
5  * The ASF licenses this file to You under the Apache License, Version 2.0
6  * (the "License"); you may not use this file except in compliance with
7  * the License. You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17
18
19 package org.apache.jasper.tagplugins.jstl;
20
21 import java.io.ByteArrayOutputStream JavaDoc;
22 import java.io.IOException JavaDoc;
23 import java.io.PrintWriter JavaDoc;
24 import java.io.StringWriter JavaDoc;
25 import java.io.UnsupportedEncodingException JavaDoc;
26 import java.util.Locale JavaDoc;
27
28 import javax.servlet.ServletOutputStream JavaDoc;
29 import javax.servlet.http.HttpServletRequest JavaDoc;
30 import javax.servlet.http.HttpServletResponse JavaDoc;
31 import javax.servlet.http.HttpServletResponseWrapper JavaDoc;
32 import javax.servlet.jsp.JspException JavaDoc;
33 import javax.servlet.jsp.JspTagException JavaDoc;
34 import javax.servlet.jsp.PageContext JavaDoc;
35
36 /**
37  * Util contains some often used consts, static methods and embedded class
38  * to support the JSTL tag plugin.
39  */

40
41 public class Util {
42     
43     public static final String JavaDoc VALID_SCHEME_CHAR =
44         "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+.-";
45     
46     public static final String JavaDoc DEFAULT_ENCODING =
47         "ISO-8859-1";
48     
49     public static final int HIGHEST_SPECIAL = '>';
50     
51     public static char[][] specialCharactersRepresentation = new char[HIGHEST_SPECIAL + 1][];
52     
53     static {
54         specialCharactersRepresentation['&'] = "&".toCharArray();
55         specialCharactersRepresentation['<'] = "&lt;".toCharArray();
56         specialCharactersRepresentation['>'] = "&gt;".toCharArray();
57         specialCharactersRepresentation['"'] = "&#034;".toCharArray();
58         specialCharactersRepresentation['\''] = "&#039;".toCharArray();
59     }
60     
61     /**
62      * Converts the given string description of a scope to the corresponding
63      * PageContext constant.
64      *
65      * The validity of the given scope has already been checked by the
66      * appropriate TLV.
67      *
68      * @param scope String description of scope
69      *
70      * @return PageContext constant corresponding to given scope description
71      *
72      * taken from org.apache.taglibs.standard.tag.common.core.Util
73      */

74     public static int getScope(String JavaDoc scope){
75         int ret = PageContext.PAGE_SCOPE;
76         
77         if("request".equalsIgnoreCase(scope)){
78             ret = PageContext.REQUEST_SCOPE;
79         }else if("session".equalsIgnoreCase(scope)){
80             ret = PageContext.SESSION_SCOPE;
81         }else if("application".equalsIgnoreCase(scope)){
82             ret = PageContext.APPLICATION_SCOPE;
83         }
84         
85         return ret;
86     }
87     
88     /**
89      * Returns <tt>true</tt> if our current URL is absolute,
90      * <tt>false</tt> otherwise.
91      * taken from org.apache.taglibs.standard.tag.common.core.ImportSupport
92      */

93     public static boolean isAbsoluteUrl(String JavaDoc url){
94         if(url == null){
95             return false;
96         }
97         
98         int colonPos = url.indexOf(":");
99         if(colonPos == -1){
100             return false;
101         }
102         
103         for(int i=0;i<colonPos;i++){
104             if(VALID_SCHEME_CHAR.indexOf(url.charAt(i)) == -1){
105                 return false;
106             }
107         }
108         
109         return true;
110     }
111     
112     /**
113      * Get the value associated with a content-type attribute.
114      * Syntax defined in RFC 2045, section 5.1.
115      * taken from org.apache.taglibs.standard.tag.common.core.Util
116      */

117     public static String JavaDoc getContentTypeAttribute(String JavaDoc input, String JavaDoc name) {
118         int begin;
119         int end;
120         int index = input.toUpperCase().indexOf(name.toUpperCase());
121         if (index == -1) return null;
122         index = index + name.length(); // positioned after the attribute name
123
index = input.indexOf('=', index); // positioned at the '='
124
if (index == -1) return null;
125         index += 1; // positioned after the '='
126
input = input.substring(index).trim();
127         
128         if (input.charAt(0) == '"') {
129             // attribute value is a quoted string
130
begin = 1;
131             end = input.indexOf('"', begin);
132             if (end == -1) return null;
133         } else {
134             begin = 0;
135             end = input.indexOf(';');
136             if (end == -1) end = input.indexOf(' ');
137             if (end == -1) end = input.length();
138         }
139         return input.substring(begin, end).trim();
140     }
141     
142     /**
143      * Strips a servlet session ID from <tt>url</tt>. The session ID
144      * is encoded as a URL "path parameter" beginning with "jsessionid=".
145      * We thus remove anything we find between ";jsessionid=" (inclusive)
146      * and either EOS or a subsequent ';' (exclusive).
147      *
148      * taken from org.apache.taglibs.standard.tag.common.core.ImportSupport
149      */

150     public static String JavaDoc stripSession(String JavaDoc url) {
151         StringBuffer JavaDoc u = new StringBuffer JavaDoc(url);
152         int sessionStart;
153         while ((sessionStart = u.toString().indexOf(";jsessionid=")) != -1) {
154             int sessionEnd = u.toString().indexOf(";", sessionStart + 1);
155             if (sessionEnd == -1)
156                 sessionEnd = u.toString().indexOf("?", sessionStart + 1);
157             if (sessionEnd == -1) // still
158
sessionEnd = u.length();
159             u.delete(sessionStart, sessionEnd);
160         }
161         return u.toString();
162     }
163     
164     
165     /**
166      * Performs the following substring replacements
167      * (to facilitate output to XML/HTML pages):
168      *
169      * & -> &amp;
170      * < -> &lt;
171      * > -> &gt;
172      * " -> &#034;
173      * ' -> &#039;
174      *
175      * See also OutSupport.writeEscapedXml().
176      *
177      * taken from org.apache.taglibs.standard.tag.common.core.Util
178      */

179     public static String JavaDoc escapeXml(String JavaDoc buffer) {
180         int start = 0;
181         int length = buffer.length();
182         char[] arrayBuffer = buffer.toCharArray();
183         StringBuffer JavaDoc escapedBuffer = null;
184         
185         for (int i = 0; i < length; i++) {
186             char c = arrayBuffer[i];
187             if (c <= HIGHEST_SPECIAL) {
188                 char[] escaped = specialCharactersRepresentation[c];
189                 if (escaped != null) {
190                     // create StringBuffer to hold escaped xml string
191
if (start == 0) {
192                         escapedBuffer = new StringBuffer JavaDoc(length + 5);
193                     }
194                     // add unescaped portion
195
if (start < i) {
196                         escapedBuffer.append(arrayBuffer,start,i-start);
197                     }
198                     start = i + 1;
199                     // add escaped xml
200
escapedBuffer.append(escaped);
201                 }
202             }
203         }
204         // no xml escaping was necessary
205
if (start == 0) {
206             return buffer;
207         }
208         // add rest of unescaped portion
209
if (start < length) {
210             escapedBuffer.append(arrayBuffer,start,length-start);
211         }
212         return escapedBuffer.toString();
213     }
214     
215     /** Utility methods
216      * taken from org.apache.taglibs.standard.tag.common.core.UrlSupport
217      */

218     public static String JavaDoc resolveUrl(
219             String JavaDoc url, String JavaDoc context, PageContext JavaDoc pageContext)
220     throws JspException JavaDoc {
221         // don't touch absolute URLs
222
if (isAbsoluteUrl(url))
223             return url;
224         
225         // normalize relative URLs against a context root
226
HttpServletRequest JavaDoc request =
227             (HttpServletRequest JavaDoc) pageContext.getRequest();
228         if (context == null) {
229             if (url.startsWith("/"))
230                 return (request.getContextPath() + url);
231             else
232                 return url;
233         } else {
234             if (!context.startsWith("/") || !url.startsWith("/")) {
235                 throw new JspTagException JavaDoc(
236                 "In URL tags, when the \"context\" attribute is specified, values of both \"context\" and \"url\" must start with \"/\".");
237             }
238             if (context.equals("/")) {
239                 // Don't produce string starting with '//', many
240
// browsers interpret this as host name, not as
241
// path on same host.
242
return url;
243             } else {
244                 return (context + url);
245             }
246         }
247     }
248     
249     /** Wraps responses to allow us to retrieve results as Strings.
250      * mainly taken from org.apache.taglibs.standard.tag.common.core.importSupport
251      */

252     public static class ImportResponseWrapper extends HttpServletResponseWrapper JavaDoc{
253         
254         private StringWriter JavaDoc sw = new StringWriter JavaDoc();
255         private ByteArrayOutputStream JavaDoc bos = new ByteArrayOutputStream JavaDoc();
256         private ServletOutputStream JavaDoc sos = new ServletOutputStream JavaDoc() {
257             public void write(int b) throws IOException JavaDoc {
258                 bos.write(b);
259             }
260         };
261         private boolean isWriterUsed;
262         private boolean isStreamUsed;
263         private int status = 200;
264         private String JavaDoc charEncoding;
265         
266         public ImportResponseWrapper(HttpServletResponse JavaDoc arg0) {
267             super(arg0);
268             // TODO Auto-generated constructor stub
269
}
270         
271         public PrintWriter JavaDoc getWriter() {
272             if (isStreamUsed)
273                 throw new IllegalStateException JavaDoc("Unexpected internal error during &lt;import&gt: " +
274                 "Target servlet called getWriter(), then getOutputStream()");
275             isWriterUsed = true;
276             return new PrintWriter JavaDoc(sw);
277         }
278         
279         public ServletOutputStream JavaDoc getOutputStream() {
280             if (isWriterUsed)
281                 throw new IllegalStateException JavaDoc("Unexpected internal error during &lt;import&gt: " +
282                 "Target servlet called getOutputStream(), then getWriter()");
283             isStreamUsed = true;
284             return sos;
285         }
286         
287         /** Has no effect. */
288         public void setContentType(String JavaDoc x) {
289             // ignore
290
}
291         
292         /** Has no effect. */
293         public void setLocale(Locale JavaDoc x) {
294             // ignore
295
}
296         
297         public void setStatus(int status) {
298             this.status = status;
299         }
300         
301         public int getStatus() {
302             return status;
303         }
304         
305         public String JavaDoc getCharEncoding(){
306             return this.charEncoding;
307         }
308         
309         public void setCharEncoding(String JavaDoc ce){
310             this.charEncoding = ce;
311         }
312         
313         public String JavaDoc getString() throws UnsupportedEncodingException JavaDoc {
314             if (isWriterUsed)
315                 return sw.toString();
316             else if (isStreamUsed) {
317                 if (this.charEncoding != null && !this.charEncoding.equals(""))
318                     return bos.toString(charEncoding);
319                 else
320                     return bos.toString("ISO-8859-1");
321             } else
322                 return ""; // target didn't write anything
323
}
324     }
325     
326 }
327
Popular Tags