/* UtilLib_Servlet - Copyright (c) 2010-2021 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.mapeadores.util.servlets;

import java.io.File;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import net.mapeadores.util.annotation.Nullable;


/**
 *
 * @author Vincent Calame
 */
public final class ServletUtils {

    private ServletUtils() {
    }

    @Nullable
    public static String getInitParameter(ServletContext servletContext, String name) {
        String value = servletContext.getInitParameter(name);
        if (value == null) {
            return null;
        }
        value = value.trim();
        if (value.length() == 0) {
            return null;
        }
        return value;
    }

    public static boolean getBooleanInitParameter(ServletContext servletContext, String name) {
        String value = servletContext.getInitParameter(name);
        if (value == null) {
            return false;
        }
        value = value.trim().toLowerCase();
        switch (value) {
            case "true":
            case "on":
            case "1":
                return true;
            default:
                return false;
        }
    }

    public static String getServletContextName(ServletContext servletContext) {
        String contextPath = servletContext.getContextPath();
        if (contextPath.length() == 0) {
            return "ROOT";
        } else {
            return contextPath.substring(1);
        }
    }

    public static String getFullUrl(String canonicalUrl, HttpServletRequest request) {
        if (canonicalUrl.length() > 0) {
            String pathInfo = request.getPathInfo();
            StringBuilder buf = new StringBuilder(canonicalUrl);
            if ((pathInfo != null) && (pathInfo.length() > 1)) {
                buf.append(pathInfo, 1, pathInfo.length());
            }
            String queryString = request.getQueryString();
            if (queryString != null) {
                buf.append("?").append(queryString);
            }
            return buf.toString();
        } else {
            StringBuffer requestURL = request.getRequestURL();
            String queryString = request.getQueryString();
            if (queryString == null) {
                requestURL.append('?').append(queryString);
            }
            return requestURL.toString();
        }
    }

    @Nullable
    public static File getRealFile(ServletContext servletContext, String path) {
        String realPath = servletContext.getRealPath(path);
        if (realPath == null) {
            return null;
        }
        File file = new File(realPath);
        if (!file.exists()) {
            return null;
        }
        return file;
    }

}
