/*
 * Copyright (c) 2017 XMLmind Software. All rights reserved. 
 *
 * Author: Hussein Shafie
 *
 * This file is part of the XMLmind W2X project.
 * For conditions of distribution and use, see the accompanying legal.txt file.
 */
package com.xmlmind.w2x_servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xmlmind.util.URLUtil;

/*package*/ final class ReqUtil {
    private ReqUtil() {}

    /**
     * Initializes the character encoding of specified requests. 
     * <p>Uses UTF-8 unless the character encoding is specified in
     * the content type of the request.
     * <p>Must be invoked before actually accessing the request.
     * @exception UnsupportedEncodingException if the character encoding 
     * that is to be used is not supported by the Java runtime 
     * (this is unlikely to happen).
     */
    public static void setCharacterEncoding(HttpServletRequest req) 
        throws UnsupportedEncodingException {
        String charset = null;

        String contentType = req.getContentType();
        if (contentType != null) {
            charset = URLUtil.contentTypeToCharset(contentType);
        }

        if (charset == null) {
            // Our own forms always use UTF-8.
            charset = "UTF-8";
        }
        req.setCharacterEncoding(charset);
    }

    // -----------------------------------------------------------------------

    public static String getString(HttpServletRequest req, 
                                   String key, String fallback) {
        String value = req.getParameter(key);

        if (value == null || (value = value.trim()).length() == 0) {
            value = fallback;
        }

        return value;
    }

    // -----------------------------------------------------------------------

    public static boolean getBoolean(HttpServletRequest req, 
                                     String key, boolean fallback) {
        String value = getString(req, key, null);

        if (value != null) {
            if (value.equals("true")) {
                return true;
            } else if (value.equals("false")) {
                return false;
            }
        }

        return fallback;
    }
}
