001: /*
002: * Licensed to the Apache Software Foundation (ASF) under one or more
003: * contributor license agreements. See the NOTICE file distributed with
004: * this work for additional information regarding copyright ownership.
005: * The ASF licenses this file to You under the Apache License, Version 2.0
006: * (the "License"); you may not use this file except in compliance with
007: * the License. You may obtain a copy of the License at
008: *
009: * http://www.apache.org/licenses/LICENSE-2.0
010: *
011: * Unless required by applicable law or agreed to in writing, software
012: * distributed under the License is distributed on an "AS IS" BASIS,
013: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014: * See the License for the specific language governing permissions and
015: * limitations under the License.
016: */
017: package org.apache.cocoon.components.language.markup.xsp;
018:
019: import org.apache.avalon.framework.CascadingRuntimeException;
020: import org.apache.avalon.framework.component.Component;
021: import org.apache.avalon.framework.component.ComponentManager;
022: import org.apache.cocoon.components.source.SourceUtil;
023: import org.apache.cocoon.environment.Context;
024: import org.apache.cocoon.environment.ObjectModelHelper;
025: import org.apache.cocoon.environment.Session;
026: import org.apache.cocoon.environment.SourceResolver;
027: import org.apache.cocoon.util.NetUtils;
028: import org.apache.cocoon.xml.IncludeXMLConsumer;
029: import org.apache.commons.lang.StringEscapeUtils;
030: import org.apache.commons.lang.StringUtils;
031: import org.apache.excalibur.source.Source;
032: import org.apache.excalibur.xml.sax.SAXParser;
033: import org.xml.sax.ContentHandler;
034: import org.xml.sax.InputSource;
035:
036: import java.io.File;
037: import java.io.FileInputStream;
038: import java.io.FileReader;
039: import java.io.IOException;
040: import java.io.InputStream;
041: import java.io.InputStreamReader;
042: import java.io.Reader;
043: import java.io.StringReader;
044: import java.io.FileNotFoundException;
045: import java.net.URLDecoder;
046: import java.net.URLEncoder;
047: import java.net.URL;
048: import java.text.SimpleDateFormat;
049: import java.util.Date;
050: import java.util.Map;
051:
052: /**
053: * The XSP <code>Utility</code> object helper
054: * @author <a href="mailto:ricardo@apache.org">Ricardo Rocha</a>
055: * @author <a href="mailto:bloritsch@apache.org">Berin Loritsch</a>
056: * @version CVS $Id: XSPUtil.java 433543 2006-08-22 06:22:54Z crossley $
057: */
058: public class XSPUtil {
059:
060: public static String pathComponent(String filename) {
061: int i = filename.lastIndexOf(File.separator);
062: return (i >= 0) ? filename.substring(0, i) : filename;
063: }
064:
065: public static String fileComponent(String filename) {
066: int i = filename.lastIndexOf(File.separator);
067: return (i >= 0) ? filename.substring(i + 1) : filename;
068: }
069:
070: public static String baseName(String filename) {
071: return baseName(filename, ".");
072: }
073:
074: public static String baseName(String filename, String suffix) {
075: int lastDot = filename.lastIndexOf(suffix);
076: if (lastDot >= 0) {
077: filename = filename.substring(0, lastDot);
078: }
079: return filename;
080: }
081:
082: public static String normalizedBaseName(String filename) {
083: filename = baseName(filename);
084: return normalizedName(filename);
085: }
086:
087: public static String normalizedName(String filename) {
088: String[] path = split(filename, File.separator);
089: int start = (path[0].length() == 0) ? 1 : 0;
090: StringBuffer buffer = new StringBuffer();
091: for (int i = start; i < path.length; i++) {
092: if (i > start) {
093: buffer.append(File.separator);
094: }
095: buffer.append('_');
096: char[] chars = path[i].toCharArray();
097: for (int j = 0; j < chars.length; j++) {
098: if (isAlphaNumeric(chars[j])) {
099: buffer.append(chars[j]);
100: } else {
101: buffer.append('_');
102: }
103: }
104: }
105: return buffer.toString();
106: }
107:
108: public static String relativeFilename(String filename,
109: Map objectModel) throws IOException {
110: File file = new File(filename);
111: if (file.isAbsolute() && file.exists()) {
112: return filename;
113: }
114: Context context = ObjectModelHelper.getContext(objectModel);
115: URL resource = context.getResource(filename);
116: if (resource == null) {
117: throw new FileNotFoundException("The file " + filename
118: + " does not exist!");
119: }
120: return NetUtils.getPath(resource.toExternalForm());
121: }
122:
123: public static boolean isAlphaNumeric(char c) {
124: return c == '_' || (c >= 'a' && c <= 'z')
125: || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
126: }
127:
128: public static String[] split(String line) {
129: return StringUtils.split(line, " \t\r\f\n");
130: }
131:
132: public static String[] split(String line, String delimiter) {
133: return StringUtils.split(line, delimiter);
134: }
135:
136: public static String encodeMarkup(String string) {
137: return StringEscapeUtils.escapeXml(string);
138: }
139:
140: public static String formEncode(String text) throws Exception {
141: return URLEncoder.encode(text);
142: }
143:
144: // Shameless, ain't it?
145: public static String formDecode(String s) throws Exception {
146: return URLDecoder.decode(s);
147: }
148:
149: /* Logicsheet Utility Methods */
150:
151: // Date
152: public static String formatDate(Date date, String pattern) {
153: if (StringUtils.isEmpty(pattern)) {
154: pattern = "yyyy/MM/dd hh:mm:ss aa";
155: }
156: try {
157: return (new SimpleDateFormat(pattern)).format(date);
158: } catch (Exception e) {
159: return date.toString();
160: }
161: }
162:
163: // Counters
164: private static volatile int count = 0;
165:
166: public static int getCount() {
167: return ++count;
168: }
169:
170: public static int getSessionCount(Session session) {
171: synchronized (session) {
172: Integer integer = (Integer) session
173: .getAttribute("util.counter");
174: if (integer == null) {
175: integer = new Integer(0);
176: }
177: int cnt = integer.intValue() + 1;
178: session.setAttribute("util.counter", new Integer(cnt));
179: return cnt;
180: }
181: }
182:
183: public static Object getContextAttribute(Map objectModel,
184: String name) {
185: Context context = ObjectModelHelper.getContext(objectModel);
186: return context.getAttribute(name);
187: }
188:
189: // Inclusion
190: public static String getSourceContents(String url,
191: SourceResolver resolver) throws IOException {
192: Source source = resolver.resolveURI(url);
193: try {
194: return getContents(source.getInputStream());
195: } finally {
196: resolver.release(source);
197: }
198: }
199:
200: public static String getSourceContents(String uri, String base,
201: SourceResolver resolver) throws IOException {
202: if (StringUtils.isEmpty(base)) {
203: base = null;
204: }
205: Source source = resolver.resolveURI(uri, base, null);
206: try {
207: return getContents(source.getInputStream());
208: } finally {
209: resolver.release(source);
210: }
211: }
212:
213: public static String getFileContents(String filename)
214: throws IOException {
215: return getContents(new FileReader(filename));
216: }
217:
218: public static String getFileContents(String filename,
219: String encoding) throws IOException {
220: return getContents(new FileInputStream(filename), encoding);
221: }
222:
223: public static String getContents(InputStream in, String encoding)
224: throws IOException {
225: return getContents(new InputStreamReader(in, encoding));
226: }
227:
228: public static String getContents(InputStream in) throws IOException {
229: return getContents(new InputStreamReader(in));
230: }
231:
232: public static String getContents(Reader reader) throws IOException {
233: int len;
234: char[] chr = new char[4096];
235: StringBuffer buffer = new StringBuffer();
236: try {
237: while ((len = reader.read(chr)) > 0) {
238: buffer.append(chr, 0, len);
239: }
240: } finally {
241: reader.close();
242: }
243: return buffer.toString();
244: }
245:
246: public static void includeSource(String uri, String base,
247: SourceResolver resolver, ContentHandler contentHandler)
248: throws RuntimeException {
249: if (StringUtils.isEmpty(base)) {
250: base = null;
251: }
252: Source source = null;
253: try {
254: source = resolver.resolveURI(uri, base, null);
255: SourceUtil.toSAX(source, new IncludeXMLConsumer(
256: contentHandler));
257: } catch (Exception e) {
258: throw new CascadingRuntimeException(
259: "Error including source " + base + " " + uri, e);
260: } finally {
261: if (source != null) {
262: resolver.release(source);
263: }
264: }
265: }
266:
267: public static void includeString(String string,
268: ComponentManager manager, ContentHandler contentHandler)
269: throws RuntimeException {
270: XSPUtil.includeInputSource(new InputSource(new StringReader(
271: String.valueOf(string))), manager, contentHandler);
272: }
273:
274: public static void includeFile(String name,
275: ComponentManager manager, ContentHandler contentHandler,
276: Map objectModel) throws RuntimeException {
277: try {
278: XSPUtil.includeInputSource(new InputSource(new FileReader(
279: XSPUtil.relativeFilename(name, objectModel))),
280: manager, contentHandler);
281: } catch (IOException e) {
282: throw new CascadingRuntimeException(
283: "Could not include file " + name, e);
284: }
285: }
286:
287: public static void includeInputSource(InputSource source,
288: ComponentManager manager, ContentHandler contentHandler)
289: throws RuntimeException {
290: SAXParser parser = null;
291: try {
292: parser = (SAXParser) manager.lookup(SAXParser.ROLE);
293: IncludeXMLConsumer consumer = new IncludeXMLConsumer(
294: contentHandler);
295: parser.parse(source, consumer, consumer);
296: } catch (Exception e) {
297: throw new CascadingRuntimeException(
298: "Could not include page", e);
299: } finally {
300: if (parser != null) {
301: manager.release((Component) parser);
302: }
303: }
304: }
305: }
|