/*
 * $Id: ResponseUtils.java 471754 2006-11-06 14:55:09Z husted $
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.struts.util;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * General purpose utility methods related to generating a servlet response in
 * the Struts controller framework.
 *
 * @version $Rev: 471754 $ $Date: 2005-08-21 14:46:28 -0400 (Sun, 21 Aug 2005)
 *          $
 */
public final class ResponseUtils {

    /**
     * Commons logging instance.
     */
    private static final Log LOG = LogFactory.getLog(ResponseUtils.class);

    /**
     * Constructor
     */
    private ResponseUtils() {
        throw new AssertionError();
    }

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

    /**
     * Filter the specified string for characters that are senstive to HTML
     * interpreters, returning the string with these characters replaced by
     * the corresponding character entities.
     * @param value The string to be filtered and returned
     * @return String
     */
    public static String filter(final String value) {
        if ((value == null) || (value.isEmpty())) {
            return value;
        }

        StringBuilder result = null;

        for (int i = 0; i < value.length(); i++) {
            String filtered = null;

            switch (value.charAt(i)) {
                case '<':
                    filtered = "&lt;";
                    break;

                case '>':
                    filtered = "&gt;";
                    break;

                case '&':
                    filtered = "&amp;";
                    break;

                case '"':
                    filtered = "&quot;";
                    break;

                case '\'':
                    filtered = "&#39;";
                    break;

                default:
                    break;
            }

            if (result == null) {
                if (filtered != null) {
                    result = new StringBuilder(value.length() + 50);

                    if (i > 0) {
                        result.append(value.substring(0, i));
                    }

                    result.append(filtered);
                }
            } else {
                if (filtered == null) {
                    result.append(value.charAt(i));
                } else {
                    result.append(filtered);
                }
            }
        }

        return (result == null) ? value : result.toString();
    }

    /**
     * URLencodes a string assuming the character encoding is UTF-8.
     *
     * @param url String
     * @return String The encoded url in UTF-8
     */
    public static String encodeURL(final String url) {
        return encodeURL(url, "UTF-8");
    }

    /**
     * Use the new URLEncoder.encode() method from Java 1.4 if available, else
     * use the old deprecated version.  This method uses reflection to find
     * the appropriate method; if the reflection operations throw exceptions,
     * this will return the url encoded with the old URLEncoder.encode()
     * method.
     * @param url String
     * @param enc The character encoding the urlencode is performed on.
     * @return String The encoded url.
     */
    public static String encodeURL(final String url, final String enc) {
        try {
            String e = enc;
            if ((e == null) || (e.isEmpty())) {
                e = "UTF-8";
            }
            return URLEncoder.encode(url, e);
        } catch (final UnsupportedEncodingException e) {
            LOG.debug("UnsupportedEncodingException", e);
            throw new RuntimeException(e);
        }
    }

    /**
     * <p>Return the <code>Class</code> object for the specified fully
     * qualified class name, from this web application's class loader.</p>
     * @param <T> Type
     * @param className Fully qualified class name to be loaded
     * @return Class object
     * @throws ReflectiveOperationException if the class cannot be found
     */
    public static <T> Class<T> applicationClass(final String className)
            throws ReflectiveOperationException {
        return cast(applicationClass(className, null));
    }

    /**
     * <p>Return the <code>Class</code> object for the specified fully
     * qualified class name, from this web application's class loader.</p>
     *
     * @param className   Fully qualified class name to be loaded
     * @param classLoader The desired classloader to use
     * @return Class object
     * @throws ReflectiveOperationException if the class cannot be found
     */
    public static Class<?> applicationClass(final String className,
            final ClassLoader classLoader) throws ReflectiveOperationException {
        ClassLoader cl = classLoader;
        if (cl == null) {
            // Look up the class loader to be used
            cl = Thread.currentThread().getContextClassLoader();

            if (cl == null) {
                cl = RequestUtils.class.getClassLoader();
            }
        }

        // Attempt to load the specified class
        return cl.loadClass(className);
    }

    /**
     * <p>Return a new instance of the specified fully qualified class name,
     * after loading the class from this web application's class loader. The
     * specified class <strong>MUST</strong> have a public zero-arguments
     * constructor.</p>
     * @param <T> Type
     * @param className Fully qualified class name to use
     * @return new instance of class
     * @throws ReflectiveOperationException ReflectiveOperationException
     */
    public static <T> T applicationInstance(final String className)
            throws ReflectiveOperationException {

        return cast(applicationInstance(className, null));
    }

    /**
     * <p>Return a new instance of the specified fully qualified class name,
     * after loading the class from this web application's class loader. The
     * specified class <strong>MUST</strong> have a public zero-arguments
     * constructor.</p>
     * @param <T> Type
     * @param className   Fully qualified class name to use
     * @param classLoader The desired classloader to use
     * @return new instance of class
     * @throws ReflectiveOperationException ReflectiveOperationException
     */
    public static <T> T applicationInstance(final String className,
            final ClassLoader classLoader)
            throws ReflectiveOperationException {

        return cast(applicationClass(className, classLoader).newInstance());
    }

    /**
     * cast
     * @param <T> generic
     * @param obj target
     * @return casted
     */
    @SuppressWarnings("unchecked")
    private static <T> T cast(final Object obj) {
        return (T) obj;
    }
}
