wms-winstone-1.0.5

Boolean.TRUE.booleanValue();
    for (int i = 0; i < ps.length; i++) {
      if ((ps[i] == '/') || (ps[i] == '\\'))
      {
        if (!div_state)
        {
          TreeNode node = cur_node.get(new String(ps, p0, i - p0));
          if (node == null)
          {
            result[1] = new Integer(lm);
            return result;
          }
          if (value != null)
          {
            result[0] = value;
            lm = i;
          }
          cur_node = node;
          div_state = Boolean.TRUE.booleanValue();
        }
      }
      else if (div_state)
      {
        p0 = i;
        div_state = Boolean.FALSE.booleanValue();
      }
    }
    cur_node = cur_node.get(new String(ps, p0, ps.length - p0));
    if ((cur_node != null) && (value != null))
    {
      result[0] = value;
      lm = ps.length;
    }
    result[1] = new Integer(lm);
    return result;
  }
  
  private final class TreeNode
  {
    Map<String, TreeNode> children;
    Object value;
    
    private TreeNode() {}
    
    public Set<String> keys()
    {
      return children == null ? Collections.EMPTY_SET : children.keySet();
    }
    
    public void put(String name, TreeNode node)
    {
      if (children == null) {
        children = new HashMap();
      }
      children.put(name, node);
    }
    
    public TreeNode get(String pc)
    {
      return children != null ? (TreeNode)children.get(pc) : null;
    }
  }
}

/* Location:
 * Qualified Name:     net.winstone.relocate.TreePath
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.relocate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import net.winstone.util.FileUtils;

public class UnWar
{
  private final File warDirectory;
  
  public UnWar(String webappDir)
    throws IllegalStateException
  {
    if (webappDir == null) {
      warDirectory = new File(System.getProperty("user.dir") + File.separator + "localhost" + File.separator + "webapps");
    } else {
      warDirectory = new File(webappDir);
    }
    if (!warDirectory.exists()) {
      warDirectory.mkdirs();
    }
    if (!warDirectory.isDirectory()) {
      throw new IllegalStateException(String.format("WarDirectory %s is not a directory!", new Object[] { warDirectory.getAbsolutePath() }));
    }
  }
  
  public void deploy(File warFile)
    throws IllegalStateException
  {
    if (!warFile.exists()) {
      throw new IllegalStateException(String.format("War file %s did not exists.", new Object[] { warFile.getAbsolutePath() }));
    }
    String context = warFile.getName();
    int index = context.lastIndexOf(".");
    if (index > 0) {
      context = context.substring(0, index);
    }
    ZipFile zipFile = null;
    try
    {
      File targetDirectory = new File(warDirectory, context);
      if (!targetDirectory.exists()) {
        targetDirectory.mkdirs();
      }
      if (!targetDirectory.isDirectory()) {
        throw new IllegalStateException(String.format("Target deployement directory %s is not a directory!", new Object[] { targetDirectory.getAbsolutePath() }));
      }
      zipFile = new ZipFile(warFile);
      Enumeration<? extends ZipEntry> entries = zipFile.entries();
      for (;;)
      {
        if (entries.hasMoreElements())
        {
          ZipEntry ze = (ZipEntry)entries.nextElement();
          String en = ze.getName();
          if (File.separatorChar == '/') {
            en = en.replace('\\', File.separatorChar);
          }
          File outFile = new File(targetDirectory, en);
          if (ze.isDirectory())
          {
            outFile.mkdirs();
          }
          else
          {
            OutputStream os = null;
            InputStream is = null;
            File parentFile = outFile.getParentFile();
            if (parentFile.exists() == Boolean.FALSE.booleanValue()) {
              parentFile.mkdirs();
            }
            if ((outFile.exists()) && (outFile.lastModified() >= ze.getTime())) {
              continue;
            }
            try
            {
              os = new FileOutputStream(outFile);
              is = zipFile.getInputStream(ze);
              FileUtils.copyStream(is, os);
              outFile.setLastModified(ze.getTime());
              try
              {
                os.close();
              }
              catch (Exception e2) {}
              try
              {
                is.close();
              }
              catch (Exception e2) {}
            }
            catch (IOException ioe2) {}finally
            {
              try
              {
                os.close();
              }
              catch (Exception e2) {}
              try
              {
                is.close();
              }
              catch (Exception e2) {}
            }
          }
        }
      }
    }
    catch (ZipException e)
    {
      throw new IllegalStateException("Invalid .war format", e);
    }
    catch (IOException e)
    {
      throw new IllegalStateException("Can't read " + warFile + "/ " + e.getMessage(), e);
    }
    finally
    {
      try
      {
        zipFile.close();
      }
      catch (Exception e) {}
      zipFile = null;
    }
  }
}

/* Location:
 * Qualified Name:     net.winstone.relocate.UnWar
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone;

class Server$1 {}

/* Location:
 * Qualified Name:     net.winstone.Server.1
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone;

import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import net.winstone.boot.Command;
import net.winstone.cluster.Cluster;
import net.winstone.core.HostConfiguration;
import net.winstone.core.HostGroup;
import net.winstone.util.StringUtils;
import org.slf4j.Logger;

final class Server$ServerControlThread
  implements Runnable
{
  private static final transient int CONTROL_TIMEOUT = 2000;
  
  private Server$ServerControlThread(Server paramServer) {}
  
  public void run()
  {
    boolean interrupted = Boolean.FALSE.booleanValue();
    try
    {
      ServerSocket controlSocket = null;
      if (Server.access$100(this$0) > 0)
      {
        InetAddress inetAddress = null;
        String controlAddress = StringUtils.stringArg(Server.access$200(this$0), "controlAddress", null);
        if (controlAddress != null) {
          inetAddress = InetAddress.getByName(controlAddress);
        }
        if (inetAddress == null) {
          inetAddress = InetAddress.getLocalHost();
        }
        controlSocket = new ServerSocket(Server.access$100(this$0), 0, inetAddress);
        controlSocket.setSoTimeout(2000);
      }
      if (Server.logger.isInfoEnabled()) {
        Server.logger.info("{} running: controlPort={}", new Object[] { WinstoneResourceBundle.getInstance().getString("ServerVersion"), Server.access$100(this$0) > 0 ? Integer.toString(Server.access$100(this$0)) : "disabled" });
      }
      while (!interrupted)
      {
        Socket accepted = null;
        try
        {
          if (controlSocket != null)
          {
            accepted = controlSocket.accept();
            if (accepted != null) {
              handleControlRequest(accepted);
            }
          }
          else
          {
            Thread.sleep(2000L);
          }
        }
        catch (InterruptedIOException err) {}catch (InterruptedException err)
        {
          interrupted = Boolean.TRUE.booleanValue();
        }
        catch (Throwable err)
        {
          Server.logger.error("Error during listener init or shutdown", err);
        }
        finally
        {
          if (accepted != null) {
            try
            {
              accepted.close();
            }
            catch (IOException err) {}
          }
          if (Thread.interrupted()) {
            interrupted = Boolean.TRUE.booleanValue();
          }
        }
      }
      if (controlSocket != null) {
        controlSocket.close();
      }
    }
    catch (Throwable err)
    {
      Server.logger.error("Error during listener init or shutdown", err);
    }
    Server.logger.info("Winstone shutdown successfully");
  }
  
  protected void handleControlRequest(Socket csAccepted)
    throws IOException
  {
    InputStream inSocket = null;
    OutputStream outSocket = null;
    ObjectInputStream inControl = null;
    try
    {
      inSocket = csAccepted.getInputStream();
      int reqType = inSocket.read();
      if ((byte)reqType == Command.SHUTDOWN.getCode())
      {
        Server.logger.info("Shutdown request received via the controlPort. Commencing Winstone shutdowny");
        this$0.shutdown();
      }
      else if ((byte)reqType == Command.RELOAD.getCode())
      {
        inControl = new ObjectInputStream(inSocket);
        String host = inControl.readUTF();
        String prefix = inControl.readUTF();
        Server.logger.info("Reload request received via the controlPort. Commencing Winstone reload from {}{}", host, prefix);
        HostConfiguration hostConfig = Server.access$300(this$0).getHostByName(host);
        hostConfig.reloadWebApp(prefix);
      }
      else if (Server.access$400(this$0) != null)
      {
        outSocket = csAccepted.getOutputStream();
        Server.access$400(this$0).clusterRequest((byte)reqType, inSocket, outSocket, csAccepted, Server.access$300(this$0));
      }
      return;
    }
    finally
    {
      if (inControl != null) {
        try
        {
          inControl.close();
        }
        catch (IOException err) {}
      }
      if (inSocket != null) {
        try
        {
          inSocket.close();
        }
        catch (IOException err) {}
      }
      if (outSocket != null) {
        try
        {
          outSocket.close();
        }
        catch (IOException err) {}
      }
    }
  }
}

/* Location:
 * Qualified Name:     net.winstone.Server.ServerControlThread
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone;

import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import net.winstone.boot.Command;
import net.winstone.boot.ShutdownHook;
import net.winstone.cluster.Cluster;
import net.winstone.cluster.SimpleCluster;
import net.winstone.core.HostConfiguration;
import net.winstone.core.HostGroup;
import net.winstone.core.ObjectPool;
import net.winstone.core.listener.Ajp13Listener;
import net.winstone.core.listener.HttpListener;
import net.winstone.core.listener.HttpsListener;
import net.winstone.core.listener.Listener;
import net.winstone.jndi.JndiManager;
import net.winstone.jndi.resources.DataSourceConfig;
import net.winstone.util.LifeCycle;
import net.winstone.util.MapConverter;
import net.winstone.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Server
  implements LifeCycle
{
  protected static Logger logger = LoggerFactory.getLogger(Server.class);
  private final int DEFAULT_CONTROL_PORT = -1;
  private final Map<String, String> args;
  private Thread controlThread = null;
  private int controlPort = -1;
  private HostGroup hostGroup = null;
  private Cluster cluster = null;
  private ObjectPool objectPool = null;
  private final List<Listener> listeners = new ArrayList();
  private JndiManager globalJndiManager = null;
  
  public Server(Map<String, String> args)
    throws IllegalArgumentException
  {
    if (args == null) {
      throw new IllegalArgumentException("arg can not be null or empty");
    }
    this.args = args;
  }
  
  public void start()
  {
    initialize();
  }
  
  public void initialize()
  {
    try
    {
      logger.debug("Winstone startup arguments: {}", args.toString());
      initializeJndi();
      objectPool = new ObjectPool(args);
      controlPort = (args.get("controlPort") == null ? -1 : Integer.parseInt((String)args.get("controlPort")));
      initializeCluster();
      
      hostGroup = new HostGroup(cluster, objectPool, globalJndiManager, args);
      initializeListener();
      if (!listeners.isEmpty())
      {
        controlThread = new Thread(new ServerControlThread(null), "LauncherControlThread[ControlPort=" + Integer.toString(controlPort) + "]]");
        controlThread.setDaemon(Boolean.FALSE.booleanValue());
        controlThread.start();
      }
      Runtime.getRuntime().addShutdownHook(new ShutdownHook(this));
    }
    catch (IOException iOException)
    {
      try
      {
        destroy();
      }
      catch (Throwable e) {}
      throw new WinstoneException("Server.initialize", iOException);
    }
  }
  
  public void destroy()
  {
    if (listeners != null)
    {
      for (Listener listener : listeners) {
        listener.destroy();
      }
      listeners.clear();
    }
    if (objectPool != null)
    {
      objectPool.destroy();
      objectPool = null;
    }
    if (cluster != null)
    {
      cluster.destroy();
      cluster = null;
    }
    if (hostGroup != null)
    {
      hostGroup.destroy();
      hostGroup = null;
    }
    if (globalJndiManager != null)
    {
      globalJndiManager.destroy();
      globalJndiManager = null;
    }
    if (controlThread != null)
    {
      controlThread.interrupt();
      controlThread = null;
    }
  }
  
  public void shutdown()
  {
    logger.info("Winstone shutdown...");
    destroy();
    Thread.yield();
    logger.info("Exiting");
  }
  
  public boolean isRunning()
  {
    return (controlThread != null) && (controlThread.isAlive());
  }
  
  private void initializeListener()
    throws IOException
  {
    spawnListener(HttpListener.class.getName());
    spawnListener(Ajp13Listener.class.getName());
    try
    {
      Class.forName("javax.net.ServerSocketFactory");
      spawnListener(HttpsListener.class.getName());
    }
    catch (ClassNotFoundException err)
    {
      logger.debug("Listener class {} needs JDK1.4 support. Disabling", HttpsListener.class.getName());
    }
  }
  
  private void initializeCluster()
  {
    String useCluster = (String)args.get("useCluster");
    boolean switchOnCluster = (useCluster != null) && ((useCluster.equalsIgnoreCase("true")) || (useCluster.equalsIgnoreCase("yes")));
    if (switchOnCluster) {
      if (controlPort < 0)
      {
        logger.info("Clustering disabled - control port must be enabled");
      }
      else
      {
        String clusterClassName = StringUtils.stringArg(args, "clusterClassName", SimpleCluster.class.getName()).trim();
        try
        {
          Class<?> clusterClass = Class.forName(clusterClassName);
          Constructor<?> clusterConstructor = clusterClass.getConstructor(new Class[] { Map.class, Integer.class });
          cluster = ((Cluster)clusterConstructor.newInstance(new Object[] { args, new Integer(controlPort) }));
        }
        catch (Throwable err)
        {
          logger.error("WARNING: Error during startup of cluster implementation - ignoring", err);
        }
      }
    }
  }
  
  private void initializeJndi()
  {
    Iterator<String> i;
    if (StringUtils.booleanArg(args, "useJNDI", Boolean.FALSE.booleanValue()))
    {
      try
      {
        Class<?> ctxFactoryClass = Class.forName("net.winstone.jndi.url.java.javaURLContextFactory");
        if (System.getProperty("java.naming.factory.initial") == null) {
          System.setProperty("java.naming.factory.initial", ctxFactoryClass.getName());
        }
        if (System.getProperty("java.naming.factory.url.pkgs") == null) {
          System.setProperty("java.naming.factory.url.pkgs", "net.winstone.jndi");
        }
      }
      catch (ClassNotFoundException err)
      {
        logger.error("JNDI Error ", err);
      }
      String jndiMgrClassName = StringUtils.stringArg(args, "containerJndiClassName", JndiManager.class.getName()).trim();
      try
      {
        Class<?> jndiMgrClass = Class.forName(jndiMgrClassName);
        globalJndiManager = ((JndiManager)jndiMgrClass.newInstance());
        globalJndiManager.initialize();
        logger.info("JNDI Started {}", jndiMgrClass.getName());
      }
      catch (ClassNotFoundException err)
      {
        logger.error("JNDI disabled at container level - can't find JNDI Manager class", err);
      }
      catch (Throwable err)
      {
        logger.error("JNDI disabled at container level - couldn't load JNDI Manager: " + jndiMgrClassName, err);
      }
      Collection<String> keys = new ArrayList(args != null ? args.keySet() : new ArrayList());
      for (i = keys.iterator(); i.hasNext();)
      {
        String key = (String)i.next();
        if (key.startsWith("jndi.resource."))
        {
          String resourceName = key.substring(14);
          String className = (String)args.get(key);
          String value = (String)args.get("jndi.param." + resourceName + ".value");
          logger.debug("Creating object: {} from startup arguments", resourceName);
          createObject(resourceName.trim(), className.trim(), value, args);
        }
      }
    }
  }
  
  protected final boolean createObject(String name, String className, String value, Map<String, String> args)
  {
    if ((className == null) || (name == null)) {
      return Boolean.FALSE.booleanValue();
    }
    if (className.equals("javax.sql.DataSource")) {
      try
      {
        DataSourceConfig dataSourceConfig = (DataSourceConfig)MapConverter.apply(extractRelevantArgs(args, name), new DataSourceConfig());
        globalJndiManager.bind(dataSourceConfig);
        return Boolean.TRUE.booleanValue();
      }
      catch (Throwable err)
      {
        logger.error("Error building JDBC Datasource object " + name, err);
      }
    } else if (className.equals("javax.mail.Session")) {
      try
      {
        Properties p = new Properties();
        p.putAll(extractRelevantArgs(args, name));
        globalJndiManager.bindSmtpSession(name, p, Thread.currentThread().getContextClassLoader());
        return Boolean.TRUE.booleanValue();
      }
      catch (Throwable err)
      {
        logger.error("Error building JavaMail session " + name, err);
      }
    } else if (value != null) {
      try
      {
        globalJndiManager.bind(name, className, value, Thread.currentThread().getContextClassLoader());
        return Boolean.TRUE.booleanValue();
      }
      catch (Throwable err)
      {
        logger.error("Error building JNDI object " + name + " (class: " + className + ")", err);
      }
    }
    return Boolean.FALSE.booleanValue();
  }
  
  private Map<String, String> extractRelevantArgs(Map<String, String> input, String name)
  {
    Map<String, String> relevantArgs = new HashMap();
    for (Iterator<String> i = input.keySet().iterator(); i.hasNext();)
    {
      String key = (String)i.next();
      if (key.startsWith("jndi.param." + name + ".")) {
        relevantArgs.put(key.substring(12 + name.length()), input.get(key));
      }
    }
    relevantArgs.put("name", name);
    return relevantArgs;
  }
  
  protected final void spawnListener(String listenerClassName)
    throws IOException
  {
    try
    {
      Class<?> listenerClass = Class.forName(listenerClassName);
      Constructor<?> listenerConstructor = listenerClass.getConstructor(new Class[] { Map.class, ObjectPool.class, HostGroup.class });
      Listener listener = (Listener)listenerConstructor.newInstance(new Object[] { args, objectPool, hostGroup });
      if (listener.start()) {
        listeners.add(listener);
      }
    }
    catch (ClassNotFoundException err)
    {
      logger.warn("Listener {} not found / disabled - ignoring", listenerClassName);
    }
    catch (Throwable err)
    {
      logger.error("Error during listener startup " + listenerClassName, err);
      throw ((IOException)new IOException("Failed to start a listener: " + listenerClassName).initCause(err));
    }
  }
  
  private final class ServerControlThread
    implements Runnable
  {
    private static final transient int CONTROL_TIMEOUT = 2000;
    
    private ServerControlThread() {}
    
    public void run()
    {
      boolean interrupted = Boolean.FALSE.booleanValue();
      try
      {
        ServerSocket controlSocket = null;
        if (controlPort > 0)
        {
          InetAddress inetAddress = null;
          String controlAddress = StringUtils.stringArg(args, "controlAddress", null);
          if (controlAddress != null) {
            inetAddress = InetAddress.getByName(controlAddress);
          }
          if (inetAddress == null) {
            inetAddress = InetAddress.getLocalHost();
          }
          controlSocket = new ServerSocket(controlPort, 0, inetAddress);
          controlSocket.setSoTimeout(2000);
        }
        if (Server.logger.isInfoEnabled()) {
          Server.logger.info("{} running: controlPort={}", new Object[] { WinstoneResourceBundle.getInstance().getString("ServerVersion"), controlPort > 0 ? Integer.toString(controlPort) : "disabled" });
        }
        while (!interrupted)
        {
          Socket accepted = null;
          try
          {
            if (controlSocket != null)
            {
              accepted = controlSocket.accept();
              if (accepted != null) {
                handleControlRequest(accepted);
              }
            }
            else
            {
              Thread.sleep(2000L);
            }
          }
          catch (InterruptedIOException err) {}catch (InterruptedException err)
          {
            interrupted = Boolean.TRUE.booleanValue();
          }
          catch (Throwable err)
          {
            Server.logger.error("Error during listener init or shutdown", err);
          }
          finally
          {
            if (accepted != null) {
              try
              {
                accepted.close();
              }
              catch (IOException err) {}
            }
            if (Thread.interrupted()) {
              interrupted = Boolean.TRUE.booleanValue();
            }
          }
        }
        if (controlSocket != null) {
          controlSocket.close();
        }
      }
      catch (Throwable err)
      {
        Server.logger.error("Error during listener init or shutdown", err);
      }
      Server.logger.info("Winstone shutdown successfully");
    }
    
    protected void handleControlRequest(Socket csAccepted)
      throws IOException
    {
      InputStream inSocket = null;
      OutputStream outSocket = null;
      ObjectInputStream inControl = null;
      try
      {
        inSocket = csAccepted.getInputStream();
        int reqType = inSocket.read();
        if ((byte)reqType == Command.SHUTDOWN.getCode())
        {
          Server.logger.info("Shutdown request received via the controlPort. Commencing Winstone shutdowny");
          shutdown();
        }
        else if ((byte)reqType == Command.RELOAD.getCode())
        {
          inControl = new ObjectInputStream(inSocket);
          String host = inControl.readUTF();
          String prefix = inControl.readUTF();
          Server.logger.info("Reload request received via the controlPort. Commencing Winstone reload from {}{}", host, prefix);
          HostConfiguration hostConfig = hostGroup.getHostByName(host);
          hostConfig.reloadWebApp(prefix);
        }
        else if (cluster != null)
        {
          outSocket = csAccepted.getOutputStream();
          cluster.clusterRequest((byte)reqType, inSocket, outSocket, csAccepted, hostGroup);
        }
        return;
      }
      finally
      {
        if (inControl != null) {
          try
          {
            inControl.close();
          }
          catch (IOException err) {}
        }
        if (inSocket != null) {
          try
          {
            inSocket.close();
          }
          catch (IOException err) {}
        }
        if (outSocket != null) {
          try
          {
            outSocket.close();
          }
          catch (IOException err) {}
        }
      }
    }
  }
  
  public int getControlPort()
  {
    return controlPort;
  }
  
  public Map<String, String> getArgs()
  {
    return args;
  }
  
  public ObjectPool getObjectPool()
    throws IllegalStateException
  {
    if (!isRunning()) {
      throw new IllegalStateException("Server is not started");
    }
    return objectPool;
  }
  
  public HostGroup getHostGroup()
    throws IllegalStateException
  {
    if (hostGroup == null) {
      throw new IllegalStateException("Server is not started");
    }
    return hostGroup;
  }
  
  public JndiManager getJndiManager()
    throws IllegalStateException
  {
    if (!isRunning()) {
      throw new IllegalStateException("Server is not started");
    }
    return globalJndiManager;
  }
  
  public Cluster getCluster()
    throws IllegalStateException
  {
    if (!isRunning()) {
      throw new IllegalStateException("Server is not started");
    }
    return cluster;
  }
  
  public List<Listener> getListeners()
    throws IllegalStateException
  {
    if (!isRunning()) {
      throw new IllegalStateException("Server is not started");
    }
    return Collections.unmodifiableList(listeners);
  }
  
  public void info(String message)
  {
    logger.info(message);
  }
}

/* Location:
 * Qualified Name:     net.winstone.Server
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import net.winstone.WinstoneResourceBundle;
import net.winstone.util.StringUtils;

public class ErrorServlet
  extends HttpServlet
{
  private static final long serialVersionUID = -1210902945433492424L;
  private String template;
  private String serverVersion;
  
  public void init(ServletConfig config)
    throws ServletException
  {
    super.init(config);
    template = WinstoneResourceBundle.getInstance().getString("WinstoneResponse.ErrorPage");
    serverVersion = WinstoneResourceBundle.getInstance().getString("ServerVersion");
  }
  
  public void service(ServletRequest request, ServletResponse response)
    throws ServletException, IOException
  {
    Integer sc = (Integer)request.getAttribute("javax.servlet.error.status_code");
    String msg = (String)request.getAttribute("javax.servlet.error.message");
    Throwable err = (Throwable)request.getAttribute("javax.servlet.error.exception");
    
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    if (err != null) {
      err.printStackTrace(pw);
    } else {
      pw.println("(none)");
    }
    pw.flush();
    
    String output = StringUtils.replaceToken(template, new String[] { sc != null ? sc.toString() : "", msg == null ? "" : StringUtils.htmlEscapeBasicMarkup(msg), StringUtils.htmlEscapeBasicMarkup(sw.toString()), serverVersion, new Date().toString() });
    
    response.setContentLength(output.getBytes(response.getCharacterEncoding()).length);
    Writer out = response.getWriter();
    out.write(output);
    out.flush();
  }
}

/* Location:
 * Qualified Name:     net.winstone.servlet.ErrorServlet
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.servlet;

import java.io.IOException;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.winstone.core.Mapping;
import net.winstone.core.ServletConfiguration;
import net.winstone.core.SimpleRequestDispatcher;
import net.winstone.core.WebAppConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class InvokerServlet
  extends HttpServlet
{
  private static final long serialVersionUID = -2502687199563269260L;
  protected static Logger logger = LoggerFactory.getLogger(InvokerServlet.class);
  private static final String INCLUDE_PATH_INFO = "javax.servlet.include.path_info";
  private Map<String, ServletConfiguration> mountedInstances;
  private final Boolean mountedInstancesSemaphore = Boolean.TRUE;
  
  public void init(ServletConfig config)
    throws ServletException
  {
    super.init(config);
    mountedInstances = new Hashtable();
  }
  
  public void destroy()
  {
    if (mountedInstances != null) {
      synchronized (mountedInstancesSemaphore)
      {
        for (Iterator<ServletConfiguration> i = mountedInstances.values().iterator(); i.hasNext();) {
          ((ServletConfiguration)i.next()).destroy();
        }
        mountedInstances.clear();
      }
    }
    mountedInstances = null;
  }
  
  protected ServletConfiguration getInvokableInstance(String servletName)
    throws ServletException, IOException
  {
    ServletConfiguration sc = null;
    synchronized (mountedInstancesSemaphore)
    {
      if (mountedInstances.containsKey(servletName)) {
        sc = (ServletConfiguration)mountedInstances.get(servletName);
      }
    }
    if (sc == null) {
      try
      {
        sc = new ServletConfiguration((WebAppConfiguration)getServletContext(), getServletConfig().getServletName() + ":" + servletName, servletName, new Hashtable(), -1);
        mountedInstances.put(servletName, sc);
        logger.debug("{}: Mounting servlet class {}", servletName, getServletConfig().getServletName());
        
        sc.ensureInitialization();
      }
      catch (Throwable err)
      {
        sc = null;
      }
    }
    return sc;
  }
  
  protected void doGet(HttpServletRequest req, HttpServletResponse rsp)
    throws ServletException, IOException
  {
    boolean isInclude = req.getAttribute("javax.servlet.include.path_info") != null;
    
    String servletName = null;
    if (isInclude) {
      servletName = (String)req.getAttribute("javax.servlet.include.path_info");
    } else if (req.getPathInfo() != null) {
      servletName = req.getPathInfo();
    } else {
      servletName = "";
    }
    if (servletName.startsWith("/")) {
      servletName = servletName.substring(1);
    }
    ServletConfiguration invokedServlet = getInvokableInstance(servletName);
    if (invokedServlet == null)
    {
      String msg = "There was no invokable servlet found matching the URL: " + servletName;
      logger.warn(msg);
      rsp.sendError(404, msg);
    }
    else
    {
      SimpleRequestDispatcher rd = new SimpleRequestDispatcher((WebAppConfiguration)getServletContext(), invokedServlet);
      rd.setForNamedDispatcher(new Mapping[0], new Mapping[0]);
      rd.forward(req, rsp);
    }
  }
  
  protected void doPost(HttpServletRequest req, HttpServletResponse rsp)
    throws ServletException, IOException
  {
    doGet(req, rsp);
  }
}

/* Location:
 * Qualified Name:     net.winstone.servlet.InvokerServlet
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package net.winstone.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.StringWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.winstone.WinstoneResourceBundle;
import net.winstone.core.WinstoneRequest;
import net.winstone.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class StaticResourceServlet
  extends HttpServlet
{
  protected Logger logger = LoggerFactory.getLogger(getClass());
  private static final long serialVersionUID = 6699448605081774638L;
  static final String FORWARD_SERVLET_PATH = "javax.servlet.forward.servlet_path";
  static final String INCLUDE_SERVLET_PATH = "javax.servlet.include.servlet_path";
  static final String CACHED_RESOURCE_DATE_HEADER = "If-Modified-Since";
  static final String LAST_MODIFIED_DATE_HEADER = "Last-Modified";
  static final String RANGE_HEADER = "Range";
  static final String ACCEPT_RANGES_HEADER = "Accept-Ranges";
  static final String CONTENT_RANGE_HEADER = "Content-Range";
  private File webRoot;
  private String prefix;
  private boolean directoryList;
  private String serverVersion;
  private String oddColour;
  private String evenColour;
  private String rowTextColour;
  private String directoryLabel;
  private String parentDirLabel;
  private String noDateLabel;
  private String headerColour;
  private String headerTextColour;
  private String labelColour;
  private String labelTextColour;
  private String rowTemplate;
  private String bodyTemplate;
  
  public void init(ServletConfig config)
    throws ServletException
  {
    super.init(config);
    webRoot = new File(config.getInitParameter("webRoot"));
    prefix = config.getInitParameter("prefix");
    String dirList = config.getInitParameter("directoryList");
    directoryList = ((dirList == null) || (dirList.equalsIgnoreCase("true")) || (dirList.equalsIgnoreCase("yes")));
    serverVersion = WinstoneResourceBundle.getInstance().getString("ServerVersion");
    
    oddColour = StringUtils.get(config.getInitParameter("oddColour"), "#dddddd");
    evenColour = StringUtils.get(config.getInitParameter("evenColour"), "#cbcbcb");
    rowTextColour = StringUtils.get(config.getInitParameter("rowTextColour"), "#000033");
    directoryLabel = StringUtils.get(config.getInitParameter("directoryLabel"), "directory");
    parentDirLabel = StringUtils.get(config.getInitParameter("parentDirLabel"), "(parent directory)");
    noDateLabel = StringUtils.get(config.getInitParameter("noDateLabel"), "-");
    
    headerColour = StringUtils.get(config.getInitParameter("headerColour"), "#ffffff");
    headerTextColour = StringUtils.get(config.getInitParameter("headerTextColour"), "#000033");
    labelColour = StringUtils.get(config.getInitParameter("labelColour"), "#aeaeae");
    labelTextColour = StringUtils.get(config.getInitParameter("labelTextColour"), "#ffffff");
    
    rowTemplate = WinstoneResourceBundle.getInstance().getString("StaticResourceServlet.Row");
    bodyTemplate = WinstoneResourceBundle.getInstance().getString("StaticResourceServlet.Body");
  }
  
  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    doGet(request, response);
  }
  
  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    boolean isInclude = request.getAttribute("javax.servlet.include.servlet_path") != null;
    boolean isForward = request.getAttribute("javax.servlet.forward.servlet_path") != null;
    String path = null;
    if (isInclude) {
      path = (String)request.getAttribute("javax.servlet.include.servlet_path");
    } else {
      path = request.getServletPath();
    }
    path = WinstoneRequest.decodePathURLToken(path);
    
    long cachedResDate = request.getDateHeader("If-Modified-Since");
    logger.debug("{}: path={}", getServletConfig().getServletName(), path);
    
    File res = path.equals("") ? webRoot : new File(webRoot, path);
    if (!res.exists())
    {
      response.sendError(404, StringUtils.replaceToken("File {} not found", new String[] { path }));
    }
    else if (!isDescendant(webRoot, res, webRoot))
    {
      logger.debug("Requested path {} was outside the webroot {}", res.getCanonicalPath(), webRoot.toString());
      response.sendError(403, StringUtils.replaceToken("Illegal path error - {}", new String[] { path }));
    }
    else if ((!isInclude) && (!isForward) && (isDescendant(new File(webRoot, "WEB-INF"), res, webRoot)))
    {
      response.sendError(404, StringUtils.replaceToken("Illegal path error - {}", new String[] { path }));
    }
    else if ((!isInclude) && (!isForward) && (isDescendant(new File(webRoot, "META-INF"), res, webRoot)))
    {
      response.sendError(404, StringUtils.replaceToken("Illegal path error - {}", new String[] { path }));
    }
    else if (res.isDirectory())
    {
      if (path.endsWith("/"))
      {
        if (directoryList) {
          generateDirectoryList(request, response, path);
        } else {
          response.sendError(403, "Access to this resource is denied");
        }
      }
      else {
        response.sendRedirect(prefix + path + "/");
      }
    }
    else if ((!isInclude) && (cachedResDate != -1L) && (cachedResDate < System.currentTimeMillis() / 1000L * 1000L) && (cachedResDate >= res.lastModified() / 1000L * 1000L))
    {
      String mimeType = getServletContext().getMimeType(res.getName().toLowerCase());
      if (mimeType != null) {
        response.setContentType(mimeType);
      }
      response.setStatus(304);
      response.setContentLength(0);
      response.flushBuffer();
    }
    else if ((request.getHeader("Range") == null) || (isInclude))
    {
      String mimeType = getServletContext().getMimeType(res.getName().toLowerCase());
      if (mimeType != null) {
        response.setContentType(mimeType);
      }
      InputStream resStream = new FileInputStream(res);
      
      response.setStatus(200);
      response.setContentLength((int)res.length());
      
      response.addDateHeader("Last-Modified", res.lastModified());
      OutputStream out = null;
      Writer outWriter = null;
      try
      {
        out = response.getOutputStream();
      }
      catch (IllegalStateException err)
      {
        outWriter = response.getWriter();
      }
      catch (IllegalArgumentException err)
      {
        outWriter = response.getWriter();
      }
      byte[] buffer = new byte['?'];
      int read = resStream.read(buffer);
      while (read > 0)
      {
        if (out != null) {
          out.write(buffer, 0, read);
        } else {
          outWriter.write(new String(buffer, 0, read, response.getCharacterEncoding()));
        }
        read = resStream.read(buffer);
      }
      resStream.close();
    }
    else if (request.getHeader("Range").startsWith("bytes="))
    {
      String mimeType = getServletContext().getMimeType(res.getName().toLowerCase());
      if (mimeType != null) {
        response.setContentType(mimeType);
      }
      InputStream resStream = new FileInputStream(res);
      
      List<String> ranges = new ArrayList();
      StringTokenizer st = new StringTokenizer(request.getHeader("Range").substring(6).trim(), ",", Boolean.FALSE.booleanValue());
      int totalSent = 0;
      String rangeText = "";
      while (st.hasMoreTokens())
      {
        String rangeBlock = st.nextToken();
        int start = 0;
        int end = (int)res.length();
        int delim = rangeBlock.indexOf('-');
        if (delim != 0) {
          start = Integer.parseInt(rangeBlock.substring(0, delim).trim());
1 2 3 4 5 6 7 8 9 10 11 12 13 14

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2019. Infinite Loop Ltd