KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > taglibs > standard > tag > common > core > Util


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

16
17 package org.apache.taglibs.standard.tag.common.core;
18
19 import java.io.ByteArrayOutputStream JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.io.OutputStreamWriter JavaDoc;
22 import java.text.DateFormat JavaDoc;
23 import java.util.Enumeration JavaDoc;
24
25 import javax.servlet.http.HttpServletRequest JavaDoc;
26 import javax.servlet.jsp.JspException JavaDoc;
27 import javax.servlet.jsp.PageContext JavaDoc;
28
29 import org.apache.taglibs.standard.resources.Resources;
30
31 /**
32  * <p>Utilities in support of tag-handler classes.</p>
33  *
34  * @author Jan Luehe
35  */

36 public class Util {
37
38     private static final String JavaDoc REQUEST = "request";
39     private static final String JavaDoc SESSION = "session";
40     private static final String JavaDoc APPLICATION = "application";
41     private static final String JavaDoc DEFAULT = "default";
42     private static final String JavaDoc SHORT = "short";
43     private static final String JavaDoc MEDIUM = "medium";
44     private static final String JavaDoc LONG = "long";
45     private static final String JavaDoc FULL = "full";
46
47     public static final int HIGHEST_SPECIAL = '>';
48     public static char[][] specialCharactersRepresentation = new char[HIGHEST_SPECIAL + 1][];
49     static {
50         specialCharactersRepresentation['&'] = "&amp;".toCharArray();
51         specialCharactersRepresentation['<'] = "&lt;".toCharArray();
52         specialCharactersRepresentation['>'] = "&gt;".toCharArray();
53         specialCharactersRepresentation['"'] = "&#034;".toCharArray();
54         specialCharactersRepresentation['\''] = "&#039;".toCharArray();
55     }
56
57     /*
58      * Converts the given string description of a scope to the corresponding
59      * PageContext constant.
60      *
61      * The validity of the given scope has already been checked by the
62      * appropriate TLV.
63      *
64      * @param scope String description of scope
65      *
66      * @return PageContext constant corresponding to given scope description
67      */

68     public static int getScope(String JavaDoc scope) {
69     int ret = PageContext.PAGE_SCOPE; // default
70

71     if (REQUEST.equalsIgnoreCase(scope))
72         ret = PageContext.REQUEST_SCOPE;
73     else if (SESSION.equalsIgnoreCase(scope))
74         ret = PageContext.SESSION_SCOPE;
75     else if (APPLICATION.equalsIgnoreCase(scope))
76         ret = PageContext.APPLICATION_SCOPE;
77
78     return ret;
79     }
80
81     /*
82      * Converts the given string description of a formatting style for
83      * dates and times to the corresponding java.util.DateFormat constant.
84      *
85      * @param style String description of formatting style for dates and times
86      * @param errCode Error code to throw if given style is invalid
87      *
88      * @return java.util.DateFormat constant corresponding to given style
89      *
90      * @throws JspException if the given style is invalid
91      */

92     public static int getStyle(String JavaDoc style, String JavaDoc errCode)
93                     throws JspException JavaDoc {
94     int ret = DateFormat.DEFAULT;
95
96     if (style != null) {
97         if (DEFAULT.equalsIgnoreCase(style)) {
98         ret = DateFormat.DEFAULT;
99         } else if (SHORT.equalsIgnoreCase(style)) {
100         ret = DateFormat.SHORT;
101         } else if (MEDIUM.equalsIgnoreCase(style)) {
102         ret = DateFormat.MEDIUM;
103         } else if (LONG.equalsIgnoreCase(style)) {
104         ret = DateFormat.LONG;
105         } else if (FULL.equalsIgnoreCase(style)) {
106         ret = DateFormat.FULL;
107         } else {
108         throw new JspException JavaDoc(Resources.getMessage(errCode, style));
109         }
110     }
111
112     return ret;
113     }
114     
115
116
117     /**
118      * Performs the following substring replacements
119      * (to facilitate output to XML/HTML pages):
120      *
121      * & -> &amp;
122      * < -> &lt;
123      * > -> &gt;
124      * " -> &#034;
125      * ' -> &#039;
126      *
127      * See also OutSupport.writeEscapedXml().
128      */

129     public static String JavaDoc escapeXml(String JavaDoc buffer) {
130         int start = 0;
131         int length = buffer.length();
132         char[] arrayBuffer = buffer.toCharArray();
133         StringBuffer JavaDoc escapedBuffer = null;
134
135         for (int i = 0; i < length; i++) {
136             char c = arrayBuffer[i];
137             if (c <= HIGHEST_SPECIAL) {
138                 char[] escaped = specialCharactersRepresentation[c];
139                 if (escaped != null) {
140                     // create StringBuffer to hold escaped xml string
141
if (start == 0) {
142                         escapedBuffer = new StringBuffer JavaDoc(length + 5);
143                     }
144                     // add unescaped portion
145
if (start < i) {
146                         escapedBuffer.append(arrayBuffer,start,i-start);
147                     }
148                     start = i + 1;
149                     // add escaped xml
150
escapedBuffer.append(escaped);
151                 }
152             }
153         }
154         // no xml escaping was necessary
155
if (start == 0) {
156             return buffer;
157         }
158         // add rest of unescaped portion
159
if (start < length) {
160             escapedBuffer.append(arrayBuffer,start,length-start);
161         }
162         return escapedBuffer.toString();
163     }
164
165     /**
166      * Get the value associated with a content-type attribute.
167      * Syntax defined in RFC 2045, section 5.1.
168      */

169     public static String JavaDoc getContentTypeAttribute(String JavaDoc input, String JavaDoc name) {
170     int begin;
171     int end;
172         int index = input.toUpperCase().indexOf(name.toUpperCase());
173         if (index == -1) return null;
174         index = index + name.length(); // positioned after the attribute name
175
index = input.indexOf('=', index); // positioned at the '='
176
if (index == -1) return null;
177         index += 1; // positioned after the '='
178
input = input.substring(index).trim();
179         
180         if (input.charAt(0) == '"') {
181             // attribute value is a quoted string
182
begin = 1;
183             end = input.indexOf('"', begin);
184             if (end == -1) return null;
185         } else {
186             begin = 0;
187             end = input.indexOf(';');
188             if (end == -1) end = input.indexOf(' ');
189             if (end == -1) end = input.length();
190         }
191         return input.substring(begin, end).trim();
192     }
193     
194     /**
195      * URL encodes a string, based on the supplied character encoding.
196      * This performs the same function as java.next.URLEncode.encode
197      * in J2SDK1.4, and should be removed if the only platform supported
198      * is 1.4 or higher.
199      * @param s The String to be URL encoded.
200      * @param enc The character encoding
201      * @return The URL encoded String
202      * [taken from jakarta-tomcat-jasper/jasper2
203      * org.apache.jasper.runtime.JspRuntimeLibrary.java]
204      */

205     public static String JavaDoc URLEncode(String JavaDoc s, String JavaDoc enc) {
206
207     if (s == null) {
208         return "null";
209     }
210
211     if (enc == null) {
212         enc = "UTF-8"; // Is this right?
213
}
214
215     StringBuffer JavaDoc out = new StringBuffer JavaDoc(s.length());
216     ByteArrayOutputStream JavaDoc buf = new ByteArrayOutputStream JavaDoc();
217     OutputStreamWriter JavaDoc writer = null;
218     try {
219         writer = new OutputStreamWriter JavaDoc(buf, enc);
220     } catch (java.io.UnsupportedEncodingException JavaDoc ex) {
221         // Use the default encoding?
222
writer = new OutputStreamWriter JavaDoc(buf);
223     }
224     
225     for (int i = 0; i < s.length(); i++) {
226         int c = s.charAt(i);
227         if (c == ' ') {
228         out.append('+');
229         } else if (isSafeChar(c)) {
230         out.append((char)c);
231         } else {
232         // convert to external encoding before hex conversion
233
try {
234             writer.write(c);
235             writer.flush();
236         } catch(IOException JavaDoc e) {
237             buf.reset();
238             continue;
239         }
240         byte[] ba = buf.toByteArray();
241         for (int j = 0; j < ba.length; j++) {
242             out.append('%');
243             // Converting each byte in the buffer
244
out.append(Character.forDigit((ba[j]>>4) & 0xf, 16));
245             out.append(Character.forDigit(ba[j] & 0xf, 16));
246         }
247         buf.reset();
248         }
249     }
250     return out.toString();
251     }
252
253     private static boolean isSafeChar(int c) {
254     if (c >= 'a' && c <= 'z') {
255         return true;
256     }
257     if (c >= 'A' && c <= 'Z') {
258         return true;
259     }
260     if (c >= '0' && c <= '9') {
261         return true;
262     }
263     if (c == '-' || c == '_' || c == '.' || c == '!' ||
264         c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') {
265         return true;
266     }
267     return false;
268     }
269     
270     /**
271      * HttpServletRequest.getLocales() returns the server's default locale
272      * if the request did not specify a preferred language.
273      * We do not want this behavior, because it prevents us from using
274      * the fallback locale.
275      * We therefore need to return an empty Enumeration if no preferred
276      * locale has been specified. This way, the logic for the fallback
277      * locale will be able to kick in.
278      */

279     public static Enumeration JavaDoc getRequestLocales(HttpServletRequest JavaDoc request) {
280         Enumeration JavaDoc values = request.getHeaders("accept-language");
281         if (values.hasMoreElements()) {
282             // At least one "accept-language". Simply return
283
// the enumeration returned by request.getLocales().
284
// System.out.println("At least one accept-language");
285
return request.getLocales();
286         } else {
287             // No header for "accept-language". Simply return
288
// the empty enumeration.
289
// System.out.println("No accept-language");
290
return values;
291         }
292     }
293 }
294
Popular Tags