KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > cocoon > components > language > markup > xsp > XSPUtil


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 package org.apache.cocoon.components.language.markup.xsp;
17
18 import org.apache.avalon.framework.CascadingRuntimeException;
19 import org.apache.avalon.framework.component.Component;
20 import org.apache.avalon.framework.component.ComponentManager;
21 import org.apache.cocoon.components.source.SourceUtil;
22 import org.apache.cocoon.environment.Context;
23 import org.apache.cocoon.environment.ObjectModelHelper;
24 import org.apache.cocoon.environment.Session;
25 import org.apache.cocoon.environment.SourceResolver;
26 import org.apache.cocoon.util.NetUtils;
27 import org.apache.cocoon.xml.IncludeXMLConsumer;
28 import org.apache.commons.lang.StringEscapeUtils;
29 import org.apache.commons.lang.StringUtils;
30 import org.apache.excalibur.source.Source;
31 import org.apache.excalibur.xml.sax.SAXParser;
32 import org.xml.sax.ContentHandler JavaDoc;
33 import org.xml.sax.InputSource JavaDoc;
34
35 import java.io.File JavaDoc;
36 import java.io.FileInputStream JavaDoc;
37 import java.io.FileReader JavaDoc;
38 import java.io.IOException JavaDoc;
39 import java.io.InputStream JavaDoc;
40 import java.io.InputStreamReader JavaDoc;
41 import java.io.Reader JavaDoc;
42 import java.io.StringReader JavaDoc;
43 import java.io.FileNotFoundException JavaDoc;
44 import java.net.URLDecoder JavaDoc;
45 import java.net.URLEncoder JavaDoc;
46 import java.net.URL JavaDoc;
47 import java.text.SimpleDateFormat JavaDoc;
48 import java.util.Date JavaDoc;
49 import java.util.Map JavaDoc;
50
51 /**
52  * The XSP <code>Utility</code> object helper
53  * @author <a HREF="mailto:ricardo@apache.org">Ricardo Rocha</a>
54  * @author <a HREF="mailto:bloritsch@apache.org">Berin Loritsch</a>
55  * @version CVS $Id: XSPUtil.java 30932 2004-07-29 17:35:38Z vgritsenko $
56  */

57 public class XSPUtil {
58
59     public static String JavaDoc pathComponent(String JavaDoc filename) {
60         int i = filename.lastIndexOf(File.separator);
61         return (i >= 0) ? filename.substring(0, i) : filename;
62     }
63
64     public static String JavaDoc fileComponent(String JavaDoc filename) {
65         int i = filename.lastIndexOf(File.separator);
66         return (i >= 0) ? filename.substring(i + 1) : filename;
67     }
68
69     public static String JavaDoc baseName(String JavaDoc filename) {
70         return baseName(filename, ".");
71     }
72
73     public static String JavaDoc baseName(String JavaDoc filename, String JavaDoc suffix) {
74         int lastDot = filename.lastIndexOf(suffix);
75         if (lastDot >= 0) {
76             filename = filename.substring(0, lastDot);
77         }
78         return filename;
79     }
80
81     public static String JavaDoc normalizedBaseName(String JavaDoc filename) {
82         filename = baseName(filename);
83         return normalizedName(filename);
84     }
85
86     public static String JavaDoc normalizedName(String JavaDoc filename) {
87         String JavaDoc[] path = split(filename, File.separator);
88         int start = (path[0].length() == 0) ? 1 : 0;
89         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
90         for (int i = start; i < path.length; i++) {
91             if (i > start) {
92                 buffer.append(File.separator);
93             }
94             buffer.append('_');
95             char[] chars = path[i].toCharArray();
96             for (int j = 0; j < chars.length; j++) {
97                 if (isAlphaNumeric(chars[j])) {
98                     buffer.append(chars[j]);
99                 } else {
100                     buffer.append('_');
101                 }
102             }
103         }
104         return buffer.toString();
105     }
106
107     public static String JavaDoc relativeFilename(String JavaDoc filename, Map JavaDoc objectModel) throws IOException JavaDoc {
108         File JavaDoc file = new File JavaDoc(filename);
109         if (file.isAbsolute() && file.exists()) {
110             return filename;
111         }
112         Context context = ObjectModelHelper.getContext(objectModel);
113         URL JavaDoc resource = context.getResource(filename);
114         if (resource == null) {
115             throw new FileNotFoundException JavaDoc("The file " + filename + " does not exist!");
116         }
117         return NetUtils.getPath(resource.toExternalForm());
118     }
119
120     public static boolean isAlphaNumeric(char c) {
121         return c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
122     }
123
124     public static String JavaDoc[] split(String JavaDoc line) {
125         return StringUtils.split(line, " \t\r\f\n");
126     }
127
128     public static String JavaDoc[] split(String JavaDoc line, String JavaDoc delimiter) {
129         return StringUtils.split(line, delimiter);
130     }
131
132     public static String JavaDoc encodeMarkup(String JavaDoc string) {
133         return StringEscapeUtils.escapeXml(string);
134     }
135
136     public static String JavaDoc formEncode(String JavaDoc text) throws Exception JavaDoc {
137         return URLEncoder.encode(text);
138     }
139
140     // Shameless, ain't it?
141
public static String JavaDoc formDecode(String JavaDoc s) throws Exception JavaDoc {
142         return URLDecoder.decode(s);
143     }
144
145     /* Logicsheet Utility Methods */
146
147     // Date
148
public static String JavaDoc formatDate(Date JavaDoc date, String JavaDoc pattern) {
149         if (StringUtils.isEmpty(pattern)) {
150             pattern = "yyyy/MM/dd hh:mm:ss aa";
151         }
152         try {
153             return (new SimpleDateFormat JavaDoc(pattern)).format(date);
154         } catch (Exception JavaDoc e) {
155             return date.toString();
156         }
157     }
158
159     // Counters
160
private static volatile int count = 0;
161
162     public static int getCount() {
163         return ++count;
164     }
165
166     public static int getSessionCount(Session session) {
167         synchronized (session) {
168             Integer JavaDoc integer = (Integer JavaDoc)session.getAttribute("util.counter");
169             if (integer == null) {
170                 integer = new Integer JavaDoc(0);
171             }
172             int cnt = integer.intValue() + 1;
173             session.setAttribute("util.counter", new Integer JavaDoc(cnt));
174             return cnt;
175         }
176     }
177
178     public static Object JavaDoc getContextAttribute(Map JavaDoc objectModel, String JavaDoc name) {
179         Context context = ObjectModelHelper.getContext(objectModel);
180         return context.getAttribute(name);
181     }
182
183     // Inclusion
184
public static String JavaDoc getSourceContents(String JavaDoc url, SourceResolver resolver) throws IOException JavaDoc {
185         Source source = resolver.resolveURI(url);
186         try {
187             return getContents(source.getInputStream());
188         } finally {
189             resolver.release(source);
190         }
191     }
192
193     public static String JavaDoc getSourceContents(String JavaDoc uri, String JavaDoc base, SourceResolver resolver) throws IOException JavaDoc {
194         if (StringUtils.isEmpty(base)) {
195             base = null;
196         }
197         Source source = resolver.resolveURI(uri, base, null);
198         try {
199             return getContents(source.getInputStream());
200         } finally {
201             resolver.release(source);
202         }
203     }
204
205     public static String JavaDoc getFileContents(String JavaDoc filename) throws IOException JavaDoc {
206         return getContents(new FileReader JavaDoc(filename));
207     }
208
209     public static String JavaDoc getFileContents(String JavaDoc filename, String JavaDoc encoding) throws IOException JavaDoc {
210         return getContents(new FileInputStream JavaDoc(filename), encoding);
211     }
212
213     public static String JavaDoc getContents(InputStream JavaDoc in, String JavaDoc encoding) throws IOException JavaDoc {
214         return getContents(new InputStreamReader JavaDoc(in, encoding));
215     }
216
217     public static String JavaDoc getContents(InputStream JavaDoc in) throws IOException JavaDoc {
218         return getContents(new InputStreamReader JavaDoc(in));
219     }
220
221     public static String JavaDoc getContents(Reader JavaDoc reader) throws IOException JavaDoc {
222         int len;
223         char[] chr = new char[4096];
224         StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
225         try {
226             while ((len = reader.read(chr)) > 0) {
227                 buffer.append(chr, 0, len);
228             }
229         } finally {
230             reader.close();
231         }
232         return buffer.toString();
233     }
234
235     public static void includeSource(String JavaDoc uri, String JavaDoc base, SourceResolver resolver, ContentHandler JavaDoc contentHandler)
236             throws RuntimeException JavaDoc {
237         if (StringUtils.isEmpty(base)) {
238             base = null;
239         }
240         Source source = null;
241         try {
242             source = resolver.resolveURI(uri, base, null);
243             SourceUtil.toSAX(source, new IncludeXMLConsumer(contentHandler));
244         } catch (Exception JavaDoc e) {
245             throw new CascadingRuntimeException("Error including source " + base + " " + uri, e);
246         } finally {
247             if (source != null) {
248                 resolver.release(source);
249             }
250         }
251     }
252
253     public static void includeString(String JavaDoc string, ComponentManager manager, ContentHandler JavaDoc contentHandler)
254             throws RuntimeException JavaDoc {
255         XSPUtil.includeInputSource(new InputSource JavaDoc(new StringReader JavaDoc(String.valueOf(string))), manager,
256                                    contentHandler);
257     }
258
259     public static void includeFile(String JavaDoc name, ComponentManager manager, ContentHandler JavaDoc contentHandler, Map JavaDoc objectModel)
260             throws RuntimeException JavaDoc {
261         try {
262             XSPUtil.includeInputSource(new InputSource JavaDoc(new FileReader JavaDoc(XSPUtil.relativeFilename(name, objectModel))),
263                                        manager, contentHandler);
264         } catch (IOException JavaDoc e) {
265             throw new CascadingRuntimeException("Could not include file " + name, e);
266         }
267     }
268
269     public static void includeInputSource(InputSource JavaDoc source, ComponentManager manager, ContentHandler JavaDoc contentHandler)
270             throws RuntimeException JavaDoc {
271         SAXParser parser = null;
272         try {
273             parser = (SAXParser)manager.lookup(SAXParser.ROLE);
274             IncludeXMLConsumer consumer = new IncludeXMLConsumer(contentHandler);
275             parser.parse(source, consumer, consumer);
276         } catch (Exception JavaDoc e) {
277             throw new CascadingRuntimeException("Could not include page", e);
278         } finally {
279             if (parser != null) {
280                 manager.release((Component)parser);
281             }
282         }
283     }
284 }
285
Popular Tags