/*
 * $Id: ServletUtils.java,v 1.24 2006/10/04 03:15:20 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: ServletUtils.java,v $
 * Revision 1.24  2006/10/04 03:15:20  marbobo
 * + Vollständige Unterstützung für Templates implementiert
 * + Alles von Virtoweb auf ProCoBa umgestellt
 *
 * Revision 1.23  2005/03/24 12:57:05  marbobo
 * + Unnötige Anweisungen entfernt
 *
 * Revision 1.22  2005/02/14 14:01:57  bigmac
 * Applikationsweites CSS konfigurierbar gemacht + Refactorings
 *
 * Revision 1.21  2005/02/09 08:57:01  bigmac
 * +removeSessionID()
 *
 * Revision 1.20  2004/11/10 15:02:47  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.19  2004/10/31 03:00:04  marbobo
 * - Unnötige Methode entfernt
 *
 * Revision 1.18  2004/08/20 12:56:41  koppy
 * +printAttributes(...)
 *
 * Revision 1.17  2004/06/07 11:15:05  jonyp
 * delete obsolete method
 *
 * Revision 1.16  2004/03/07 13:36:57  bigmac
 * überflüssige Methode getDocumentTypes() gelöscht
 *
 * Revision 1.15  2004/03/02 23:05:48  bigmac
 * Anpassungen an VKCDocumentSerializer und VKCCategorySerializer
 *
 * Revision 1.14  2004/02/09 13:20:23  bigmac
 * *** empty log message ***
 *
 * Revision 1.13  2004/01/29 15:33:51  jonyp
 * commented out: retrieve acls after retrieveCategories
 *
 * Revision 1.12  2003/12/24 10:11:59  bigmac
 * Projektweite Import-Optimierung
 *
 * Revision 1.11  2003/09/08 16:59:06  marbobo
 * *** empty log message ***
 *
 * Revision 1.10  2003/08/02 16:14:06  bigmac
 * *** empty log message ***
 *
 * Revision 1.9  2003/07/31 01:21:04  koppy
 * + markCutOutItems(..)
 *
 * Revision 1.8  2003/04/15 12:52:48  vchris
 * ...
 *
 * Revision 1.7  2003/04/15 12:04:49  vchris
 * ...
 *
 * Revision 1.6  2003/04/15 11:59:22  koppy
 * + getCategory(..)
 *
 * Revision 1.5  2003/03/03 22:53:42  koppy
 * Kleinigkeiten, bugfixes
 *
 * Revision 1.4  2003/01/29 03:23:37  koppy
 * ACLs + Versionierung
 *
 * Revision 1.3  2003/01/12 22:31:22  koppy
 * <No Comment Entered>
 *
 * Revision 1.2  2002/11/04 02:02:47  koppy
 * long --> Integer
 *
 * Revision 1.1  2002/10/21 14:36:27  bigmac
 * *** empty log message ***
 *
 * Revision 1.1  2002/10/21 13:51:04  koppy
 * Initiale Version
 *
 */
package vkc.util;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.PageContext;

import org.apache.commons.beanutils.BeanUtils;

import vkc.db.entities.VKCUser;
import vkc.misc.VKCLogManager;
import vkc.view.WebShare;

public final class ServletUtils {
	/**
	 * Returns the servlet path + ? + query string
	 *
	 * @param request
	 *
	 * @return smth. like /admin/EditCategory.jsp?create=true&asdfad=fad....
	 */
	public static final String getRequestedPath(HttpServletRequest request) {
		StringBuffer path = new StringBuffer();
		
		path.append(request.getServletPath());

		if (request.getQueryString() != null) {
			path.append("?");

			path.append(request.getQueryString());
		}

		return path.toString();
	}

	/**
	 * Forwards to a JSP page
	 *
	 * @param pageContext under this page context
	 * @param path the path of the page to forward to
	 * @throws JspTagException if something goes wrong
	 */
	public static final void jspForward(PageContext pageContext, String path)
		throws JspTagException {

		try {
			pageContext.forward(path);

		} catch (Exception e) {
			VKCLogManager.errorLog(ServletUtils.class, "", e.getMessage(), e);
			throw new JspTagException("Exception while forwarding to " + path + " : " + e.toString());
		}
	}

	/**
	 * Liefert den momentan eingeloggten User aus dem Session scope
	 *
	 * @param request
	 * @return null, falls nicht vorhanden, sonst Referenz auf VKCUser
	 */
	public static final VKCUser getUser(HttpServletRequest request) {
		return (VKCUser) request.getSession().getAttribute(WebShare.USER_KEY);
	}

    public static void removeSessionAttributes(HttpSession session) {
        try {
            Vector v = new Vector();
            String s = null;

            Enumeration e = session.getAttributeNames();

            while (e.hasMoreElements()) {
                s = e.nextElement().toString();
                v.add(s);
            }

            for (int i = 0; i < v.size(); i++) {
                session.removeAttribute(v.elementAt(i).toString());
            }
        } catch (Exception ex) {
            VKCLogManager.errorLog(ServletUtils.class, "", ex.getMessage(), ex);
        }
    }

	/**
	 * Liefert alle Requestparameter als Vector zurück
	 * @param request
	 * @return
	 */
	public static HashMap getRequestedParameters(HttpServletRequest request) {
		HashMap parameters = new HashMap();
		
		if (request.getQueryString() != null) {
			Vector params = VKCStringUtils.stringToVector(request.getQueryString(), "&");
			
			for (int i = 0; i < params.size(); i++) {
				String param = (String)params.elementAt(i);
				String paramName = "";
				String paramValue = "";
				int index = param.indexOf("=");
				
				if (index != -1) {
					paramName  = param.substring(0, index);
					paramValue = param.substring(index + 1, param.length());
					
				} else {
					paramName = param;
				}
				
				RequestParameter requestParam = new RequestParameter(paramName, paramValue);
				parameters.put(paramName, requestParam);
			}
		}
		
		return parameters;
	}

    /**
     * @param servletContext
     */
    public static void printAttributes(ServletContext servletContext) {
        Enumeration e = servletContext.getAttributeNames();
        
        while (e.hasMoreElements()) {
            String elem = (String)e.nextElement();
            System.out.println("  " + elem + " --> " + servletContext.getAttribute(elem));
        }
        
    }
    
    /**
     * Methode löscht die SessionID aus einem Ressourcen-Pfad
     */
    public final static String removeSessionID(String resource) {
    	if (resource == null) {
    		return resource;
    	}
    	
    	int indexID = resource.indexOf(";jsessionid=");
    	
    	if (indexID < 0) {
    		return resource;
    	}
    	
    	int indexQM = resource.indexOf("?", indexID);
    	
    	if (indexQM < 0) {
    		return resource.substring(0, indexID);
    	} 

    	return resource.substring(0, indexID) + resource.substring(indexQM);
    }

    public static String replacePathVars(String path, VKCUser user) {
		if (path == null || path.indexOf("${") < 0) {
			return path; // nothing to replace
		}

		if (user == null) {
			path = StringUtils.replaceToken(path, "${template.name}", WebShare.DEFAULT_TEMPLATE);

			return path;
		}

		StringBuffer newPath = new StringBuffer();

		Pattern p = Pattern.compile("\\$\\{(.)+\\}");
		Matcher m = p.matcher(path);

		try {
			while (m.find()) {
				String property = m.group();
				property = property.substring(2, property.length() - 1);

				m.appendReplacement(newPath,  BeanUtils.getNestedProperty(user, property));
			}
		} catch (Exception e) {
			VKCLogManager.errorLog(ServletUtils.class, "", e.getMessage(), e);

			return path;
		}

		m.appendTail(newPath);

		return newPath.toString();
	}
}