home *** CD-ROM | disk | FTP | other *** search
Java Source | 2000-04-03 | 11.0 KB | 520 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.util.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
- import com.sambar.javaeng.SambarAPI;
-
- class SambarContext implements ServletConfig, ServletContext,
- HttpSessionContext, Runnable
- {
- public Vector emptyVector;
- private long javaeng;
- static private int sessionCount = 0;
- protected Hashtable servletHash;
- protected Hashtable sessionHash;
- protected Hashtable contextData;
- protected SambarClassLoader loader;
-
- int sessionTimeout;
- int sessionCheckFrequency;
-
- private static class ServletEntry
- {
- int count;
- Servlet servlet;
- }
-
- public SambarContext(long javaeng) throws RuntimeException
- {
- String val;
-
- this.javaeng = javaeng;
- this.sessionTimeout = 0;
- this.sessionCheckFrequency = 0;
-
- val = System.getProperty("sessionTimeout");
- if (val != null)
- this.sessionTimeout = Integer.parseInt(val);
-
- val = System.getProperty("sessionCheckFrequency");
- if (val != null)
- this.sessionCheckFrequency = Integer.parseInt(val);
-
- if (this.sessionTimeout <= 1000)
- this.sessionTimeout = 1800000;
- if (this.sessionCheckFrequency <= 1000)
- this.sessionCheckFrequency = 5000;
-
- servletHash = new Hashtable();
- sessionHash = new Hashtable();
- contextData = new Hashtable();
- emptyVector = new Vector();
- String path = SambarAPI.getServletsPath(javaeng);
- Vector classRepository = parsepath(path);
-
- try
- {
- loader = new SambarClassLoader(this, classRepository, true);
- }
- catch (IllegalArgumentException e)
- {
- log("SambarClassLoader failed (invalid CLASSPATH?) - " +
- e.toString());
-
- throw new RuntimeException("SambarClassLoader failed: " +
- e.toString());
- }
-
- Thread housekeeping = new Thread(this);
- housekeeping.setDaemon(true);
- housekeeping.start();
- }
-
- public Vector parsepath(String classpath)
- {
- Vector path = new Vector();
-
- if (classpath == null)
- return path;
-
- StringTokenizer stok = new StringTokenizer(classpath, ";");
- while (stok.hasMoreTokens())
- {
- String tok = stok.nextToken();
- if (tok.length() > 0)
- path.addElement(tok);
- }
-
- return path;
- }
-
- public ServletContext getServletContext()
- {
- return this;
- }
-
- public String getInitParameter(String name)
- {
- return SambarAPI.getInitParameter(javaeng, name);
- }
-
- public Enumeration getInitParameterNames()
- {
- return emptyVector.elements();
- }
-
- public void log(String msg)
- {
- SambarAPI.logctx(javaeng, msg);
- }
-
- public void log(Exception e, String msg)
- {
- log(msg + " - " + e.toString());
- }
-
- public void log(String msg, Throwable throwable)
- {
- log(msg + " - " + throwable.toString());
- }
-
- public ServletContext getContext(String uripath)
- {
- return this;
- }
-
- public int getMajorVersion()
- {
- return 2;
- }
-
- public int getMinorVersion()
- {
- return 1;
- }
-
- public String getMimeType(String file)
- {
- return SambarAPI.getMimeType(javaeng, file);
- }
-
- public String getRealPath(String path)
- {
- return SambarAPI.getRealPath(javaeng, path);
- }
-
- public String getServerInfo()
- {
- return SambarAPI.getServerInfo(javaeng);
- }
-
- public Object getAttribute(String name)
- {
- return contextData.get(name);
- }
-
- public void removeAttribute(String name)
- {
- contextData.remove(name);
- }
-
- public Enumeration getAttributeNames()
- {
- return contextData.keys();
- }
-
- public void setAttribute(String name, Object object)
- {
- contextData.put(name, object);
- }
-
- public URL getResource(String path) throws MalformedURLException
- {
- return new URL("file:" + getRealPath(path));
- }
-
- public InputStream getResourceAsStream(String path)
- {
- InputStream is = null;
- URL u = null;
- try
- {
- u = getResource(path);
- }
- catch (MalformedURLException mue)
- {
- u = null;
- }
-
- if (u != null)
- {
- try
- {
- is = u.openStream();
- }
- catch (IOException ioe)
- {
- }
- }
-
- return is;
- }
-
- public RequestDispatcher getRequestDispatcher(String urlpath)
- {
- if ((urlpath == null) || !(urlpath.startsWith("/")))
- {
- // Return null if we can't return a dispather
- return null;
- }
-
- SambarRequestDispatcher rd = new SambarRequestDispatcher(this);
- rd.setPath(urlpath);
-
- return rd;
- }
-
- public synchronized Servlet getServlet(String name, boolean cache)
- throws ServletException
- {
- // Strip .class from the servlet if it is present.
- if ((name.length() > 6) &&
- (name.endsWith(".class") || name.endsWith(".CLASS")))
- {
- name = name.substring(0, name.length() - 6);
- }
-
- ServletEntry entry = null;
-
- if (loader.shouldReload(name))
- {
- log("SambarClassLoader reloading...");
- loader = loader.reinstantiate();
-
- // Destroy the old cached servlet (if it exists)
- entry = (ServletEntry)servletHash.get(name);
- if (entry != null)
- {
- try
- {
- servletHash.remove(name);
- }
- catch(Exception e)
- {
- log("Servlet '"+name+"' destroy failure - "+e.toString());
- }
- }
- }
-
- entry = null;
- if (cache)
- {
- entry = (ServletEntry)servletHash.get(name);
- if (entry != null)
- {
- entry.count++;
- return entry.servlet;
- }
- }
-
- Servlet servlet = null;
-
- try
- {
- servlet = (Servlet)loader.loadClass(name).newInstance();
- }
- catch (NoClassDefFoundError e)
- {
- log("NoClassDefFoundError: " + name + " - " + e.toString());
- return null;
- }
- catch (ClassNotFoundException e)
- {
- log("ClassNotFoundException: " + name + " - " + e.toString());
- return null;
- }
- catch (ClassFormatError e)
- {
- log("ClassFormatError: " + name + " - " + e.toString());
- return null;
- }
- catch (IllegalAccessException e)
- {
- log("IllegalAccessException: " + name + " - " + e.toString());
- return null;
- }
- catch (InstantiationException e)
- {
- log("InstantiationException: " + name + " - " + e.toString());
- return null;
- }
- catch (Exception e)
- {
- log("Exception: " + name + " - " + e.toString());
- return null;
- }
-
- try
- {
- servlet.init(this);
- }
- catch (ServletException e)
- {
- log("ServletException: " + name + " - " + e.toString());
- return null;
- }
- catch (Exception e)
- {
- log("Exception: " + name + " - " + e.toString());
- return null;
- }
-
- if (cache)
- {
- entry = new ServletEntry();
- entry.count = 1;
- entry.servlet = servlet;
-
- servletHash.put(name, entry);
- }
-
- return servlet;
- }
-
- public synchronized Servlet getServlet(String name)
- throws ServletException
- {
- return getServlet(name, true);
- }
-
- public Enumeration getServlets()
- {
- return emptyVector.elements();
- }
-
- public Enumeration getServletNames()
- {
- return emptyVector.elements();
- }
-
- public synchronized void destroyServlet(String name)
- {
- destroyServlet(name, false);
- }
-
- public synchronized void destroyServlet(String name, boolean force)
- {
- if (name == null)
- return;
-
- ServletEntry entry = (ServletEntry)servletHash.get(name);
- if (entry == null)
- return;
-
- // Don't destroy the servlet if it is in use.
- if (!force)
- {
- entry.count--;
- if (entry.count > 0)
- return;
- }
-
- try
- {
- entry.servlet.destroy();
- servletHash.remove(name);
- }
- catch(Exception e)
- {
- log("Servlet '" + name + "' destroy failure - " + e.toString());
- }
- }
-
- public synchronized void destroyServlets()
- {
- int i = 0;
- String[] tmpServlets = new String[servletHash.size()];
- Enumeration servletEnum = servletHash.keys();
- while (servletEnum.hasMoreElements())
- {
- tmpServlets[i++] = (String)servletEnum.nextElement();
- }
-
- try
- {
- while (i > 0)
- {
- i--;
- destroyServlet(tmpServlets[i], true);
- }
- }
- finally
- {
- servletHash.clear();
- }
- }
-
- public synchronized HttpSession getSession(String sessionId)
- {
- return (HttpSession)sessionHash.get(sessionId);
- }
-
- public synchronized SambarSession createSession(SambarConnection sconn)
- {
- SambarSession session;
-
- session = new SambarSession(getIdentifier(), this, sessionTimeout);
- sessionHash.put(session.id, session);
-
- Cookie cookie = new Cookie(SambarAPI.SESSION_ID, session.id);
- cookie.setPath("/");
- sconn.addCookie(cookie);
-
- return session;
- }
-
- public synchronized void removeSession(SambarSession session)
- {
- sessionHash.remove(session.id);
- }
-
- /*
- ** Create a suitable string for session identification
- ** Use count and synchronized to ensure uniqueness.
- ** Use timestamp because it useful in session timeouts.
- ** Use random string to ensure timestamp cannot be guessed
- ** by programmed attack.
- **
- ** format of id is <random-hex-string>.<count>.<timestamp-ms>
- */
- static synchronized private String getIdentifier()
- {
- String time;
- String random;
-
- random = Long.toHexString(Double.doubleToLongBits(Math.random()));
- time = Long.toString(System.currentTimeMillis());
- sessionCount++;
-
- return random + "-" + time + "-" + sessionCount;
- }
-
- synchronized private String getIdentifier(String jsIdent)
- {
- if (jsIdent != null)
- return getIdentifier() + "-" + jsIdent;
-
- return getIdentifier();
- }
-
- /*
- ** Returns an enumeration of all of the session IDs in this context.
- */
- public synchronized Enumeration getIds()
- {
- Vector ids = new Vector();
- Enumeration idEnum = sessionHash.keys();
- while (idEnum.hasMoreElements())
- ids.addElement( idEnum.nextElement() );
-
- return ids.elements();
- }
-
-
- /*
- ** The housekeeping thread
- ** Checks for sessions that have not been used for a certain
- ** amount of time and invalidates them.
- */
- public void run()
- {
- Enumeration sessions;
- SambarSession session;
- long sysMillis;
-
- while (true)
- {
- // sleep for 5 seconds.
- try
- {
- Thread.sleep(sessionCheckFrequency);
- }
- catch(InterruptedException exc)
- {
- }
-
- // walk through all sessions and invalidate old ones
- sessions = sessionHash.elements();
- sysMillis = System.currentTimeMillis();
- while (sessions.hasMoreElements())
- {
- session = (SambarSession)sessions.nextElement();
- synchronized (session)
- {
- if (sysMillis - session.lastAccessTime >
- session.getMaxInactiveInterval())
- {
- try
- {
- session.invalidate();
- }
- catch (IllegalStateException ignored)
- {
- }
- }
- }
- }
- }
- }
- }
-