Paste number 21016: Bracing issue

Paste number 21016: Bracing issue
Pasted by: jdolan
When:12 years, 9 months ago
Share:Tweet this! | http://paste.lisp.org/+G7S
Channel:None
Paste contents:
Raw Source | XML | Display As
/**  Copyright 2002-2006 Goesnet, Inc.  */

package com.goesnet.dportal;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.goesnet.dportal.sql.Customer;
import com.goesnet.dportal.sql.Dealership;
import com.goesnet.dportal.sql.Employee;
import com.goesnet.dportal.util.Lists;
import com.goesnet.dportal.util.StringHandler;

import com.goesnet.dportal.util.Lists;
import com.goesnet.dportal.util.StringHandler;

/**
*  A convenient framework that encompasses HttpServletRequest and Response objects.  There are several key 
*  enhancements over the J2EE implementations.  Namely, parameter information is mutable, making slight 
*  modifications to incoming Url's very easy.  Session management, Template printing, and redirection encoding 
*  are also neatly bundled and conveniently available.  Invocations may be deferred to Session data if authentication
*  tokens are not in place at the time of their initial Request, and serviced later upon a successful SIGN_IN.
*
*  @author jdolan
*/

public final class ServletInvocation {
	
/**
*  A convenient framework that encompasses HttpServletRequest and Response objects.  There are several key 
*  enhancements over the J2EE implementations.  Namely, parameter information is mutable, making slight 
*  modifications to incoming Url's very easy.  Session management, Template printing, and redirection encoding 
*  are also neatly bundled and conveniently available.  Invocations may be deferred to Session data if authentication
*  tokens are not in place at the time of their initial Request, and serviced later upon a successful SIGN_IN.
*
*  @author jdolan
*/

public final class ServletInvocation {
	
	/**
	*  Methods supported, SIGN_IN and SIGN_OUT are specified by "magic" parameters.
	*/
	public static final int GET = 10;
	public static final int POST = 20;
	public static final int SIGN_IN = 30;
	public static final int SIGN_OUT = 40;
	
	/**
	*  Response constants, wrapped for convenience.
	*/
	public static final int SC_OK = HttpServletResponse.SC_OK;
	public static final int SC_BAD_REQUEST = HttpServletResponse.SC_BAD_REQUEST;
	public static final int SC_NOT_FOUND = HttpServletResponse.SC_NOT_FOUND;
	public static final int SC_FORBIDDEN = HttpServletResponse.SC_FORBIDDEN;
	
	/**
	*  Parameters used for results pagination, ordering, and collation.
	*/
	public static final String[] FLUFF_PARAMS = {
		"page", /*"page_show_all",*/ "order", "collator_enabled", "collator_disabled"
	};
	
	private Dealership dealership;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private int method;
	private Servlet servlet;
	private Map<String, String[]> _parameters;  //original params, accessed when all values are desired
	private Map<String, String> parameters;  //clean params, accessed for just first value
	private Employee employee;
	private Customer customer;
	private boolean compactUi;
	private boolean commit;
	
	/**
	*  Instantiates a new ServletInvocation to wrap <code>request</code> and <code>response</code>.
	*/
	public ServletInvocation(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		setRequest(request); setResponse(response);  //set request and response
		setDealership(Dportal.getDealership(getHost()));  //resolve dealership
		
		//we actually have to copy the incoming params to preserve them in the
		//case of deferred invocations
		
		_parameters = new HashMap<String, String[]>(request.getParameterMap());
		
		//we also create another copy of the params in a Map<String, String>
		//to make url recreation and token stuffing painless
		
		setParameters(new HashMap<String, String>());  //resolve params
		
		Iterator iterator = _parameters.keySet().iterator(); String p, v[];
		while(iterator.hasNext()){  //copy first param value to parameters
			p = (String)iterator.next();
			v = (String[])_parameters.get(p);
			
			if(v != null && v.length > 0)
				setParameter(p, v[0]);
		}
		
		if(getBoolParameter("_sign_in")) setMethod(SIGN_IN);  //resolve method
		else if(getBoolParameter("_sign_out")) setMethod(SIGN_OUT);
		else if(getRequest().getMethod().equals("GET")) setMethod(GET);
		else setMethod(POST);
		
		String servletName = getRequest().getPathInfo().replaceAll("/", "");
		setServlet(Servlet.getInstance(servletName));
		
		Cookie cookie = getCookie(getServlet().getSessionCookie());
		if(cookie != null) setCookie(cookie);  //touch cookie
		
		customer = null; employee = null;
	}
	
	/**
	*  Returns the [virtual] host on which this Invocation's Request was received.
	*/
	public String getHost(){
		return getRequest().getServerName();
	}
	
	/**
	*  Returns this Invocation's Url, including all path information as well as the query string if applicable.
	*  @param includeFluff If true, the returned Url will include all parameters and values, even those
	*  defined in <code>FLUFF_PARAMS</code>.  If false, <code>FLUFF_PARAMS</code> will be omitted.
	*/
	public String getUrl(boolean includeFluff){
		
		StringBuilder url = new StringBuilder("/bin/" + getServlet().getClass().getName() + "?");
		
		String param, value;
		Iterator<String> iterator = getParameters().keySet().iterator();
		while(iterator.hasNext()){
			
			param = iterator.next();
			
			if(!includeFluff && Lists.contains(FLUFF_PARAMS, param))
				continue;  //skip fluff params
			
			value = getParameter(param);
			
			if(value == null || value.equals(""))
				continue;
			
			url.append(param + "=" + value + "&amp;");
		}
		
		return url.toString();
	}
	
	/**
	*  Returns the entire request Url.  This is equivalent to <code>getUrl(true)</code>.
	*/
	public String getUrl(){
		return getUrl(true);
	}
	
	/**
	*  Returns the request Url, minus parameters for result pagination, ordering, and collating.
	*  This is equivalent to <code>getUrl(false)</code>
	*/
	public String getBaseUrl(){
		return getUrl(false);
	}
	
	/**
	*  Sets param to value.  Pass null or the empty String to unset the parameter.
	*/
	public void setParameter(String param, String value){
		if(value == null || value.equals("")) getParameters().remove(param);
		else getParameters().put(param, value);
	}
	
	/**
	*  Returns the value passed with param, null if the parameter was not present.
	*/
	public String getParameter(String param){
		return StringHandler.parse(getParameters().get(param));
	}
	
	/**
	*  Returns a search value passed with param, null if the parameter was not present.
	*/
	public String getSearchParameter(String param){
		return StringHandler.parseSearch(getParameters().get(param));
	}
	
	/**
	*  Returns an int value passed with param using StringHandler.parseInt(String).
	*/
	public int getIntParameter(String param){
		return StringHandler.parseInt(getParameters().get(param));
	}
	
	/**
	*  Returns a long value passed with param using StringHandler.parseLong(String).
	*/
	public long getLongParameter(String param){
		return StringHandler.parseLong(getParameters().get(param));
	}
	
	/**
	*  Returns a double value passed with param using StringHandler.parseDouble(String).
	*/
	public double getDoubleParameter(String param){
		return StringHandler.parseDouble(getParameters().get(param));
	}
	
	/**
	*  Returns a Date value passed with param using StringHandler.parseDate(String).
	*/
	public Date getDateParameter(String param){
		return StringHandler.parseDate(getParameters().get(param));
	}
	
	/**
	*  Returns a Time value passed with param using StringHandler.parseTime(String).
	*/
	public Time getTimeParameter(String param){
		return StringHandler.parseTime(getParameters().get(param));
	}
	
	/**
	*  Returns a Timestamp value passed with param using StringHandler.parseDatetime(String).
	*/
	public Timestamp getDatetimeParameter(String param){
		return StringHandler.parseDatetime(getParameters().get(param));
	}
	
	/**
	*  Returns a boolean value passed with param using StringHandler.parseBool(String).
	*/
	public boolean getBoolParameter(String param){
		return StringHandler.parseBool(getParameters().get(param));
	}
	
	/**
	*  A convenience method which wraps <code>ServletRequest.getParameterValues</code>.
	*/
	public String[] getParameterValues(String param){
		return (String[])_parameters.get(param);
	}
	
	/**
	*  Returns a Cookie by name, or null if such a Cookie has not yet been set.
	*/
	public Cookie getCookie(String name){
		
		Cookie cookies[] = getRequest().getCookies();
		
		if(cookies == null) return null;
		
		for(int i = 0; i < cookies.length; i++)
			if(cookies[i].getName().equals(name))
				return cookies[i];
		
		return null;
	}
	
	/**
	*  Stores cookie to the underlying Response after ensuring its visibility to the entire application.
	*/
	public void setCookie(Cookie cookie){
		cookie.setDomain(getHost()); cookie.setMaxAge(3600); getResponse().addCookie(cookie);
	}
	
	/**
	*  Resets any cookies currently available to the Application.
	*/
	public void clearCookies(){
		
		Cookie cookies[] = getRequest().getCookies();
		
		if(cookies == null) return;
		
		for(int i = 0; i < cookies.length; i++){
			cookies[i].setValue(null);
			setCookie(cookies[i]);
		}
	}
	
	/**
	*  Sets customer as the current Customer for this session.  Pass null to invalidate the session.
	*/
	public void setCustomer(Customer customer) throws Exception {
		
		this.customer = customer;
		
		if(customer == null){  //invalidate session
			clearCookies();
			return;
		}
		
		String id = StringHandler.encrypt(customer.getId() + "");
		setCookie(new Cookie("customer_id", id));
	}
	
	/**
	*  Returns the Customer from this Invocation's Session.  null if one does not exist.
	*/
	public Customer getCustomer(Connection connection) throws Exception {
		
		if(customer != null) return customer;  //local customer
		
		int id; Cookie cookie = getCookie("customer_id");
		
		try { id = Integer.parseInt(StringHandler.decrypt(cookie.getValue()));}
		catch(Exception e){ return null; }
		
		return new Customer(connection, id);
	}
	
	/**
	*  Sets employee as the current Employee for this session.  Pass null to invalidate the session.
	*/
	public void setEmployee(Employee employee) throws Exception {
		
		this.employee = employee;
		
		if(employee == null){  //invalidate session
			clearCookies();
			return;
		}
		
		String id = StringHandler.encrypt(employee.getId() + "");
		setCookie(new Cookie("employee_id", id));
	}
	
	/**
	*  Returns the Employee from this Invocation's Session.  null if one does not exist.
	*/
	public Employee getEmployee(Connection connection) throws Exception {
		
		if(employee != null) return employee;  //local employee
		
		int id; Cookie cookie = getCookie("employee_id");
		
		try { id = Integer.parseInt(StringHandler.decrypt(cookie.getValue()));}
		catch(Exception e){ return null; }
		
		return new Employee(connection, id);
	}
	
	/**
	*  Returns the most recently deferred Invocation, defaulting to null.
	*/
	public ServletInvocation getDeferred(){
		
		ServletInvocation deferred = (ServletInvocation)getSession().getAttribute("deferred_invocation");
		
		if(deferred != null){  //ensure deferred has valid request/response
			deferred.setRequest(getRequest());
			deferred.setResponse(getResponse());
		}
		
		return deferred;
	}
	
	/**
	*  Defers this Invocation and prints the Sign In Template.  This method is equivalent 
	*  to calling <code>defer(true)</code>.
	*/
	public void defer() throws Exception {
		defer(true);
	}
	
	/**
	*  Defers this Invocation and, if desired, prints the Sign In Template.
	*/
	public void defer(boolean signIn) throws Exception {
		getSession().setAttribute("deferred_invocation", this);
		if(signIn) print(getServlet().getSigninTemplate());
	}
	
	/**
	*  Prints the deny Template to the client.
	*/
	public void deny() throws Exception {
		setStatus(SC_FORBIDDEN); print(getServlet().getDenyTemplate());
	}
	
	/**
	*  Prints the error Template to the client.
	*/
	public void error() throws Exception {
		setStatus(SC_BAD_REQUEST); print(getServlet().getErrorTemplate());
	}
	
	/**
	*  Returns the page number of this Invocation for multipage views.
	*/
	public int getPageNumber(){
		int page = getIntParameter("page");
		return page > -1 ? page : 1;
	}
	
	/**
	*  Sets the page number of this Invocation to page.
	*/
	public void setPageNumber(int page){
		setParameter("page", page + "");
	}
	
	/**
	*  Sets the underlying Response's status to the wrapped constant, status.  This can successfully
	*  be called only once per Invocation, and is enforced via <code>getCommit()</code>.
	*/
	public void setStatus(int status){
		if(!getCommit()) getResponse().setStatus(status);
		setCommit(true);
	}
	
	/**
	*  Sets the underlying Response's content type to the specified String.
	*/
	public void setContentType(String contentType){
		getResponse().setContentType(contentType);
	}
	
	/**
	*  Sets the specified header within the underlying Response.
	*/
	public void setHeader(String header, String value){
		getResponse().setHeader(header, value);
	}
	
	/**
	*  Prints buffer to the client using the "text/plain" mime type.
	*/
	public void print(StringBuilder buffer) throws Exception {
		print(buffer, "text/plain; charset=UTF-8");
	}
	
	/**
	*  Prints buffer to the client using the specified mime type.
	*/
	public void print(StringBuilder buffer, String contentType) throws Exception {
		
		setStatus(SC_OK);
		if(contentType != null) setContentType(contentType);
		
		getWriter().print(buffer.toString());
		getWriter().close();
	}
	
	/**
	*  Prints the specified template to the client using the default content type.
	*/
	public void print(String template) throws Exception {
		print(template, new HashMap<String, String>());
	}
	
	/**
	*  Prints the specified template to the client using the default content type.
	*/
	public void print(String template, Map<String, String> tokens) throws Exception {
		print(template, tokens, "text/html; charset=UTF-8");
	}
	
	/**
	*  Prints the specified template to the client using the specified content type.
	*/
	public void print(String template, String contentType) throws Exception {
		print(template, new HashMap<String, String>(), contentType);
	}
	
	/**
	*  Prints template to the client using the specified content type.
	*/
	public void print(String template, Map<String, String> tokens, String contentType) throws Exception {
		
		setStatus(SC_OK); 
		if(contentType != null) setContentType(contentType);  //assign content type
		tokens.put("compact_ui", getCompactUi() + "");  //stuff ui token
		
		Template tmp = new Template(getDealership(), template, tokens);
		tmp.setWriter(getWriter()); tmp.parse();
		
		getWriter().close();
	}
	
	/**
	*  Writes file to the client using the "text/plain" mime type.
	*/
	public void write(File file) throws Exception {
		write(file, "text/plain; charset=UTF-8");
	}
	
	/**
	*  Writes file to the client using the specified content type.  This method may be used to 
	*  transport generated images, file attachments, etc.
	*/
	public void write(File file, String contentType) throws Exception {
		
		FileInputStream inStream = new FileInputStream(file);
		byte[] bytes = new byte[(int)file.length()];
		
		inStream.read(bytes); inStream.close();
		
		write(bytes, contentType);
	}
	
	/**
	*  Writes the specified byte array to the client using the "text/plain" mime type.
	*/
	public void write(byte[] content) throws Exception{
		write(content, "text/plain; charset=UTF-8");
	}
	
	/**
	*  Writes the specified byte array to the client, using the specified content type.
	*/
	public void write(byte[] content, String contentType) throws Exception{
		
		setStatus(SC_OK); setContentType(contentType);
		
		getOutputStream().write(content);
		getOutputStream().close();
	}
	
	/**
	*  Redirect the client to the specified domain's welcome file.
	*/
	public void redirect(int domain) throws Exception {
		
		switch(domain){  //redirect to domain welcome url
			case Dportal.INTERNET: redirect("/"); break;
			case Dportal.INTRANET: redirect("/intranet"); break;
			default: break;
		}
	}
	
	/**
	*  Redirect the client to the specified Url, which will be prepended, escaped, and encoded as necessary.
	*/
	public void redirect(String url) throws Exception {
		
		if(url.indexOf("://") == -1) url = getDealership().getUrl() + url;  //prepend dealership url
		url = getResponse().encodeRedirectURL(url.replaceAll("&amp;", "&"));  //unescape &'s
		
		getResponse().sendRedirect(url);
	}
	
	// Sets
	private void setDealership(Dealership dealership){
		this.dealership = dealership;
	}
	
	private void setRequest(HttpServletRequest request){
		this.request = request;
	}
	
	private void setResponse(HttpServletResponse response){
		this.response = response;
	}
	
	private void setMethod(int method){
		this.method = method;
	}
	
	private void setServlet(Servlet servlet){
		this.servlet = servlet;
	}
	
	public void setParameters(Map<String, String> parameters){
		this.parameters = parameters;
	}
	
	public void setCompactUi(boolean compactUi){
		this.compactUi = compactUi;
	}
	
	private void setCommit(boolean commit){
		this.commit = commit;
	}
	
	// Gets
	public Dealership getDealership(){
		return dealership;
	}
	
	public HttpServletRequest getRequest(){
		return request;
	}
	
	public HttpServletResponse getResponse(){
		return response;
	}
	
	public int getMethod(){
		return method;
	}
	
	public Servlet getServlet(){
		return servlet;
	}
	
	public Map<String, String> getParameters(){
		return parameters;
	}
	
	public boolean getCompactUi(){
		return compactUi;
	}
	
	public boolean getCommit(){
		return commit;
	}
	
	public HttpSession getSession(){
		return getRequest().getSession(true);
	}
	
	public PrintWriter getWriter() throws IOException {
		return getResponse().getWriter();
	}
	
	public OutputStream getOutputStream() throws IOException {
		return getResponse().getOutputStream();
	}
}

This paste has no annotations.

Colorize as:
Show Line Numbers

Lisppaste pastes can be made by anyone at any time. Imagine a fearsomely comprehensive disclaimer of liability. Now fear, comprehensively.