home *** CD-ROM | disk | FTP | other *** search
Java Source | 2000-04-03 | 19.4 KB | 885 lines |
- /*
- ** Sambar Server JAVA Engine Implementation
- **
- ** Confidential Property of Tod Sambar
- ** (c) Copyright Tod Sambar 1999
- ** All rights reserved.
- */
- package com.sambar.javaeng;
-
- import java.io.*;
- import java.net.*;
- import java.text.*;
- import java.util.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
- import com.sambar.javaeng.SambarAPI;
- import com.sambar.javaeng.SambarUtils;
-
- class SambarConnection implements HttpServletRequest, HttpServletResponse
- {
- private long sreq;
- private SambarContext scontext;
-
- /*
- ** HttpServletResquest Variables
- */
- private boolean sessionFromCookie = false;
- private boolean sessionFromUrl = false;
- private String sessionid = null;
- private SambarSession session = null;
- private Cookie[] cookiesIn = null;
-
- /*
- ** HttpServletResponse Variables
- */
- private int status;
- private int contentLength;
- private String statusString = null;
- private String contentType = null;
- private boolean sentHeader;
- private SambarInputStream istream = null;
- private SambarOutputStream ostream = null;
- private PrintWriter swriter = null;
- private Hashtable headersOut = new Hashtable(15, 0.9f);
- private Vector cookiesOut = new Vector(5);
- private Hashtable params = null;
-
-
- public SambarConnection(long sreq, SambarContext scontext)
- {
- this.sreq = sreq;
- this.scontext = scontext;
-
- this.status = SC_OK;
- this.contentLength = 0;
- this.sentHeader = false;
- if (SambarAPI.wasHeaderSent(sreq) > 0)
- this.sentHeader = true;
-
- // Get the sessionid from the query string and/or cookie
- sessionid = getUrlSessionId();
- if (sessionid != null)
- {
- sessionFromUrl = true;
- }
- else
- {
- sessionid = getCookieSessionId();
- if (sessionid != null)
- sessionFromCookie = false;
- }
- }
-
- public void close()
- {
- if (swriter != null)
- swriter.close();
- }
-
- /***********************************************************************
- **
- ** ServletRequest Methods
- **
- ***********************************************************************/
- public Object getAttribute(String name)
- {
- if (name.equalsIgnoreCase("isSambarAdmin"))
- {
- if (SambarAPI.isSambarAdmin(sreq) > 0)
- return new String("true");
- }
- else if (name.equalsIgnoreCase("isSambarUser"))
- {
- if (SambarAPI.isSambarUser(sreq) > 0)
- return new String("true");
- }
-
- return null;
- }
-
- public Enumeration getAttributeNames()
- {
- // Not implemented
- return null;
- }
-
- public int getContentLength()
- {
- return SambarAPI.getContentLength(sreq);
- }
-
- public String getContentType()
- {
- return SambarAPI.getContentType(sreq);
- }
-
- /*
- ** Returns the input stream for reading binary data in the request body
- */
- public ServletInputStream getInputStream() throws IOException
- {
- if (istream == null)
- istream = new SambarInputStream(sreq, this);
-
- return (ServletInputStream)istream;
- }
-
- protected void getParameters()
- {
- if (params != null)
- return;
-
- /*
- ** Retrieve the parameters from the Sambar Connection cache
- */
- params = new Hashtable();
- int count = SambarAPI.getParameterCount(sreq);
- for (int i = 0; i < count; i++)
- {
- String name = SambarAPI.getParameterName(sreq, i + 1);
- String value = SambarAPI.getParameterValue(sreq, i + 1);
- if (value == null)
- value = new String("");
-
- Object pval = params.get(name);
- if (pval == null)
- {
- params.put(name, value);
- }
- else if (pval instanceof String)
- {
- Vector pvector = new Vector();
- pvector.addElement(pval);
- pvector.addElement(value);
- params.put(name, pvector);
- }
- else
- {
- Vector pvector = (Vector)pval;
- pvector.addElement(value);
- }
- }
-
- return;
- }
-
- public String getParameter(String name)
- {
- return SambarAPI.getParameter(sreq, name);
- }
-
- public void setParameter(String name, String val)
- {
- getParameters();
-
- /*
- ** Set the parameter in both the servlet paramters and
- ** server parameters
- */
- SambarAPI.setParameter(sreq, name, val);
- params.put(name, val);
- return;
- }
-
- public Enumeration getParameterNames()
- {
- getParameters();
- return params.keys();
- }
-
- public String[] getParameterValues(String name)
- {
- getParameters();
- Object val = params.get(name);
-
- if (val == null)
- {
- return new String[0];
- }
- else if (val instanceof String)
- {
- String values[] = {(String)val};
- return values;
- }
- else
- {
- Vector pvector = (Vector)val;
- String values[] = new String[pvector.size()];
- for (int i = 0; i < values.length; i++)
- values[i] = (String)pvector.elementAt(i);
-
- return values;
- }
- }
-
- public String getProtocol()
- {
- return SambarAPI.getProtocol(sreq);
- }
-
- public String getScheme()
- {
- return SambarAPI.getScheme(sreq);
- }
-
- public String getHostname()
- {
- return SambarAPI.getHostname(sreq);
- }
-
- public String getServerName()
- {
- return SambarAPI.getServerName(sreq);
- }
-
- public int getServerPort()
- {
- return SambarAPI.getServerPort(sreq);
- }
-
- /*
- ** Returns a buffered reader for reading text in the request body
- */
- public BufferedReader getReader() throws IOException
- {
- // FIX THIS sambar - implement
- return null;
- }
-
- public String getRemoteAddr()
- {
- return SambarAPI.getRemoteAddr(sreq);
- }
-
- public String getRemoteHost()
- {
- return SambarAPI.getRemoteHost(sreq);
- }
-
- public void setAttribute(String name, Object object)
- {
- // Not implemented
- return;
- }
-
- public String getRealPath(String path)
- {
- return SambarAPI.getRealPath(sreq, path);
- }
-
- public String getContextPath()
- {
- return SambarAPI.getContextPath(sreq);
- }
-
- public boolean isRemoteUserInRole(String name)
- {
- // Not implemented
- return false;
- }
-
- /***********************************************************************
- **
- ** HTTPServletRequest Methods
- **
- ***********************************************************************/
- public String getAuthType()
- {
- return SambarAPI.getAuthType(sreq);
- }
-
- public String getAuthPass()
- {
- return SambarAPI.getAuthPass(sreq);
- }
-
- public Cookie[] getCookies()
- {
- if (cookiesIn == null)
- {
- cookiesIn = SambarUtils.parseCookies(SambarAPI.getHeader(sreq,
- "HTTP_COOKIE"));
- }
-
- return cookiesIn;
- }
-
- public long getDateHeader(String name)
- {
- SimpleDateFormat sdf;
- String header = SambarAPI.getHeader(sreq, name);
- if (header == null)
- return -1;
-
- sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
- try
- {
- Date date = sdf.parse(header);
- return date.getTime();
- }
- catch (ParseException formatNotValid)
- {
- // try another format
- }
-
- sdf = new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US);
- try
- {
- Date date = sdf.parse(header);
- return date.getTime();
- }
- catch (ParseException formatNotValid)
- {
- // try another format
- }
-
- sdf = new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US);
- try
- {
- Date date = sdf.parse(header);
- return date.getTime();
- }
- catch (ParseException formatNotValid)
- {
- throw new IllegalArgumentException(header);
- }
- }
-
- public String getHeader(String name)
- {
- return SambarAPI.getHeader(sreq, name);
- }
-
- public Enumeration getHeaders(String name)
- {
- // FIX THIS sambar - implement
- return scontext.emptyVector.elements();
- }
-
- public Enumeration getHeaderNames()
- {
- // FIX THIS sambar - implement
- return scontext.emptyVector.elements();
- }
-
- public int getIntHeader(String name)
- {
- String header = SambarAPI.getHeader(sreq, name);
- if (header == null)
- return -1;
-
- return Integer.parseInt(header);
- }
-
- public String getMethod()
- {
- return SambarAPI.getMethod(sreq);
- }
-
- public String getPathInfo()
- {
- return SambarAPI.getPathInfo(sreq);
- }
-
- public String getPathTranslated()
- {
- return SambarAPI.getPathTranslated(sreq);
- }
-
- public String getQueryString()
- {
- return SambarAPI.getQueryString(sreq);
- }
-
- public String getRemoteUser()
- {
- return SambarAPI.getRemoteUser(sreq);
- }
-
- public String getRequestURI()
- {
- return SambarAPI.getRequestURI(sreq);
- }
-
- public String getServletPath()
- {
- return SambarAPI.getServletPath(sreq);
- }
-
- public String getRequestedSessionId()
- {
- return sessionid;
- }
-
- public HttpSession getSession(boolean create)
- {
- if (session != null)
- return session;
-
- if (sessionid != null)
- {
- session = (SambarSession)scontext.getSession(sessionid);
- if (session != null)
- return session;
- }
-
- if (create == true)
- {
- session = scontext.createSession(this);
- sessionid = session.id;
- return session;
- }
-
- return null;
- }
-
- public HttpSession getSession()
- {
- return getSession(false);
- }
-
- public boolean isRequestedSessionIdValid()
- {
- if (sessionid == null)
- return false;
- else if (scontext.getSession(sessionid) == null)
- return false;
-
- return true;
- }
-
- public boolean isRequestedSessionIdFromCookie()
- {
- return sessionFromCookie;
- }
-
- public boolean isRequestedSessionIdFromUrl()
- {
- return sessionFromUrl;
- }
-
- public boolean isRequestedSessionIdFromURL()
- {
- return isRequestedSessionIdFromUrl();
- }
-
- public RequestDispatcher getRequestDispatcher(String path)
- {
- if (path == null)
- return null;
-
- if (!path.startsWith("/"))
- {
- String base = getRequestURI();
- if (base == null)
- base = "/";
-
- // check for ? string on lookuppath
- int qindex = base.indexOf("?");
-
- if (qindex > -1)
- base = base.substring(0, qindex);
-
- if (base.length() < 1)
- base = "/";
-
- path = SambarUtils.catPath(base, path);
-
- if (path == null)
- return null;
- }
-
- return scontext.getRequestDispatcher(path);
- }
-
- /***********************************************************************
- **
- ** ServletResponse Methods
- **
- ***********************************************************************/
- public String getCharacterEncoding()
- {
- /*
- ** Returns the character set encoding used for this MIME body.
- ** If no content type has yet been assigned, it is implicitly
- ** set to <em>text/plain</em>
- */
- if (contentType == null)
- contentType = "text/plain";
-
- return SambarUtils.parseCharacterEncoding(contentType);
- }
-
- public ServletOutputStream getOutputStream() throws IOException
- {
- if (ostream == null)
- ostream = new SambarOutputStream(sreq, this);
-
- return (ServletOutputStream)ostream;
- }
-
- public PrintWriter getWriter() throws IOException
- {
- if (swriter == null)
- {
- OutputStreamWriter out;
- out = new OutputStreamWriter(getOutputStream(),
- getCharacterEncoding());
- swriter = new PrintWriter(out);
- }
-
- return swriter;
- }
-
- public void setContentLength(int len)
- {
- contentLength = len;
- return;
- }
-
- public void setContentType(String type)
- {
- contentType = type;
- return;
- }
-
- /***********************************************************************
- **
- ** HTTPServletResponse Methods
- **
- ***********************************************************************/
- public void addCookie(Cookie cookie)
- {
- cookiesOut.addElement(cookie);
- return;
- }
-
- public boolean containsHeader(String name)
- {
- return headersOut.contains(name.toLowerCase());
- }
-
- public String encodeURL(String url)
- {
- if (isRequestedSessionIdFromCookie())
- {
- return url;
- }
- else
- {
- SambarSession session = (SambarSession)getSession();
- if (session == null)
- return url;
-
- // Encode the URL with the session ID
- if (url.indexOf('?') == -1)
- return url + '?' + SambarAPI.SESSION_ID + '=' + session.id;
- else
- return url + "&" + SambarAPI.SESSION_ID + '=' + session.id;
- }
- }
-
- public String encodeUrl(String url)
- {
- return encodeURL(url);
- }
-
- public String encodeRedirectURL(String url)
- {
- String hostname = SambarAPI.getHostname(sreq);
- if (url.indexOf(hostname) == -1)
- return url;
- else
- return encodeURL(url);
- }
-
- public String encodeRedirectUrl(String url)
- {
- return encodeRedirectURL(url);
- }
-
- public void sendError(int sc, String msg)
- {
- status = sc;
- contentType = "text/html";
- sendHttpHeaders();
-
- SambarAPI.puts(sreq, "<HTML><HEAD>\n");
- SambarAPI.puts(sreq, "<TITLE>" + status + " Servlet Error</TITLE>\n");
- SambarAPI.puts(sreq, "</HEAD><BODY BGCOLOR=#FFFFFF>\n");
- SambarAPI.puts(sreq, "<TABLE BORDER=0 WIDTH=500 CELLPADDING=10 " +
- "CELLSPACING=10>\n");
- SambarAPI.puts(sreq, "<TR><TD BGCOLOR=#990033 ALIGN=LEFT>\n");
- SambarAPI.puts(sreq, "<FONT SIZE=5 COLOR=#FFFFFF><B>" + status);
- SambarAPI.puts(sreq, " " + statusString + "</B></FONT>\n");
- SambarAPI.puts(sreq, "</TR></TD><TR><TD><FONT SIZE=+1><BR>\n");
- SambarAPI.puts(sreq, msg);
- SambarAPI.puts(sreq, "</FONT><BR><BR>\n");
- SambarAPI.puts(sreq, "<A HREF=\"http://www.sambar.com\">");
- SambarAPI.puts(sreq, "<FONT SIZE=2>Powered By Sambar</FONT></A>");
- SambarAPI.puts(sreq, "</TD></TR></TABLE></BODY></HTML>\n");
-
- // Flush and close, so the error can be returned right
- // away, and so any additional data sent is ignored
- SambarAPI.flush(sreq);
- SambarAPI.close(sreq);
- return;
- }
-
- public void sendError(int sc)
- {
- sendError(sc, getStatusString(sc));
- return;
- }
-
- public void sendError(Throwable e)
- {
- sendError(SC_INTERNAL_SERVER_ERROR,
- e.toString() + ": " + e.getMessage());
- }
-
- public void sendRedirect(String location) throws IOException
- {
- setStatus(SC_MOVED_TEMPORARILY);
- setHeader("Location", location);
- sendHttpHeaders();
- return;
- }
-
- public void setDateHeader(String name, long date)
- {
- addDateHeader(name, date);
- }
-
- public void addDateHeader(String name, long date)
- {
- SimpleDateFormat sdf =
- new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);
- TimeZone tz = TimeZone.getTimeZone("GMT");
-
- sdf.setTimeZone(tz);
-
- headersOut.put(name, sdf.format(new Date(date)));
- return;
- }
-
- public void setHeader(String name, String value)
- {
- addHeader(name, value);
- }
-
- public void addHeader(String name, String value)
- {
- int pos;
-
- // Make sure no newlines are present in the header
- if ((pos = value.indexOf((int)'\n')) > 0)
- {
- char msgAsArray[] = value.toCharArray();
- msgAsArray[pos] = ' ';
-
- while ((pos = value.indexOf((int)'\n', pos + 1)) > 0)
- msgAsArray[pos] = ' ';
-
- value = new String(msgAsArray);
- }
-
- headersOut.put(name, value);
- return;
- }
-
- public void setIntHeader(String name, int value)
- {
- addIntHeader(name, value);
- }
-
- public void addIntHeader(String name, int value)
- {
- Integer val = new Integer(value);
- headersOut.put(name, val.toString());
- return;
- }
-
- public void setStatus(int sc, String sm)
- {
- this.status = sc;
- this.statusString = sm;
- return;
- }
-
- public void setStatus(int sc)
- {
- setStatus(sc, null);
- return;
- }
-
- /*
- **
- ** Send the HTTP headers and prepare to send response.
- */
- protected void sendHttpHeaders()
- {
- // Send the status info
- if (statusString == null)
- statusString = getStatusString(status);
-
- if (sentHeader)
- return;
-
- String hdr;
- sentHeader = true;
-
- hdr = "HTTP/1.1 " + status + " " + statusString;
- SambarAPI.puts(sreq, hdr + "\r\n");
-
- if (contentType == null)
- hdr = "Content-Type: text/plain";
- else
- hdr = "Content-Type: " + contentType;
-
- SambarAPI.puts(sreq, hdr + "\r\n");
-
- if (contentLength > 0)
- {
- hdr = "Content-length: " + contentLength;
- SambarAPI.puts(sreq, hdr + "\r\n");
-
- SambarAPI.setKeepAlive(sreq);
-
- if (!containsHeader("Connection"))
- setHeader("Connection", "Keep-Alive");
- if (!containsHeader("Keep-Alive"))
- setHeader("Keep-Alive", "timeout=180");
- }
- else
- {
- if (!containsHeader("Connection"))
- setHeader("Connection", "close");
- }
-
- if (!containsHeader("Date"))
- setDateHeader("Date", System.currentTimeMillis());
-
- if (!containsHeader("Server"))
- setHeader("Server", "SAMBAR4.3/JavaEngine");
-
- if (!containsHeader("MIME-version"))
- setHeader("MIME-version", "1.0");
-
- if (headersOut != null)
- {
- // Send the headers
- for (Enumeration e = headersOut.keys(); e.hasMoreElements();)
- {
- String key = (String) e.nextElement();
- hdr = key + ": " + headersOut.get(key);
- SambarAPI.puts(sreq, hdr + "\r\n");
- }
- }
-
- // Send the cookies
- Enumeration elements = cookiesOut.elements();
- while (elements.hasMoreElements())
- {
- Cookie cookie = (Cookie)elements.nextElement();
- hdr = "Set-Cookie: " + SambarUtils.encodeCookie(cookie);
- SambarAPI.puts(sreq, hdr + "\r\n");
- }
-
- // Send a terminating blank line
- SambarAPI.puts(sreq, "\r\n");
-
- // Flush the output to the client
- SambarAPI.flush(sreq);
- }
-
- /*
- ** Finds a status string from one of the standard status code.
- */
- public static final String getStatusString(int sc)
- {
- switch (sc)
- {
- case SC_ACCEPTED:
- return "Accepted";
- case SC_BAD_GATEWAY:
- return "Bad Gateway";
- case SC_BAD_REQUEST:
- return "Bad Request";
- case SC_CREATED:
- return "Created";
- case SC_FORBIDDEN:
- return "Forbidden";
- case SC_INTERNAL_SERVER_ERROR:
- return "Internal Server Error";
- case SC_MOVED_PERMANENTLY:
- return "Moved Permanently";
- case SC_MOVED_TEMPORARILY:
- return "Moved Temporarily";
- case SC_NO_CONTENT:
- return "No Content";
- case SC_NOT_FOUND:
- return "Not Found";
- case SC_NOT_IMPLEMENTED:
- return "Method Not Implemented";
- case SC_NOT_MODIFIED:
- return "Not Modified";
- case SC_OK:
- return "OK";
- case SC_SERVICE_UNAVAILABLE:
- return "Service Temporarily Unavailable";
- case SC_UNAUTHORIZED:
- return "Authorization Required";
- default:
- return "Response";
- }
- }
-
- /***********************************************************************
- **
- ** Session Methods
- **
- ***********************************************************************/
- public String getUrlSessionId()
- {
- String queryString = getQueryString();
- if (queryString == null)
- return null;
-
- try
- {
- Hashtable params = HttpUtils.parseQueryString(queryString);
- Object o = params.get(SambarAPI.SESSION_ID);
- if (o == null)
- return null;
-
- if (o instanceof String)
- return (String)o;
-
- return ((String[])o)[0];
- }
- catch (IllegalArgumentException ex)
- {
- return null;
- }
-
- }
-
- public String getCookieSessionId()
- {
- Cookie[] cookies = getCookies();
-
- if ((cookies == null) || (cookies.length == 0))
- return null;
-
- for (int i = 0; i < cookies.length; i++)
- {
- if (cookies[i].getName().equals(SambarAPI.SESSION_ID))
- return cookies[i].getValue();
- }
-
- return null;
- }
- }
-