/*
 * $Header: /globals/hci1/projects/VKC3/src/vkc/webdav/URLUtil.java,v 1.8 2005/02/11 09:26:54 lawern Exp $
 * $Revision: 1.8 $
 * $Date: 2005/02/11 09:26:54 $
 *
 * ====================================================================
 *
 * The Apache Software License, Version 1.1
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution, if
 *    any, must include the following acknowlegement:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowlegement may appear in the software itself,
 *    if and wherever such third-party acknowlegements normally appear.
 *
 * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
 *    Foundation" must not be used to endorse or promote products derived
 *    from this software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache"
 *    nor may "Apache" appear in their names without prior written
 *    permission of the Apache Group.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 * [Additional notices, if required by prior licensing conditions]
 *
 */
package vkc.webdav;

import vkc.misc.VKCLogManager;

import vkc.util.VKCStringUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import java.text.SimpleDateFormat;

import java.util.BitSet;
import java.util.TimeZone;


/**
 * General purpose request parsing and encoding utility methods.
 *
 * @author Craig R. McClanahan
 * @author Tim Tye
 * @author Remy Maucherat
 * @version $Revision: 1.8 $ $Date: 2005/02/11 09:26:54 $
 */
public final class URLUtil {
    // -------------------------------------------------------------- Variables

    /**
     * The DateFormat to use for generating readable dates in cookies.
     */
    private static SimpleDateFormat format = new SimpleDateFormat(
            " EEEE, dd-MMM-yy kk:mm:ss zz");

    /**
     * Array containing the safe characters set.
     */
    protected static BitSet safeCharacters;
    protected static final char[] hexadecimal = {
            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
            'E', 'F'
        };

    // ----------------------------------------------------- Static Initializer
    static {
        format.setTimeZone(TimeZone.getTimeZone("GMT"));

        safeCharacters = new BitSet(256);

        int i;

        for (i = 'a'; i <= 'z'; i++) {
            safeCharacters.set(i);
        }

        for (i = 'A'; i <= 'Z'; i++) {
            safeCharacters.set(i);
        }

        for (i = '0'; i <= '9'; i++) {
            safeCharacters.set(i);
        }

        safeCharacters.set('-');
        safeCharacters.set('_');
        safeCharacters.set('.');
        safeCharacters.set('*');
        safeCharacters.set('/');
    }

    // --------------------------------------------------------- Public Methods

    /**
     * Decode and return the specified URL-encoded String.
     * When the byte array is converted to a string, the system default
     * character encoding is used...  This may be different than some other
     * servers.
     *
     * @param str The url-encoded string
     *
     * @exception IllegalArgumentException if a '%' character is not followed
     * by a valid 2-digit hexadecimal number
     */
    public static String URLDecode(String str) {
        return URLDecode(str, null);
    }

    /**
     * Decode and return the specified URL-encoded String.
     *
     * @param str The url-encoded string
     * @param enc The encoding to use; if null, the default encoding is used
     * @exception IllegalArgumentException if a '%' character is not followed
     * by a valid 2-digit hexadecimal number
     */
    public static String URLDecode(String str, String enc) {
        if (str == null) {
            return (null);
        }

        // FIXME: replace all byte[] by char[]
        byte[] bytes;

        if (enc == null) {
            bytes = str.getBytes();
        } else {
            try {
                bytes = str.getBytes(enc);
            } catch (UnsupportedEncodingException ex) {
                bytes = str.getBytes();
            }
        }

        return URLDecode(bytes, enc);
    }

    /**
     * Decode and return the specified URL-encoded byte array.
     *
     * @param bytes The url-encoded byte array
     * @exception IllegalArgumentException if a '%' character is not followed
     * by a valid 2-digit hexadecimal number
     */
    public static String URLDecode(byte[] bytes) {
        return URLDecode(bytes, null);
    }

    /**
     * Decode and return the specified URL-encoded byte array.
     *
     * @param bytes The url-encoded byte array
     * @param enc The encoding to use; if null, the default encoding is used
     * @exception IllegalArgumentException if a '%' character is not followed
     * by a valid 2-digit hexadecimal number
     */
    public static String URLDecode(byte[] bytes, String enc) {
        if (bytes == null) {
            return (null);
        }

        int len = bytes.length;
        int ix = 0;
        int ox = 0;

        while (ix < len) {
            byte b = bytes[ix++]; // Get byte to test

            if (b == '+') {
                b = (byte) ' ';
            } else if (b == '%') {
                b = (byte) ((convertHexDigit(bytes[ix++]) << 4) +
                    convertHexDigit(bytes[ix++]));
            }

            bytes[ox++] = b;
        }

        if (enc != null) {
            try {
                return new String(bytes, 0, ox, enc);
            } catch (Exception e) {
                VKCLogManager.errorLog(URLUtil.class, "", e.getMessage(), e);
            }
        }

        return new String(bytes, 0, ox);
    }

    /**
     * Convert a byte character value to hexidecimal digit value.
     *
     * @param b the character value byte
     */
    private static byte convertHexDigit(byte b) {
        if ((b >= '0') && (b <= '9')) {
            return (byte) (b - '0');
        }

        if ((b >= 'a') && (b <= 'f')) {
            return (byte) (b - 'a' + 10);
        }

        if ((b >= 'A') && (b <= 'F')) {
            return (byte) (b - 'A' + 10);
        }

        return 0;
    }

    /**
     * URL rewriter.
     *
     * @param path Path which has to be rewiten
     */
    public static String URLEncode(String path, String enc) {
        /**
         * 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.
         */
        String filteredPath = VKCStringUtils.decodeXmlEntities(path);
        int maxBytesPerChar = 10;
        StringBuffer rewrittenPath = new StringBuffer(filteredPath.length());
        ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
        OutputStreamWriter writer = null;

        try {
            // FIXME: Use the same encoding as the one specified above
            writer = new OutputStreamWriter(buf, enc);
        } catch (Exception e) {
            //VKCLogManager.errorLog(this, "", e.getMessage(),e);
            writer = new OutputStreamWriter(buf);
        }

        for (int i = 0; i < filteredPath.length(); i++) {
            int c = filteredPath.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();
    }

    /**
     * Encodes filenames for Content-Disposition header field.
     *
     * @param path filename
     */
    public static String contentDispositionEncode(String path) {
        /**
         * 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.
         */
        String filteredPath = VKCStringUtils.decodeXmlEntities(path);
        int maxBytesPerChar = 10;
        StringBuffer rewrittenPath = new StringBuffer(filteredPath.length());
        ByteArrayOutputStream buf = new ByteArrayOutputStream(maxBytesPerChar);
        OutputStreamWriter writer = null;

        try {
            // FIXME: Use the same encoding as the one specified above
            writer = new OutputStreamWriter(buf, "UTF-8");
        } catch (Exception e) {
            //VKCLogManager.errorLog(this, "", e.getMessage(),e);
            writer = new OutputStreamWriter(buf);
        }

        for (int i = 0; i < filteredPath.length(); i++) {
            int c = filteredPath.charAt(i);

            if ((c < 256) && (c != 34) && (c != 37)) {
                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();
    }
}
