You are viewing a plain text version of this content. The canonical link for it is here.
Posted to cvs@cocoon.apache.org by jh...@apache.org on 2005/11/03 15:00:48 UTC

svn commit: r330548 [65/132] - in /cocoon/whiteboard/maven2/cocoon-flat-layout: ./ cocoon-ajax-block/ cocoon-ajax-block/api/ cocoon-ajax-block/api/src/ cocoon-ajax-block/api/src/main/ cocoon-ajax-block/api/src/main/java/ cocoon-ajax-block/api/src/main/...

Added: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/NetUtils.java
URL: http://svn.apache.org/viewcvs/cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/NetUtils.java?rev=330548&view=auto
==============================================================================
--- cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/NetUtils.java (added)
+++ cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/NetUtils.java Thu Nov  3 05:41:06 2005
@@ -0,0 +1,500 @@
+/*
+ * Copyright 1999-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.util;
+
+import org.apache.cocoon.environment.Request;
+import org.apache.commons.lang.StringUtils;
+import org.apache.excalibur.source.SourceParameters;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.UnsupportedEncodingException;
+import java.net.URLDecoder;
+import java.net.URLEncoder;
+import java.util.BitSet;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.StringTokenizer;
+
+/**
+ * A collection of <code>File</code>, <code>URL</code> and filename
+ * utility methods
+ *
+ * @author <a href="mailto:stefano@apache.org">Stefano Mazzocchi</a>
+ * @version CVS $Id: NetUtils.java 168043 2005-05-04 01:49:38Z antonio $
+ */
+public class NetUtils {
+
+    /**
+     * Array containing the safe characters set as defined by RFC 1738
+     */
+    private static BitSet safeCharacters;
+
+    private static final char[] hexadecimal =
+    {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
+     'A', 'B', 'C', 'D', 'E', 'F'};
+
+    static {
+        safeCharacters = new BitSet(256);
+        int i;
+        // 'lowalpha' rule
+        for (i = 'a'; i <= 'z'; i++) {
+            safeCharacters.set(i);
+        }
+        // 'hialpha' rule
+        for (i = 'A'; i <= 'Z'; i++) {
+            safeCharacters.set(i);
+        }
+        // 'digit' rule
+        for (i = '0'; i <= '9'; i++) {
+            safeCharacters.set(i);
+        }
+
+        // 'safe' rule
+        safeCharacters.set('$');
+        safeCharacters.set('-');
+        safeCharacters.set('_');
+        safeCharacters.set('.');
+        safeCharacters.set('+');
+
+        // 'extra' rule
+        safeCharacters.set('!');
+        safeCharacters.set('*');
+        safeCharacters.set('\'');
+        safeCharacters.set('(');
+        safeCharacters.set(')');
+        safeCharacters.set(',');
+
+        // special characters common to http: file: and ftp: URLs ('fsegment' and 'hsegment' rules)
+        safeCharacters.set('/');
+        safeCharacters.set(':');
+        safeCharacters.set('@');
+        safeCharacters.set('&');
+        safeCharacters.set('=');
+    }
+
+    /**
+     * Decode a path.
+     *
+     * <p>Interprets %XX (where XX is hexadecimal number) as UTF-8 encoded bytes.
+     * <p>The validity of the input path is not checked (i.e. characters that were not encoded will
+     * not be reported as errors).
+     * <p>This method differs from URLDecoder.decode in that it always uses UTF-8 (while URLDecoder
+     * uses the platform default encoding, often ISO-8859-1), and doesn't translate + characters to spaces.
+     *
+     * @param path the path to decode
+     * @return the decoded path
+     */
+    public static String decodePath(String path) {
+        StringBuffer translatedPath = new StringBuffer(path.length());
+        byte[] encodedchars = new byte[path.length() / 3];
+        int i = 0;
+        int length = path.length();
+        int encodedcharsLength = 0;
+        while (i < length) {
+            if (path.charAt(i) == '%') {
+                // we must process all consecutive %-encoded characters in one go, because they represent
+                // an UTF-8 encoded string, and in UTF-8 one character can be encoded as multiple bytes
+                while (i < length && path.charAt(i) == '%') {
+                    if (i + 2 < length) {
+                        try {
+                            byte x = (byte)Integer.parseInt(path.substring(i + 1, i + 3), 16);
+                            encodedchars[encodedcharsLength] = x;
+                        } catch (NumberFormatException e) {
+                            throw new IllegalArgumentException("NetUtils.decodePath: " +
+                                                               "Illegal hex characters in pattern %" + path.substring(i + 1, i + 3));
+                        }
+                        encodedcharsLength++;
+                        i += 3;
+                    } else {
+                        throw new IllegalArgumentException("NetUtils.decodePath: " +
+                                                           "% character should be followed by 2 hexadecimal characters.");
+                    }
+                }
+                try {
+                    String translatedPart = new String(encodedchars, 0, encodedcharsLength, "UTF-8");
+                    translatedPath.append(translatedPart);
+                } catch (UnsupportedEncodingException e) {
+                    // the situation that UTF-8 is not supported is quite theoretical, so throw a runtime exception
+                    throw new RuntimeException("Problem in decodePath: UTF-8 encoding not supported.");
+                }
+                encodedcharsLength = 0;
+            } else {
+                // a normal character
+                translatedPath.append(path.charAt(i));
+                i++;
+            }
+        }
+        return translatedPath.toString();
+    }
+
+    /**
+     * Encode a path as required by the URL specification (<a href="http://www.ietf.org/rfc/rfc1738.txt">
+     * RFC 1738</a>). This differs from <code>java.net.URLEncoder.encode()</code> which encodes according
+     * to the <code>x-www-form-urlencoded</code> MIME format.
+     *
+     * @param path the path to encode
+     * @return the encoded path
+     */
+    public static String encodePath(String path) {
+       // stolen from org.apache.catalina.servlets.DefaultServlet ;)
+
+        /**
+         * Note: This code portion is very similar to URLEncoder.encode.
+         * Unfortunately, there is no way to specify to the URLEncoder which
+         * characters should be encoded. Here, ' ' should be encoded as "%20"
+         * and '/' shouldn't be encoded.
+         */
+
+        int maxBytesPerChar = 10;
+        StringBuffer rewrittenPath = new StringBuffer(path.length());
+        ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
+        OutputStreamWriter writer = null;
+        try {
+            writer = new OutputStreamWriter(buf, "UTF8");
+        } catch (Exception e) {
+            e.printStackTrace();
+            writer = new OutputStreamWriter(buf);
+        }
+
+        for (int i = 0; i < path.length(); i++) {
+            int c = path.charAt(i);
+            if (safeCharacters.get(c)) {
+                rewrittenPath.append((char)c);
+            } else {
+                // convert to external encoding before hex conversion
+                try {
+                    writer.write(c);
+                    writer.flush();
+                } catch(IOException e) {
+                    buf.reset();
+                    continue;
+                }
+                byte[] ba = buf.toByteArray();
+                for (int j = 0; j < ba.length; j++) {
+                    // Converting each byte in the buffer
+                    byte toEncode = ba[j];
+                    rewrittenPath.append('%');
+                    int low = (toEncode & 0x0f);
+                    int high = ((toEncode & 0xf0) >> 4);
+                    rewrittenPath.append(hexadecimal[high]);
+                    rewrittenPath.append(hexadecimal[low]);
+                }
+                buf.reset();
+            }
+        }
+        return rewrittenPath.toString();
+    }
+
+    /**
+     * Returns the path of the given resource.
+     *
+     * @param uri The URI of the resource
+     * @return the resource path
+     */
+    public static String getPath(String uri) {
+        int i = uri.lastIndexOf('/');
+        if (i > -1) {
+            return uri.substring(0, i);
+        }
+        i = uri.indexOf(':');
+        return (i > -1) ? uri.substring(i + 1, uri.length()) : "";
+    }
+
+    /**
+     * Remove path and file information from a filename returning only its
+     * extension  component
+     *
+     * @param uri The filename
+     * @return The filename extension (with starting dot!) or null if filename extension is not found
+     */
+    public static String getExtension(String uri) {
+        int dot = uri.lastIndexOf('.');
+        if (dot > -1) {
+            uri = uri.substring(dot);
+            int slash = uri.lastIndexOf('/');
+            if (slash > -1) {
+                return null;
+            } else {
+                int sharp = uri.lastIndexOf('#');
+                if (sharp > -1) {
+                    // uri starts with dot already
+                    return uri.substring(0, sharp);
+                } else {
+                    int mark = uri.lastIndexOf('?');
+                    if (mark > -1) {
+                        // uri starts with dot already
+                        return uri.substring(0, mark);
+                    } else {
+                        return uri;
+                    }
+                }
+            }
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * Absolutize a relative resource path on the given absolute base path.
+     *
+     * @param path The absolute base path
+     * @param resource The relative resource path
+     * @return The absolutized resource path
+     */
+    public static String absolutize(String path, String resource) {
+        if (StringUtils.isEmpty(path)) {
+            return resource;
+        } else if (StringUtils.isEmpty(resource)) {
+            return path;
+        } else if (resource.charAt(0) == '/') {
+            // Resource path is already absolute
+            return resource;
+        }
+
+        boolean slash = (path.charAt(path.length() - 1) == '/');
+        
+        StringBuffer b = new StringBuffer(path.length() + 1 + resource.length());
+        b.append(path);
+        if (!slash) {
+            b.append('/');
+        } 
+        b.append(resource);
+        return b.toString();
+    }
+
+    /**
+     * Relativize an absolute resource on a given absolute path.
+     *
+     * @param path The absolute path
+     * @param absoluteResource The absolute resource
+     * @return the resource relative to the given path
+     */
+    public static String relativize(String path, String absoluteResource) {
+        if (StringUtils.isEmpty(path)) {
+            return absoluteResource;
+        }
+
+        if (path.charAt(path.length() - 1) != '/') {
+            path += "/";
+        }
+
+        if (absoluteResource.startsWith(path)) {
+            // resource is direct descentant
+            return absoluteResource.substring(path.length());
+        } else {
+            // resource is not direct descendant
+            int index = StringUtils.indexOfDifference(path, absoluteResource);
+            if (index > 0 && path.charAt(index-1) != '/') {
+                index = path.substring(0, index).lastIndexOf('/');
+                index++;
+            }
+            String pathDiff = path.substring(index);
+            String resource = absoluteResource.substring(index);
+            int levels = StringUtils.countMatches(pathDiff, "/");
+            StringBuffer b = new StringBuffer(levels * 3 + resource.length());
+            for (int i = 0; i < levels; i++) {
+                b.append("../");
+            }
+            b.append(resource);
+            return b.toString();
+        }
+    }
+
+    /**
+     * Normalize a uri containing ../ and ./ paths.
+     *
+     * @param uri The uri path to normalize
+     * @return The normalized uri
+     */
+    public static String normalize(String uri) {
+        if ("".equals(uri)) {
+            return uri;
+        }
+        int leadingSlashes = 0;
+        for (leadingSlashes = 0 ; leadingSlashes < uri.length()
+                && uri.charAt(leadingSlashes) == '/' ; ++leadingSlashes) {}
+        boolean isDir = (uri.charAt(uri.length() - 1) == '/');
+        StringTokenizer st = new StringTokenizer(uri, "/");
+        LinkedList clean = new LinkedList();
+        while (st.hasMoreTokens()) {
+            String token = st.nextToken();
+            if ("..".equals(token)) {
+                if (! clean.isEmpty() && ! "..".equals(clean.getLast())) {
+                    clean.removeLast();
+                    if (! st.hasMoreTokens()) {
+                        isDir = true;
+                    }
+                } else {
+                    clean.add("..");
+                }
+            } else if (! ".".equals(token) && ! "".equals(token)) {
+                clean.add(token);
+            }
+        }
+        StringBuffer sb = new StringBuffer();
+        while (leadingSlashes-- > 0) {
+            sb.append('/');
+        }
+        for (Iterator it = clean.iterator() ; it.hasNext() ; ) {
+            sb.append(it.next());
+            if (it.hasNext()) {
+                sb.append('/');
+            }
+        }
+        if (isDir && sb.length() > 0 && sb.charAt(sb.length() - 1) != '/') {
+            sb.append('/');
+        }
+        return sb.toString();
+    }
+
+    /**
+     * Remove parameters from a uri.
+     * Resulting Map will have either String for single value attributes,
+     * or String arrays for multivalue attributes.
+     * 
+     * @param uri The uri path to deparameterize.
+     * @param parameters The map that collects parameters.
+     * @return The cleaned uri
+     */
+    public static String deparameterize(String uri, Map parameters) {
+        int i = uri.lastIndexOf('?');
+        if (i == -1) {
+            return uri;
+        }
+
+        String[] params = StringUtils.split(uri.substring(i + 1), '&');
+        for (int j = 0; j < params.length; j++) {
+            String p = params[j];
+            int k = p.indexOf('=');
+            if (k == -1) {
+                break;
+            }
+            String name = p.substring(0, k);
+            String value = p.substring(k + 1);
+            Object values = parameters.get(name);
+            if (values == null) {
+                parameters.put(name, value);
+            } else if (values.getClass().isArray()) {
+                String[] v1 = (String[])values;
+                String[] v2 = new String[v1.length + 1];
+                System.arraycopy(v1, 0, v2, 0, v1.length);
+                v2[v1.length] = value;
+                parameters.put(name, v2);
+            } else {
+                parameters.put(name, new String[]{values.toString(), value});
+            }
+        }
+        return uri.substring(0, i);
+    }
+
+    /**
+     * Add parameters stored in the Map to the uri string.
+     * Map can contain Object values which will be converted to the string,
+     * or Object arrays, which will be treated as multivalue attributes.
+     * 
+     * @param uri The uri to add parameters into
+     * @param parameters The map containing parameters to be added
+     * @return The uri with added parameters
+     */
+    public static String parameterize(String uri, Map parameters) {
+        if (parameters.size() == 0) {
+            return uri;
+        }
+        
+        StringBuffer buffer = new StringBuffer(uri);
+        if (uri.indexOf('?') == -1) {
+            buffer.append('?');
+        } else {
+            buffer.append('&');
+        }
+        
+        for (Iterator i = parameters.entrySet().iterator(); i.hasNext();) {
+            Map.Entry entry = (Map.Entry)i.next();
+            if (entry.getValue().getClass().isArray()) {
+                Object[] value = (Object[])entry.getValue();
+                for (int j = 0; j < value.length; j++) {
+                    if (j > 0) {
+                        buffer.append('&');
+                    }
+                    buffer.append(entry.getKey());
+                    buffer.append('=');
+                    buffer.append(value[j]);
+                }
+            } else {
+                buffer.append(entry.getKey());
+                buffer.append('=');
+                buffer.append(entry.getValue());
+            }
+            if (i.hasNext()) {
+                buffer.append('&');
+            }
+        }
+        return buffer.toString();
+    }
+
+    /**
+     * Create new <code>SourceParameters</code> with the same
+     * parameters as the current request
+     */
+    public static SourceParameters createParameters(Request request) {
+        final SourceParameters pars = new SourceParameters();
+
+        if (null != request) {
+            final Enumeration names = request.getParameterNames();
+            while (names.hasMoreElements()) {
+                final String current = (String)names.nextElement();
+                final String[] values = request.getParameterValues(current);
+                if (null != values) {
+                    for(int i=0; i < values.length; i++) {
+                        pars.setParameter(current, values[i]);
+                    }
+                }
+            }
+        }
+
+        return pars;
+    }
+
+    /**
+     * Remove any authorisation details from a URI
+     */
+    public static String removeAuthorisation(String uri) {
+        if (uri.indexOf("@")!=-1 && (uri.startsWith("ftp://") || uri.startsWith("http://"))) {
+            return uri.substring(0, uri.indexOf(":")+2)+uri.substring(uri.indexOf("@")+1);
+        }
+        return uri;
+    }
+
+    /**
+     * Pass through to the {@link java.net.URLEncoder}. If running under JDK &lt; 1.4,
+     * default encoding will always be used.
+     */
+    public static String encode(String s, String enc) throws UnsupportedEncodingException {
+        return URLEncoder.encode(s, enc);
+    }
+
+    /**
+     * Pass through to the {@link java.net.URLDecoder}. If running under JDK &lt; 1.4,
+     * default encoding will always be used.
+     */
+    public static String decode(String s, String enc) throws UnsupportedEncodingException {
+        return URLDecoder.decode(s, enc);
+    }
+}

Propchange: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/NetUtils.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/NullOutputStream.java
URL: http://svn.apache.org/viewcvs/cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/NullOutputStream.java?rev=330548&view=auto
==============================================================================
--- cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/NullOutputStream.java (added)
+++ cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/NullOutputStream.java Thu Nov  3 05:41:06 2005
@@ -0,0 +1,37 @@
+/*
+ * Copyright 1999-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.util;
+
+import java.io.OutputStream;
+
+/**
+ * @author <a href="http://apache.org/~reinhard">Reinhard Poetz</a> 
+ * @version CVS $Id: NullOutputStream.java 30941 2004-07-29 19:56:58Z vgritsenko $
+ *
+ * @since 2.1.4
+ */
+public final class NullOutputStream extends OutputStream {
+
+    public void write(byte b[]) {
+    }
+
+    public void write(byte b[], int off, int len) {
+    }
+
+    public void write(int b) {
+    }
+
+}
\ No newline at end of file

Propchange: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/NullOutputStream.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/PostInputStream.java
URL: http://svn.apache.org/viewcvs/cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/PostInputStream.java?rev=330548&view=auto
==============================================================================
--- cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/PostInputStream.java (added)
+++ cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/PostInputStream.java Thu Nov  3 05:41:06 2005
@@ -0,0 +1,264 @@
+/*
+ * Copyright 1999-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+/**
+ * The class PostInputStream is a wrapper for InputStream associated with POST message.
+ * It allows to control read operation, restricting the number of bytes read to the value returned by getContentLen() method.
+ *
+ * @author <a href="mailto:Kinga_Dziembowski@hp.com">Kinga Dziembowski</a>
+ * @version CVS $Id: PostInputStream.java 30941 2004-07-29 19:56:58Z vgritsenko $
+ */
+
+public class PostInputStream extends InputStream {
+
+    /**
+    * Class name
+    */
+    public static final String CLASS = PostInputStream.class.getName();
+
+    /** The real InputStream object */
+    private InputStream m_inputStream = null;
+
+    /** The length of InputStream */
+    private int m_contentLen = 0;
+
+    /** The number of bytes read */
+    protected int m_bytesRead = 0;
+
+
+    /**
+    * Creates a PostInputStream
+    */
+    public PostInputStream() {
+        super();
+    }
+    /**
+    * Creates a <code>PostInputStream</code> based on a real InputStream object with the specified
+    * post message body length. Saves its  argument, the input stream
+    * <code>m_inputStream</code>, for later use.
+    *
+    * @param   input     the underlying input stream.
+    * @param   len   the post message body length.
+    * @exception IllegalArgumentException  len <= 0.
+    */
+
+    public PostInputStream(final InputStream input, final int len) throws IllegalArgumentException {
+        super();
+        init(input, len );
+    }
+    /**
+    * Sets the underlying input stream and contentLen value .
+    *
+    * @param input the input stream; can not be null.
+    * @param len the post message body length.
+    *
+    * @throws IllegalArgumentException
+    */
+    protected void init(final InputStream input, final int len) throws IllegalArgumentException {
+        if (len <= 0) {
+            throw new IllegalArgumentException("contentLen <= 0 ");
+        }
+        this.m_inputStream = input;
+        this.m_contentLen = len;
+    }
+
+    /**
+    * Sets the underlying input stream and contentLen value .
+    *
+    * @param input the input stream; can not be null.
+    * @param len the post message body length.
+    *
+    * @throws IOException
+    */
+    public synchronized void setInputStream(final InputStream input, final int len) throws IOException {
+        if (m_inputStream != null) {
+            close();
+        }
+        init(input, len);
+    }
+    /**
+    * Returns the underlying input stream.
+    *
+    * @return inputStream the underlying InputStream.
+    */
+    public InputStream getInputStream() {
+        return( m_inputStream );
+    }
+
+    /**
+    * Returns the post message body length.
+    *
+    * @return m_contentLen;
+    */
+
+    public int getContentLen() {
+        return( m_contentLen );
+    }
+
+    /**
+    * Reads the next byte from the input stream.  If the end of the stream has been reached, this method returns -1.
+    *
+    * @return the next byte or -1 if at the end of the stream.
+    *
+    * @throws IOException
+    */
+    public synchronized int read() throws IOException {
+
+        checkOpen();
+        if (m_bytesRead == m_contentLen) {
+            return -1;
+        }
+        int byt =  m_inputStream.read();
+        if (byt != -1) {
+           m_bytesRead++;
+        }
+        return byt;
+    }
+
+    /**
+    * Reads bytes from this byte-input stream into the specified byte array,
+    * starting at the given offset.
+    *
+    * <p> This method implements the general contract of the corresponding
+    * <code>{@link InputStream#read(byte[], int, int) read}</code> method of
+    * the <code>{@link InputStream}</code> class.
+    * This method delegetes the read operation to the underlying InputStream implementation class but it
+    * controlls the number of bytes read from the stream. In the remote situation the underlying InputStream has no knowledge of
+    * the length of the stream and the notion of the "end" is undefined. This wrapper class has a knowledge of the
+    * length of data send by the requestor by the means of contentLength. This method returns the number of bytes read and
+    * accumulates the total number of bytes read in m_bytesRead. When the m_bytesRead is equal to the specified contentLength
+    * value the method returns returns -1 to signal the end of data.
+    *
+    * @param buffer the byte array to read into; can not be null.
+    * @param offset the starting offset in the byte array.
+    * @param len the maximum number of bytes to read.
+    *
+    * @return     the number of bytes read, or <code>-1</code> if the end of
+    *             the stream has been reached.
+    * @exception  IOException  if an I/O error occurs.
+    */
+
+    public synchronized int read(byte[] buffer, int offset, int len) throws IOException {
+        checkOpen();
+        if (m_bytesRead == m_contentLen) {
+            return -1;
+        }
+        int available = Math.min( available(), len );
+        int num = m_inputStream.read( buffer, offset, available );
+        if (num > 0) {
+            m_bytesRead += num;
+        }
+        return num;
+    }
+
+    public synchronized int read(byte[] buffer) throws IOException {
+
+        return read( buffer, 0, buffer.length);
+    }
+
+
+    /**
+    * Checks to see if this stream is closed; if it is, an IOException is thrown.
+    *
+    * @throws IOException
+    */
+    protected void checkOpen() throws IOException {
+        if (m_inputStream == null) {
+            throw new IOException("InputStream closed");
+        }
+    }
+
+    /**
+         * See the general contract of the <code>skip</code>
+     * method of <code>InputStream</code>.
+     * Delegates execution to the underlying InputStream implementation class.
+     * Checks to see if this stream is closed; if it is, an IOException is thrown.
+     * @param      n   the number of bytes to be skipped.
+     * @return     the actual number of bytes skipped.
+     * @exception  IOException  if an I/O error occurs.
+     */
+    public synchronized long skip(long n) throws IOException {
+        checkOpen();
+        if ( m_bytesRead == m_contentLen )
+        {
+            return ( 0 );
+        }
+        else
+        {
+            return ( m_inputStream.skip( n ) );
+        }
+
+    }
+
+    /**
+    * Returns the number of bytes available from this input stream that can be read without the stream blocking.
+    * Delegates execution to the underlying InputStream implementation class.
+    * @return available the number of available bytes.
+    *
+    * @throws IOException
+    */
+    public synchronized int available() throws IOException {
+        checkOpen();
+        int avail = m_inputStream.available();
+        return (avail == 0 ? (m_contentLen - m_bytesRead) : avail);
+    }
+
+    /**
+    * Tests if this input stream supports the <code>mark</code>
+    * and <code>reset</code> methods. The <code>markSupported</code>
+    * method of <code>BufferedInputStream</code> returns
+    * <code>false</code>.
+    *
+    * @return  a <code>boolean</code> indicating if this stream type supports
+    *          the <code>mark</code> and <code>reset</code> methods.
+    * @see     java.io.InputStream#mark(int)
+    * @see     java.io.InputStream#reset()
+    */
+    public boolean markSupported() {
+        return false;
+    }
+
+    /**
+    * Closes this input stream by closing the underlying stream and marking this one as closed.
+    *
+    * @throws IOException
+    */
+    public synchronized void close() throws IOException {
+        if (m_inputStream == null) {
+            return;
+        }
+        m_inputStream.close();
+        m_inputStream = null;
+        m_contentLen = 0;
+        m_bytesRead = 0;
+    }
+
+    /**
+    * Returns a String representation of this.
+    *
+    * @return string the String representation of this.
+    */
+    public String toString() {
+        return new StringBuffer(getClass().getName())
+                .append("[inputStream=").append(m_inputStream)
+                .append(",  contentLen=").append(m_contentLen)
+                .append("bytesRead=").append(m_bytesRead)
+                .append("]").toString();
+    }
+}

Propchange: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/PostInputStream.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/ReflectionUtils.java
URL: http://svn.apache.org/viewcvs/cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/ReflectionUtils.java?rev=330548&view=auto
==============================================================================
--- cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/ReflectionUtils.java (added)
+++ cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/ReflectionUtils.java Thu Nov  3 05:41:06 2005
@@ -0,0 +1,137 @@
+/*
+ * Copyright 1999-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.util;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.Map;
+
+/**
+ * @author tcurdt
+ *
+ */
+public final class ReflectionUtils {
+
+	public interface Matcher {
+        boolean matches(final String pName);
+    }
+	    
+    public interface Indexer {
+        void put(final Map pMap, final String pKey, final Object pObject);
+    }
+	    
+    private static DefaultIndexer defaultIndexer = new DefaultIndexer();
+    private static DefaultMatcher defaultMatcher = new DefaultMatcher();
+	    
+    private static class DefaultMatcher implements Matcher {
+        public boolean matches(final String pName) {
+            return pName.startsWith("do");
+        }
+    }
+	    
+    private static class DefaultIndexer implements Indexer {
+        public void put(final Map pMap, final String pKey, final Object pObject) {
+
+            // doAction -> action
+            final String name = Character.toLowerCase(pKey.charAt(2)) + pKey.substring(3);
+
+            System.out.println("reflecting " + name);
+            pMap.put(name, pObject);
+        }
+    }
+	    
+    public static Map discoverFields(
+            final Class pClazz,
+            final Matcher pMatcher
+            ) {
+        
+        return discoverFields(pClazz, pMatcher, defaultIndexer);
+    }
+
+    public static Map discoverFields(
+            final Class pClazz
+            ) {
+        
+        return discoverFields(pClazz, defaultMatcher, defaultIndexer);
+    }
+    
+    public static Map discoverFields(
+            final Class pClazz,
+            final Matcher pMatcher,
+            final Indexer pIndexer
+            ) {
+        
+        System.out.println("discovering fields on " + pClazz.getName());
+        
+        final Map result = new HashMap();
+
+        Class current = pClazz;
+        do {
+            final Field[] fields = current.getDeclaredFields();
+            for (int i = 0; i < fields.length; i++) {
+                final String fname = fields[i].getName();
+                if (pMatcher.matches(fname)) {
+                    pIndexer.put(result, fname, fields[i]);
+                }
+            }
+            current = current.getSuperclass();
+        } while(current != null);
+     
+        return result;
+    }    
+
+    
+    public static Map discoverMethods(
+            final Class pClazz,
+            final Matcher pMatcher
+            ) {
+        
+        return discoverMethods(pClazz, pMatcher, defaultIndexer);
+    }
+
+    public static Map discoverMethods(
+            final Class pClazz
+            ) {
+        
+        return discoverMethods(pClazz, defaultMatcher, defaultIndexer);
+    }
+    
+    public static Map discoverMethods(
+            final Class pClazz,
+            final Matcher pMatcher,
+            final Indexer pIndexer
+            ) {
+        
+        System.out.println("discovering methods on " + pClazz.getName());
+        
+        final Map result = new HashMap();
+
+        Class current = pClazz;
+        do {
+            final Method[] methods = current.getDeclaredMethods();
+            for (int i = 0; i < methods.length; i++) {
+                final String mname = methods[i].getName();
+                if (pMatcher.matches(mname)) {
+                    pIndexer.put(result, mname, methods[i]);
+                }
+            }
+            current = current.getSuperclass();
+        } while(current != null);
+     
+        return result;
+    }    
+
+}

Propchange: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/ReflectionUtils.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/ResizableContainer.java
URL: http://svn.apache.org/viewcvs/cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/ResizableContainer.java?rev=330548&view=auto
==============================================================================
--- cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/ResizableContainer.java (added)
+++ cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/ResizableContainer.java Thu Nov  3 05:41:06 2005
@@ -0,0 +1,70 @@
+/*
+ * Copyright 1999-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cocoon.util;
+
+/**
+ * Add-only Container class.
+ *
+ * @author <a href="mailto:stefano@apache.org">Stefano Mazzocchi</a>
+ * @version CVS $Id: ResizableContainer.java 30941 2004-07-29 19:56:58Z vgritsenko $
+ */
+public class ResizableContainer {
+
+    private int pointer = -1;
+    private int size = 0;
+    private Object[] container;
+
+    public ResizableContainer(int initialCapacity){
+        this.container = new Object[initialCapacity];
+    }
+
+    public void add(Object o) {
+        set(++pointer,o);
+    }
+    
+    public void set(int index, Object o) {
+        adjustPointer(index);
+        ensureCapacity(index+1);
+        container[index] = o;
+        size++;
+    }
+    
+    public Object get(int index) {
+        return (index < container.length) ? container[index] : null; 
+    }    
+
+    public int size() {
+        return size;
+    }
+
+    private void adjustPointer(int newPointer) {
+        this.pointer = Math.max(this.pointer, newPointer);
+    }
+    
+    private void ensureCapacity(int minCapacity) {
+        int oldCapacity = container.length;
+        if (oldCapacity < minCapacity) {
+            Object[] oldContainer = container;
+            int newCapacity = (oldCapacity * 3)/2 + 1;
+            if (newCapacity < minCapacity) {
+                newCapacity = minCapacity;
+            }
+            container = new Object[newCapacity];
+            System.arraycopy(oldContainer, 0, container, 0, oldContainer.length);
+        }
+    }
+}

Propchange: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/ResizableContainer.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/StringUtils.java
URL: http://svn.apache.org/viewcvs/cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/StringUtils.java?rev=330548&view=auto
==============================================================================
--- cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/StringUtils.java (added)
+++ cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/StringUtils.java Thu Nov  3 05:41:06 2005
@@ -0,0 +1,75 @@
+/*
+ * Copyright 1999-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.util;
+
+/**
+ * A collection of <code>String</code> handling utility methods.
+ *
+ * @author <a href="mailto:ricardo@apache.org">Ricardo Rocha</a>
+ * @author <a href="mailto:stefano@apache.org">Stefano Mazzocchi</a>
+ * @version CVS $Id: StringUtils.java 30941 2004-07-29 19:56:58Z vgritsenko $
+ */
+public class StringUtils {
+
+    /**
+     * Split a string as an array using whitespace as separator
+     *
+     * @param line The string to be split
+     * @return An array of whitespace-separated tokens
+     */
+    public static String[] split(String line) {
+        return split(line, " \t\n\r");
+    }
+
+    /**
+     * Split a string as an array using a given set of separators
+     *
+     * @param line The string to be split
+     * @param delimiter A string containing token separators
+     * @return An array of token
+     */
+    public static String[] split(String line, String delimiter) {
+        return Tokenizer.tokenize(line, delimiter, false);
+    }
+
+    /**
+     * Tests whether a given character is alphabetic, numeric or
+     * underscore
+     *
+     * @param c The character to be tested
+     * @return whether the given character is alphameric or not
+     */
+    public static boolean isAlphaNumeric(char c) {
+        return c == '_' ||
+            (c >= 'a' && c <= 'z') ||
+            (c >= 'A' && c <= 'Z') ||
+            (c >= '0' && c <= '9');
+    }
+
+    /**
+     * Replaces tokens in input with Value present in System.getProperty
+     */
+    public static String replaceToken(String s) {
+        int startToken = s.indexOf("${");
+        int endToken = s.indexOf("}",startToken);
+        String token = s.substring(startToken+2,endToken);
+        StringBuffer value = new StringBuffer();
+        value.append(s.substring(0,startToken));
+        value.append(System.getProperty(token));
+        value.append(s.substring(endToken+1));
+        return value.toString();
+    }
+}

Propchange: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/StringUtils.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/Tokenizer.java
URL: http://svn.apache.org/viewcvs/cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/Tokenizer.java?rev=330548&view=auto
==============================================================================
--- cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/Tokenizer.java (added)
+++ cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/Tokenizer.java Thu Nov  3 05:41:06 2005
@@ -0,0 +1,289 @@
+/*
+ * Copyright 1999-2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.util;
+
+import java.util.Enumeration;
+import java.util.NoSuchElementException;
+
+/**
+ * Replacement for StringTokenizer in java.util, because of bug in the
+ * Sun's implementation.
+ *
+ * @author <A HREF="mailto:moravek@pobox.sk">Peter Moravek</A>
+ * @version CVS $Id: Tokenizer.java 47156 2004-09-24 13:34:02Z vgritsenko $
+ */
+public class Tokenizer implements Enumeration {
+
+  /**
+   * Constructs a string tokenizer for the specified string. All characters
+   * in the delim argument are the delimiters for separating tokens.
+   * If the returnTokens flag is true, then the delimiter characters are
+   * also returned as tokens. Each delimiter is returned as a string of
+   * length one. If the flag is false, the delimiter characters are skipped
+   * and only serve as separators between tokens.
+   *
+   * @param str           a string to be parsed
+   * @param delim         the delimiters
+   * @param returnTokens  flag indicating whether to return the delimiters
+   *                      as tokens
+   */
+  public Tokenizer(String str, String delim, boolean returnTokens) {
+    this.str = str;
+    this.delim = delim;
+    this.returnTokens = returnTokens;
+
+    max = str.length();
+  }
+
+  /**
+   * Constructs a string tokenizer for the specified string. The characters
+   * in the delim argument are the delimiters for separating tokens.
+   * Delimiter characters themselves will not be treated as tokens.
+   *
+   * @param str          a string to be parsed
+   * @param delim        the delimiters
+   */
+  public Tokenizer(String str, String delim) {
+    this(str, delim, false);
+  }
+
+  /**
+   * Constructs a string tokenizer for the specified string. The character
+   * in the delim argument is the delimiter for separating tokens.
+   * Delimiter character themselves will not be treated as token.
+   *
+   * @param str          a string to be parsed
+   * @param delim        the delimiter
+   */
+  public Tokenizer(String str, char delim) {
+    this(str, String.valueOf(delim), false);
+  }
+
+  /**
+   * Constructs a string tokenizer for the specified string. The tokenizer
+   * uses the default delimiter set, which is " \t\n\r\f": the space
+   * character, the tab character, the newline character, the carriage-return
+   * character, and the form-feed character. Delimiter characters themselves
+   * will not be treated as tokens.
+   *
+   * @param str          a string to be parsed
+   */
+  public Tokenizer(String str) {
+    this(str, DEFAULT_DELIMITERS, false);
+  }
+
+  /**
+   * Tests if there are more tokens available from this tokenizer's string.
+   * If this method returns true, then a subsequent call to nextToken with
+   * no argument will successfully return a token.
+   *
+   * @return true if and only if there is at least one token in the string
+   * after the current position; false otherwise.
+   */
+  public boolean hasMoreTokens() {
+    return ((current < max) ? (true) :
+      (((current == max) && (max == 0
+        || (returnTokens && delim.indexOf(str.charAt(previous)) >= 0)))));
+  }
+
+  /**
+   * Returns the next token from this string tokenizer.
+   *
+   * @return the next token from this string tokenizer
+   *
+   * @exception NoSuchElementException  if there are no more tokens in this
+   *                                    tokenizer's string
+   */
+  public String nextToken() throws NoSuchElementException {
+    if (current == max
+      && (max == 0
+      || (returnTokens && delim.indexOf(str.charAt(previous)) >= 0))) {
+
+      current++;
+      return new String();
+    }
+
+    if (current >= max)
+      throw new NoSuchElementException();
+
+    int start = current;
+    String result = null;
+
+    if (delim.indexOf(str.charAt(start)) >= 0) {
+      if (previous == -1 || (returnTokens && previous != current
+        && delim.indexOf(str.charAt(previous)) >= 0)) {
+
+        result = new String();
+      }
+      else if (returnTokens)
+        result = str.substring(start, ++current);
+
+      if (!returnTokens)
+        current++;
+    }
+
+    previous = start;
+    start = current;
+
+    if (result == null)
+      while (current < max && delim.indexOf(str.charAt(current)) < 0)
+        current++;
+
+    return result == null ? str.substring(start, current) : result;
+  }
+
+  /**
+   * Returns the next token in this string tokenizer's string. First, the
+   * set of characters considered to be delimiters by this Tokenizer
+   * object is changed to be the characters in the string delim.
+   * Then the next token in the string after the current position is
+   * returned. The current position is advanced beyond the recognized token.
+   * The new delimiter set remains the default after this call.
+   *
+   * @param delim the new delimiters
+   *
+   * @return the next token, after switching to the new delimiter set
+   *
+   * @exception NoSuchElementException  if there are no more tokens in this
+   *                                    tokenizer's string.
+   */
+  public String nextToken(String delim) throws NoSuchElementException {
+    this.delim = delim;
+    return nextToken();
+  }
+
+  /**
+   * Returns the same value as the hasMoreTokens method. It exists so that
+   * this class can implement the Enumeration interface.
+   *
+   * @return true if there are more tokens; false otherwise.
+   */
+  public boolean hasMoreElements() {
+    return hasMoreTokens();
+  }
+
+  /**
+   * Returns the same value as the nextToken method, except that its
+   * declared return value is Object rather than String. It exists so that
+   * this class can implement the Enumeration interface.
+   *
+   * @return the next token in the string
+   *
+   * @exception NoSuchElementException  if there are no more tokens in this
+   *                                    tokenizer's string
+   */
+  public Object nextElement() {
+    return nextToken();
+  }
+
+  /**
+   * Calculates the number of times that this tokenizer's nextToken method
+   * can be called before it generates an exception. The current position
+   * is not advanced.
+   *
+   * @return  the number of tokens remaining in the string using the
+   *          current delimiter set
+   */
+  public int countTokens() {
+    int curr = current;
+    int count = 0;
+
+    for (int i = curr; i < max; i++) {
+      if (delim.indexOf(str.charAt(i)) >= 0)
+        count++;
+
+      curr++;
+    }
+
+    return count + (returnTokens ? count : 0) + 1;
+  }
+
+  /**
+   * Resets this tokenizer's state so the tokenizing starts from the begin.
+   */
+  public void reset() {
+    previous = -1;
+    current = 0;
+  }
+
+  /**
+   * Constructs a string tokenizer for the specified string. All characters
+   * in the delim argument are the delimiters for separating tokens.
+   * If the returnTokens flag is true, then the delimiter characters are
+   * also returned as tokens. Each delimiter is returned as a string of
+   * length one. If the flag is false, the delimiter characters are skipped
+   * and only serve as separators between tokens. Then tokenizes the str
+   * and return an String[] array with tokens.
+   *
+   * @param str           a string to be parsed
+   * @param delim         the delimiters
+   * @param returnTokens  flag indicating whether to return the delimiters
+   *                      as tokens
+   *
+   * @return array with tokens
+   */
+  public static String[] tokenize(String str, String delim,
+    boolean returnTokens) {
+
+    Tokenizer tokenizer = new Tokenizer(str, delim, returnTokens);
+    String[] tokens = new String[tokenizer.countTokens()];
+
+    int i = 0;
+    while (tokenizer.hasMoreTokens()) {
+      tokens[i] = tokenizer.nextToken();
+      i++;
+    }
+
+    return tokens;
+  }
+
+  /**
+   * Default delimiters " \t\n\r\f":
+   * the space character, the tab character, the newline character,
+   * the carriage-return character, and the form-feed character.
+   */
+  public static final String DEFAULT_DELIMITERS = " \t\n\r\f";
+
+  /**
+   * String to tokenize.
+   */
+  private String str = null;
+
+  /**
+   * Delimiters.
+   */
+  private String delim = null;
+
+  /**
+   * Flag indicating whether to return the delimiters as tokens.
+   */
+  private boolean returnTokens = false;
+
+  /**
+   * Previous token start.
+   */
+  private int previous = -1;
+
+  /**
+   * Current position in str string.
+   */
+  private int current = 0;
+
+  /**
+   * Maximal position in str string.
+   */
+  private int max = 0;
+}

Propchange: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/Tokenizer.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/TraxErrorHandler.java
URL: http://svn.apache.org/viewcvs/cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/TraxErrorHandler.java?rev=330548&view=auto
==============================================================================
--- cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/TraxErrorHandler.java (added)
+++ cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/TraxErrorHandler.java Thu Nov  3 05:41:06 2005
@@ -0,0 +1,103 @@
+/*
+ * Copyright 1999-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.util;
+
+import org.apache.avalon.framework.logger.Logger;
+
+import javax.xml.transform.ErrorListener;
+import javax.xml.transform.SourceLocator;
+import javax.xml.transform.TransformerException;
+
+/**
+ * This ErrorListener simply logs the exception and in
+ * case of an fatal-error the exception is rethrown.
+ * Warnings and errors are ignored.
+ *
+ * @author <a href="mailto:cziegeler@apache.org">Carsten Ziegeler</a>
+ * @version CVS $Id: TraxErrorHandler.java 30941 2004-07-29 19:56:58Z vgritsenko $
+ */
+public class TraxErrorHandler implements ErrorListener {
+
+    private StringBuffer warnings = new StringBuffer("Errors in XSLT transformation:\n");
+    private Logger logger = null;
+
+    public TraxErrorHandler( Logger logger ) {
+        this.logger = logger;
+    }
+
+    public void warning( TransformerException exception )
+            throws TransformerException
+    {
+        final String message = getMessage( exception );
+        if ( this.logger != null ) {
+            this.logger.warn( message );
+        } else {
+            System.out.println( "WARNING: " + message );
+        }
+        warnings.append("Warning: ");
+        warnings.append(message);
+        warnings.append("\n");
+    }
+
+    public void error( TransformerException exception )
+            throws TransformerException
+    {
+        final String message = getMessage( exception );
+        if ( this.logger != null ) {
+            this.logger.error( message, exception );
+        } else {
+            System.out.println( "ERROR: " + message );
+        }
+        warnings.append("Error: ");
+        warnings.append(message);
+        warnings.append("\n");
+    }
+
+    public void fatalError( TransformerException exception )
+            throws TransformerException
+    {
+        final String message = getMessage( exception );
+        if ( this.logger != null ) {
+            this.logger.fatalError( message, exception );
+        } else {
+            System.out.println( "FATAL-ERROR: " + message );
+        }
+        warnings.append("Fatal: ");
+        warnings.append(message);
+        warnings.append("\n");
+        try {
+            throw new TransformerException(warnings.toString());
+        } finally {
+            warnings = new StringBuffer();
+        }
+    }
+
+    private String getMessage( TransformerException exception ) {
+
+        SourceLocator locator = exception.getLocator();
+        if ( null != locator ) {
+            String id = ( locator.getPublicId() != locator.getPublicId() )
+                    ? locator.getPublicId()
+                    : ( null != locator.getSystemId() )
+                    ? locator.getSystemId() : "SystemId Unknown";
+            return "File " + id
+                    + "; Line " + locator.getLineNumber()
+                    + "; Column " + locator.getColumnNumber()
+                    + "; " + exception.getMessage();
+        }
+        return exception.getMessage();
+    }
+}

Propchange: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/TraxErrorHandler.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/jxpath/DOMFactory.java
URL: http://svn.apache.org/viewcvs/cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/jxpath/DOMFactory.java?rev=330548&view=auto
==============================================================================
--- cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/jxpath/DOMFactory.java (added)
+++ cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/jxpath/DOMFactory.java Thu Nov  3 05:41:06 2005
@@ -0,0 +1,127 @@
+/*
+ * Copyright 1999-2004 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.util.jxpath;
+
+import org.apache.commons.jxpath.AbstractFactory;
+import org.apache.commons.jxpath.JXPathContext;
+import org.apache.commons.jxpath.Pointer;
+import org.w3c.dom.Attr;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+
+/**
+ * A <a href="http://jakarta.apache.org/commons/jxpath">JXPath</a> <code>AbstractFactory</code>
+ * that creates DOM elements.
+ *
+ * @author <a href="http://www.apache.org/~sylvain/">Sylvain Wallez</a>
+ * @version $Id: DOMFactory.java 149078 2005-01-29 22:26:58Z sylvain $
+ */
+
+public class DOMFactory extends AbstractFactory {
+
+    /**
+     * Return <b>false</b> if this factory cannot create the requested object.
+     */
+    public boolean createObject(
+        JXPathContext context,
+        Pointer pointer,
+        Object parent,
+        String name,
+        int index) 
+    {
+         //FIXME: JXPath automatically creates attributes if the element already exists,
+         //but does not call this method if the element does not exit 
+
+        addDOMElement((Node) parent, index, name);
+        
+        return true;
+    }
+
+    private void addDOMElement(Node parent, int index, String tag) {
+        int pos = tag.indexOf(':');
+        String prefix = null;
+        if (pos != -1) {
+            prefix = tag.substring(0, pos);
+        }
+        String uri = null;
+        
+        Node child = parent.getFirstChild();
+        int count = 0;
+        while (child != null) {
+            if (child.getNodeName().equals(tag)) {
+                count++;
+            }
+            child = child.getNextSibling();
+        }
+
+        Document doc = parent.getOwnerDocument();
+        
+        if (doc != null) {
+            uri = getNamespaceURI((Element)parent, prefix);
+        } else {
+            if (parent instanceof Document) {
+                doc = (Document)parent;
+                if (prefix != null) {
+                    throw new RuntimeException("Cannot map non-null prefix " +
+                        "when creating a document element");    
+                }
+            } else { // Shouldn't happen (must be a DocumentType object)
+                throw new RuntimeException("Node of class " +
+                    parent.getClass().getName() + " has null owner document " +
+                    "but is not a Document"); 
+            }
+
+        }
+
+        // Keep inserting new elements until we have index + 1 of them
+        while (count <= index) {
+            Node newElement = doc.createElementNS(uri, tag);
+            parent.appendChild(newElement);
+            count++;
+        }
+    }
+    
+    public String getNamespaceURI(Element element, String prefix) {
+        Node tmp = element;
+        String nsAttr = prefix == null ? "xmlns" : "xmlns:" + prefix;
+        
+        while (tmp != null && tmp.getNodeType() == Node.ELEMENT_NODE) {
+            element = (Element)tmp;
+            
+            // First test element prefixes
+            if (prefix == null) {
+                if (element.getPrefix() == null) {
+                    return element.getNamespaceURI();
+                }
+            } else if(prefix.equals(element.getPrefix())) {
+                return element.getNamespaceURI();
+            }
+            
+            // Note: stupid DOM api returns "" when an attribute doesn't exist, so we use the Attr node.
+            Attr nsAttrNode = ((Element)tmp).getAttributeNode(nsAttr);
+            if (nsAttrNode != null) {
+                return nsAttrNode.getValue();
+            }
+            tmp = tmp.getParentNode();
+        }
+        return null;
+    }
+
+    public boolean declareVariable(JXPathContext context, String name) {
+        return false;
+    }
+}

Propchange: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/jxpath/DOMFactory.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/jxpath/NamespacesTablePointer.java
URL: http://svn.apache.org/viewcvs/cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/jxpath/NamespacesTablePointer.java?rev=330548&view=auto
==============================================================================
--- cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/jxpath/NamespacesTablePointer.java (added)
+++ cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/jxpath/NamespacesTablePointer.java Thu Nov  3 05:41:06 2005
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.util.jxpath;
+
+import org.apache.cocoon.xml.NamespacesTable;
+import org.apache.commons.jxpath.ri.QName;
+import org.apache.commons.jxpath.ri.model.NodeIterator;
+import org.apache.commons.jxpath.ri.model.NodePointer;
+
+/**
+ * A JXPath <code>Pointer</code> that tracks namespaces defined by a {@link NamespacesTable}.
+ * This class is to be used to inform JXPath of the namespaces declared in a host environment
+ * (e.g. JXTemplateGenerator) using
+ * <a href="http://jakarta.apache.org/commons/jxpath/apidocs/org/apache/commons/jxpath/JXPathContext.html#setNamespaceContextPointer(org.apache.commons.jxpath.Pointer)">JXPathContext.setNamespaceContextPointer()</a>.
+ * 
+ * @since 2.1.8
+ * @version $Id: NamespacesTablePointer.java 231269 2005-08-10 15:43:57Z sylvain $
+ */
+public class NamespacesTablePointer extends NodePointer {
+    
+    private NamespacesTable namespaces;
+
+    public NamespacesTablePointer(NamespacesTable namespaces) {
+        super(null);
+        this.namespaces = namespaces;
+    }
+
+    public String getNamespaceURI(String prefix) {
+        return namespaces.getUri(prefix);
+    }
+
+    protected String getDefaultNamespaceURI() {
+        return namespaces.getUri("");
+    }
+
+    public NodeIterator namespaceIterator() {
+        return null;
+    }
+    
+    //-------------------------------------------------------------------------
+    // Dummy implementation of abstract methods
+    //-------------------------------------------------------------------------
+
+    public boolean isLeaf() {
+        return true;
+    }
+
+    public boolean isCollection() {
+        return false;
+    }
+
+    public int getLength() {
+        return 0;
+    }
+
+    public QName getName() {
+        return null;
+    }
+
+    public Object getBaseValue() {
+        return null;
+    }
+
+    public Object getImmediateNode() {
+        return null;
+    }
+
+    public void setValue(Object value) {
+        // ignore
+    }
+
+    public int compareChildNodePointers(NodePointer arg0, NodePointer arg1) {
+        return -1;
+    }
+}

Propchange: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/jxpath/NamespacesTablePointer.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/Locatable.java
URL: http://svn.apache.org/viewcvs/cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/Locatable.java?rev=330548&view=auto
==============================================================================
--- cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/Locatable.java (added)
+++ cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/Locatable.java Thu Nov  3 05:41:06 2005
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2005 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.util.location;
+
+/**
+ * A interface that should be implemented by objects knowning their location (i.e. where they
+ * have been created from).
+ * 
+ * @since 2.1.8
+ * @version $Id: Locatable.java 233343 2005-08-18 18:06:44Z sylvain $
+ */
+public interface Locatable {
+    /**
+     * Get the location of this object
+     * 
+     * @return the location
+     */
+    Location getLocation();
+}

Propchange: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/Locatable.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/LocatableException.java
URL: http://svn.apache.org/viewcvs/cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/LocatableException.java?rev=330548&view=auto
==============================================================================
--- cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/LocatableException.java (added)
+++ cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/LocatableException.java Thu Nov  3 05:41:06 2005
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2005 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.util.location;
+
+/**
+ * Extension of {@link Locatable} for exceptions.
+ * <p>
+ * In order to dump location information in the stacktrace, the <code>getMessage()</code> method of
+ * a {@link Locatable} exception should return a concatenation of the raw message (given in the
+ * constructor) and the exception's location, e.g. "<code>foo failed (file.xml:12:3)</code>". However,
+ * {@link Locatable}-aware classes will want to handle the raw message (i.e. "<code>foo failed</code>")
+ * and location separately. This interface gives access to the raw message.
+ * <p>
+ * <strong>Note:</strong> care should be taken for locatable exceptions to use only immutable and
+ * serializable implementations of {@link Location} ({@see org.apache.cocoon.util.location.LocationImpl#get(Location)}).
+ * 
+ * @since 2.1.8
+ * @version $Id: LocatableException.java 233343 2005-08-18 18:06:44Z sylvain $
+ */
+public interface LocatableException extends Locatable {
+    
+    /**
+     * Get the raw message of the exception (the one used in the constructor)
+     * 
+     * @return the raw message
+     */
+    public String getRawMessage();
+}

Propchange: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/LocatableException.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/LocatedException.java
URL: http://svn.apache.org/viewcvs/cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/LocatedException.java?rev=330548&view=auto
==============================================================================
--- cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/LocatedException.java (added)
+++ cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/LocatedException.java Thu Nov  3 05:41:06 2005
@@ -0,0 +1,154 @@
+/*
+ * Copyright 2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.util.location;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.commons.lang.exception.ExceptionUtils;
+import org.apache.commons.lang.exception.NestableException;
+
+/**
+ * A cascading and located <code>Exception</code>. It is also {@link MultiLocatable} to easily build
+ * stack traces.
+ *
+ * @since 2.1.8
+ * @version $Id: LocatedException.java 291771 2005-09-26 22:32:55Z vgritsenko $
+ */
+public class LocatedException extends NestableException
+                              implements LocatableException, MultiLocatable {
+
+    private List locations;
+
+    public LocatedException(String message) {
+        this(message, null, null);
+    }
+
+    public LocatedException(String message, Throwable cause) {
+        this(message, cause, null);
+    }
+
+    public LocatedException(String message, Location location) {
+        this(message, null, location);
+    }
+
+    public LocatedException(String message, Throwable cause, Location location) {
+        super(message, cause);
+        ensureCauseChainIsSet(cause);
+        addCauseLocations(this, cause);
+        addLocation(location);
+    }
+
+    /**
+     * Crawl the cause chain and ensure causes are properly set using {@ link Throwable#initCause}.
+     * This is needed because some exceptions (e.g. SAXException) don't have a {@ link Throwable#getCause}
+     * that is used to print stacktraces.
+     */
+    public static void ensureCauseChainIsSet(Throwable thr) {
+        // Loop either until null or encountering exceptions that use this method.
+        while (thr != null && !(thr instanceof LocatedRuntimeException) && !(thr instanceof LocatedException)) {
+            Throwable parent = ExceptionUtils.getCause(thr);
+            if (thr.getCause() == null && parent != null) {
+                thr.initCause(parent);
+            }
+            thr = parent;
+        }
+    }
+
+    /**
+     * Add to the location stack all locations of an exception chain. This allows to have all possible
+     * location information in the stacktrace, as some exceptions like SAXParseException don't output
+     * their location in printStackTrace().
+     * <p>
+     * Traversal of the call chain stops at the first <code>Locatable</code> exception which is supposed
+     * to handle the loction of its causes by itself.
+     * <p>
+     * This method is static as a convenience for {@link LocatedRuntimeException other implementations}
+     * of locatable exceptions.
+     *
+     * @param self the current locatable exception
+     * @param cause a cause of <code>self</code>
+     */
+    public static void addCauseLocations(MultiLocatable self, Throwable cause) {
+        if (cause == null || cause instanceof Locatable) {
+            // Locatable handles its location itself
+            return;
+        }
+        // Add parent location first
+        addCauseLocations(self, ExceptionUtils.getCause(cause));
+        // then ourselve's
+        Location loc = LocationUtils.getLocation(cause);
+        if (LocationUtils.isKnown(loc)) {
+            // Get the exception's short name
+            String name = cause.getClass().getName();
+            int pos = name.lastIndexOf('.');
+            if (pos != -1) {
+                name = name.substring(pos+1);
+            }
+            loc = new LocationImpl("[" + name + "]", loc.getURI(), loc.getLineNumber(), loc.getColumnNumber());
+            self.addLocation(loc);
+        }
+    }
+
+    public Location getLocation() {
+        return locations == null ? null : (Location)locations.get(0);
+    }
+
+    public List getLocations() {
+        return locations == null ? Collections.EMPTY_LIST : locations;
+    }
+
+    public String getRawMessage() {
+        return super.getMessage();
+    }
+
+    /**
+     * Standard way of building the message of a {@link LocatableException}, as a Java-like
+     * stack trace of locations.
+     *
+     * @param message the exception's message, given by <code>super.getMessage()</code> (can be null)
+     * @param locations the location list (can be null)
+     *
+     * @return the message, or <code>null</code> no message and locations were given.
+     */
+    public static String getMessage(String message, List locations) {
+        if (locations == null || locations.isEmpty()) {
+            return message;
+        }
+
+        // Produce a Java-like stacktrace with locations
+        StringBuffer buf = message == null ? new StringBuffer() : new StringBuffer(message);
+        for (int i = 0; i < locations.size(); i++) {
+            buf.append("\n\tat ").append(LocationUtils.toString((Location)locations.get(i)));
+        }
+        return buf.toString();
+    }
+
+    public String getMessage() {
+        return getMessage(super.getMessage(), locations);
+    }
+
+    public void addLocation(Location loc) {
+        if (LocationUtils.isUnknown(loc))
+            return;
+
+        if (locations == null) {
+            this.locations = new ArrayList(1); // Start small
+        }
+        locations.add(LocationImpl.get(loc));
+    }
+}

Propchange: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/LocatedException.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/LocatedRuntimeException.java
URL: http://svn.apache.org/viewcvs/cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/LocatedRuntimeException.java?rev=330548&view=auto
==============================================================================
--- cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/LocatedRuntimeException.java (added)
+++ cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/LocatedRuntimeException.java Thu Nov  3 05:41:06 2005
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2005 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.util.location;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.commons.lang.exception.NestableRuntimeException;
+
+/**
+ * A cascading and located <code>RuntimeException</code>. It is also {@link MultiLocatable} to easily build
+ * location stack traces.
+ * <p>
+ * If a <code>LocatedRuntimeException</code> is built with a location and a cause which is also a
+ * <code>LocatedRuntimeException</code>, then the default behavior is to add the location to the cause
+ * exception and immediately rethrow the cause. This avoids exception nesting and builds a location
+ * stack.
+ * 
+ * @since 2.1.8
+ * @version $Id: LocatedRuntimeException.java 290845 2005-09-21 22:04:27Z sylvain $
+ */
+public class LocatedRuntimeException extends NestableRuntimeException implements LocatableException, MultiLocatable {
+    
+    private List locations;
+
+    public LocatedRuntimeException(String message) {
+        this(message, null, null, true);
+    }
+    
+    public LocatedRuntimeException(String message, Throwable cause) throws LocatedRuntimeException {
+        this(message, cause, null, true);
+    }
+    
+    public LocatedRuntimeException(String message, Location location) {
+        this(message, null, location, true);
+    }
+    
+    public LocatedRuntimeException(String message, Throwable cause, Location location) throws LocatedRuntimeException {
+        this(message, cause, location, true);
+    }
+
+    public LocatedRuntimeException(String message, Throwable cause, Location location, boolean rethrowLocated)
+        throws LocatedRuntimeException {
+        super(message, cause);
+        if (rethrowLocated && cause instanceof LocatedRuntimeException) {
+            LocatedRuntimeException lreCause = (LocatedRuntimeException)cause;
+            lreCause.addLocation(location);
+            // Rethrow the cause
+            throw lreCause;
+        }
+
+        LocatedException.ensureCauseChainIsSet(cause);
+        LocatedException.addCauseLocations(this, cause);
+        addLocation(location);
+    }
+
+    public Location getLocation() {
+        return locations == null ? null : (Location)locations.get(0);
+    }
+
+    public List getLocations() {
+        return locations == null ? Collections.EMPTY_LIST : locations;
+    }
+
+    public String getRawMessage() {
+        return super.getMessage();
+    }
+
+    public String getMessage() {
+        return LocatedException.getMessage(super.getMessage(), locations);
+    }
+    
+    public void addLocation(Location loc) {
+        if (LocationUtils.isUnknown(loc))
+            return;
+
+        if (locations == null) {
+            this.locations = new ArrayList(1); // Start small
+        }
+        locations.add(LocationImpl.get(loc));
+    }
+}

Propchange: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/LocatedRuntimeException.java
------------------------------------------------------------------------------
    svn:eol-style = native

Added: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/Location.java
URL: http://svn.apache.org/viewcvs/cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/Location.java?rev=330548&view=auto
==============================================================================
--- cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/Location.java (added)
+++ cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/Location.java Thu Nov  3 05:41:06 2005
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2005 The Apache Software Foundation.
+ * 
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * 
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ * 
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.cocoon.util.location;
+
+
+/**
+ * A location in a resource. The location is composed of the URI of the resource, and 
+ * the line and column numbers within that resource (when available), along with a description.
+ * <p>
+ * Locations are mostly provided by {@link Locatable}s objects.
+ * 
+ * @since 2.1.8
+ * @version $Id: Location.java 233343 2005-08-18 18:06:44Z sylvain $
+ */
+public interface Location {
+    
+    /**
+     * Constant for unknown locations.
+     */
+    public static final Location UNKNOWN = LocationImpl.UNKNOWN;
+    
+    /**
+     * Get the description of this location
+     * 
+     * @return the description (can be <code>null</code>)
+     */
+    public String getDescription();
+    
+    /**
+     * Get the URI of this location
+     * 
+     * @return the URI (<code>null</code> if unknown).
+     */
+    public String getURI();
+    /**
+     * Get the line number of this location
+     * 
+     * @return the line number (<code>-1</code> if unknown)
+     */
+    public int getLineNumber();
+    
+    /**
+     * Get the column number of this location
+     * 
+     * @return the column number (<code>-1</code> if unknown)
+     */
+    public int getColumnNumber();
+
+}

Propchange: cocoon/whiteboard/maven2/cocoon-flat-layout/cocoon-core/src/main/java/org/apache/cocoon/util/location/Location.java
------------------------------------------------------------------------------
    svn:eol-style = native