wms-winstone-1.0.5

ic String getPathInfo()
  {
    return pathInfo;
  }
  
  public String getProtocol()
  {
    return protocol;
  }
  
  public String getQueryString()
  {
    return queryString;
  }
  
  public String getScheme()
  {
    return scheme;
  }
  
  public String getServletPath()
  {
    return servletPath;
  }
  
  public String getContextPath()
  {
    return contextPath;
  }
}

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import net.winstone.WinstoneException;
import net.winstone.core.ObjectPool;
import net.winstone.core.WinstoneInputStream;
import net.winstone.core.WinstoneRequest;
import net.winstone.util.SizeRestrictedHashMap;
import net.winstone.util.SizeRestrictedHashtable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class RetryRequestWrapper
  extends HttpServletRequestWrapper
{
  protected static Logger logger = LoggerFactory.getLogger(RetryRequestWrapper.class);
  private static final transient String METHOD_HEAD = "GET";
  private static final transient String METHOD_GET = "GET";
  private static final transient String METHOD_POST = "POST";
  private static final transient String POST_PARAMETERS = "application/x-www-form-urlencoded";
  protected static final DateFormat headerDF = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
  private final RetryRequestParams oldRequest;
  private String encoding;
  private Map parsedParams;
  private ServletInputStream inData;
  
  static
  {
    headerDF.setTimeZone(TimeZone.getTimeZone("GMT"));
  }
  
  public RetryRequestWrapper(HttpServletRequest request, RetryRequestParams oldRequest)
    throws IOException
  {
    super(request);
    this.oldRequest = oldRequest;
    encoding = this.oldRequest.getEncoding();
  }
  
  private boolean hasBeenForwarded()
  {
    return super.getAttribute("javax.servlet.forward.request_uri") != null;
  }
  
  public String getScheme()
  {
    if (hasBeenForwarded()) {
      return super.getScheme();
    }
    return oldRequest.getScheme();
  }
  
  public String getMethod()
  {
    if (hasBeenForwarded()) {
      return super.getMethod();
    }
    return oldRequest.getMethod();
  }
  
  public String getContextPath()
  {
    if (hasBeenForwarded()) {
      return super.getContextPath();
    }
    return oldRequest.getContextPath();
  }
  
  public String getServletPath()
  {
    if (hasBeenForwarded()) {
      return super.getServletPath();
    }
    return oldRequest.getServletPath();
  }
  
  public String getPathInfo()
  {
    if (hasBeenForwarded()) {
      return super.getPathInfo();
    }
    return oldRequest.getPathInfo();
  }
  
  public String getQueryString()
  {
    if (hasBeenForwarded()) {
      return super.getQueryString();
    }
    return oldRequest.getQueryString();
  }
  
  public String getRequestURI()
  {
    if (hasBeenForwarded()) {
      return super.getRequestURI();
    }
    String contextPath = oldRequest.getContextPath();
    String servletPath = oldRequest.getServletPath();
    String pathInfo = oldRequest.getPathInfo();
    String queryString = oldRequest.getQueryString();
    return contextPath + servletPath + (pathInfo == null ? "" : pathInfo) + (queryString == null ? "" : new StringBuilder().append("?").append(queryString).toString());
  }
  
  public String getCharacterEncoding()
  {
    if (hasBeenForwarded()) {
      return super.getCharacterEncoding();
    }
    return oldRequest.getEncoding();
  }
  
  public void setCharacterEncoding(String encoding)
    throws UnsupportedEncodingException
  {
    if (hasBeenForwarded()) {
      super.setCharacterEncoding(encoding);
    } else {
      this.encoding = encoding;
    }
  }
  
  public int getContentLength()
  {
    if (hasBeenForwarded()) {
      return super.getContentLength();
    }
    return oldRequest.getContentLength();
  }
  
  public String getContentType()
  {
    if (hasBeenForwarded()) {
      return super.getContentType();
    }
    return oldRequest.getContentType();
  }
  
  public Locale getLocale()
  {
    if (hasBeenForwarded()) {
      return super.getLocale();
    }
    return oldRequest.getLocale();
  }
  
  public Enumeration getLocales()
  {
    if (hasBeenForwarded()) {
      return super.getLocales();
    }
    return Collections.enumeration(oldRequest.getLocales());
  }
  
  public int getIntHeader(String name)
  {
    if (hasBeenForwarded()) {
      return super.getIntHeader(name);
    }
    String header = getHeader(name);
    return header == null ? -1 : Integer.parseInt(header);
  }
  
  public String getHeader(String name)
  {
    if (hasBeenForwarded()) {
      return super.getHeader(name);
    }
    Enumeration e = getHeaders(name);
    return (e != null) && (e.hasMoreElements()) ? (String)e.nextElement() : null;
  }
  
  public Enumeration getHeaderNames()
  {
    if (hasBeenForwarded()) {
      return super.getHeaderNames();
    }
    return Collections.enumeration(oldRequest.getHeaders().keySet());
  }
  
  public Enumeration getHeaders(String name)
  {
    if (hasBeenForwarded()) {
      return super.getHeaders(name);
    }
    return (Enumeration)oldRequest.getHeaders().get(name.toLowerCase());
  }
  
  public String getParameter(String name)
  {
    if (hasBeenForwarded()) {
      return super.getParameter(name);
    }
    parseRequestParameters();
    Object param = parsedParams.get(name);
    if (param == null) {
      return null;
    }
    if ((param instanceof String)) {
      return (String)param;
    }
    if ((param instanceof String[])) {
      return ((String[])(String[])param)[0];
    }
    return param.toString();
  }
  
  public Enumeration getParameterNames()
  {
    if (hasBeenForwarded()) {
      return super.getParameterNames();
    }
    parseRequestParameters();
    return Collections.enumeration(parsedParams.keySet());
  }
  
  public String[] getParameterValues(String name)
  {
    if (hasBeenForwarded()) {
      return super.getParameterValues(name);
    }
    parseRequestParameters();
    Object param = parsedParams.get(name);
    if (param == null) {
      return null;
    }
    if ((param instanceof String)) {
      return new String[] { (String)param };
    }
    if ((param instanceof String[])) {
      return (String[])param;
    }
    throw new WinstoneException("Unknown param type: " + name + " - " + param.getClass());
  }
  
  public Map getParameterMap()
  {
    if (hasBeenForwarded()) {
      return super.getParameterMap();
    }
    Map<String, String[]> paramMap = new SizeRestrictedHashtable(ObjectPool.getMaximumAllowedParameter());
    for (Enumeration names = getParameterNames(); names.hasMoreElements();)
    {
      String name = (String)names.nextElement();
      paramMap.put(name, getParameterValues(name));
    }
    return paramMap;
  }
  
  public BufferedReader getReader()
    throws IOException
  {
    if (hasBeenForwarded()) {
      return super.getReader();
    }
    if (getCharacterEncoding() != null) {
      return new BufferedReader(new InputStreamReader(getInputStream(), encoding));
    }
    return new BufferedReader(new InputStreamReader(getInputStream()));
  }
  
  public ServletInputStream getInputStream()
    throws IOException
  {
    if (hasBeenForwarded()) {
      return super.getInputStream();
    }
    if (parsedParams != null) {
      logger.debug("Called getInputStream after getParameter ... error");
    }
    if (inData == null) {
      inData = new WinstoneInputStream(oldRequest.getBodyContent());
    }
    return inData;
  }
  
  private void parseRequestParameters()
  {
    if (inData != null) {
      logger.warn("Called getInputStream after getParameter ... error");
    }
    if (parsedParams == null)
    {
      String contentType = oldRequest.getContentType();
      String queryString = oldRequest.getQueryString();
      String method = oldRequest.getMethod();
      Map workingParameters = new SizeRestrictedHashMap(ObjectPool.getMaximumAllowedParameter());
      try
      {
        if (((method.equals("GET")) || (method.equals("GET")) || (method.equals("POST"))) && (queryString != null)) {
          WinstoneRequest.extractParameters(queryString, encoding, workingParameters, Boolean.FALSE.booleanValue());
        }
        if ((method.equals("POST")) && (contentType != null) && ((contentType.equals("application/x-www-form-urlencoded")) || (contentType.startsWith("application/x-www-form-urlencoded;"))))
        {
          String paramLine = encoding == null ? new String(oldRequest.getBodyContent()) : new String(oldRequest.getBodyContent(), encoding);
          WinstoneRequest.extractParameters(paramLine.trim(), encoding, workingParameters, Boolean.FALSE.booleanValue());
        }
        parsedParams = workingParameters;
      }
      catch (UnsupportedEncodingException err)
      {
        logger.error("Error parsing request parameters", err);
        parsedParams = null;
      }
    }
  }
  
  /* Error */
  public long getDateHeader(String name)
  {
    // Byte code:
    //   0: aload_0
    //   1: invokespecial 7	net/winstone/core/authentication/RetryRequestWrapper:hasBeenForwarded	()Z
    //   4: ifeq +9 -> 13
    //   7: aload_0
    //   8: aload_1
    //   9: invokespecial 38	javax/servlet/http/HttpServletRequestWrapper:getDateHeader	(Ljava/lang/String;)J
    //   12: lreturn
    //   13: aload_0
    //   14: aload_1
    //   15: invokevirtual 39	net/winstone/core/authentication/RetryRequestWrapper:getHeader	(Ljava/lang/String;)Ljava/lang/String;
    //   18: astore_2
    //   19: aload_2
    //   20: ifnonnull +7 -> 27
    //   23: ldc2_w 40
    //   26: lreturn
    //   27: getstatic 42	net/winstone/core/authentication/RetryRequestWrapper:headerDF	Ljava/text/DateFormat;
    //   30: dup
    //   31: astore_3
    //   32: monitorenter
    //   33: getstatic 42	net/winstone/core/authentication/RetryRequestWrapper:headerDF	Ljava/text/DateFormat;
    //   36: aload_2
    //   37: invokevirtual 43	java/text/DateFormat:parse	(Ljava/lang/String;)Ljava/util/Date;
    //   40: invokevirtual 44	java/util/Date:getTime	()J
    //   43: aload_3
    //   44: monitorexit
    //   45: lreturn
    //   46: astore 4
    //   48: aload_3
    //   49: monitorexit
    //   50: aload 4
    //   52: athrow
    //   53: astore_3
    //   54: new 46	java/lang/IllegalArgumentException
    //   57: dup
    //   58: new 21	java/lang/StringBuilder
    //   61: dup
    //   62: invokespecial 22	java/lang/StringBuilder:<init>	()V
    //   65: ldc 47
    //   67: invokevirtual 23	java/lang/StringBuilder:append	(Ljava/lang/String;)Ljava/lang/StringBuilder;
    //   70: aload_2
    //   71: invokevirtual 23	java/lang/StringBuilder:append	(Ljava/lang/String;)Ljava/lang/StringBuilder;
    //   74: invokevirtual 26	java/lang/StringBuilder:toString	()Ljava/lang/String;
    //   77: invokespecial 48	java/lang/IllegalArgumentException:<init>	(Ljava/lang/String;)V
    //   80: athrow
    // Line number table:
    //   Java source line #202	-> byte code offset #0
    //   Java source line #203	-> byte code offset #7
    //   Java source line #205	-> byte code offset #13
    //   Java source line #206	-> byte code offset #19
    //   Java source line #207	-> byte code offset #23
    //   Java source line #210	-> byte code offset #27
    //   Java source line #211	-> byte code offset #33
    //   Java source line #212	-> byte code offset #46
    //   Java source line #213	-> byte code offset #53
    //   Java source line #214	-> byte code offset #54
    // Local variable table:
    //   start	length	slot	name	signature
    //   0	81	0	this	RetryRequestWrapper
    //   0	81	1	name	String
    //   18	53	2	dateHeader	String
    //   31	18	3	Ljava/lang/Object;	Object
    //   53	2	3	err	java.text.ParseException
    //   46	5	4	localObject1	Object
    // Exception table:
    //   from	to	target	type
    //   33	45	46	finally
    //   46	50	46	finally
    //   27	45	53	java/text/ParseException
    //   46	53	53	java/text/ParseException
  }
}

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

import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import net.winstone.core.Mapping;
import net.winstone.core.WebAppConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public final class SecurityConstraint
{
  protected static Logger logger = LoggerFactory.getLogger(SecurityConstraint.class);
  private static final transient String ELEM_DISPLAY_NAME = "display-name";
  private static final transient String ELEM_WEB_RESOURCES = "web-resource-collection";
  private static final transient String ELEM_URL_PATTERN = "url-pattern";
  private static final transient String ELEM_HTTP_METHOD = "http-method";
  private static final transient String ELEM_AUTH_CONSTRAINT = "auth-constraint";
  private static final transient String ELEM_ROLE_NAME = "role-name";
  private static final transient String ELEM_USER_DATA_CONSTRAINT = "user-data-constraint";
  private static final transient String ELEM_TRANSPORT_GUARANTEE = "transport-guarantee";
  private static final transient String GUARANTEE_NONE = "NONE";
  private String displayName;
  private final String[] methodSets;
  private final Mapping[] urlPatterns;
  private final String[] rolesAllowed;
  private boolean needsSSL;
  
  public SecurityConstraint(Node elm, Set rolesAllowed, int counter)
  {
    needsSSL = Boolean.FALSE.booleanValue();
    Set localUrlPatternList = new HashSet();
    Set localMethodSetList = new HashSet();
    Set localRolesAllowed = new HashSet();
    for (int i = 0; i < elm.getChildNodes().getLength(); i++)
    {
      Node child = elm.getChildNodes().item(i);
      if (child.getNodeType() == 1) {
        if (child.getNodeName().equals("display-name"))
        {
          displayName = WebAppConfiguration.getTextFromNode(child);
        }
        else if (child.getNodeName().equals("web-resource-collection"))
        {
          String methodSet = null;
          for (int k = 0; k < child.getChildNodes().getLength(); k++)
          {
            Node resourceChild = child.getChildNodes().item(k);
            if (resourceChild.getNodeType() == 1)
            {
              String resourceChildNodeName = resourceChild.getNodeName();
              if (resourceChildNodeName.equals("url-pattern")) {
                localUrlPatternList.add(Mapping.createFromURL("Security", WebAppConfiguration.getTextFromNode(resourceChild)));
              } else if (resourceChildNodeName.equals("http-method")) {
                methodSet = (methodSet == null ? "." : methodSet) + WebAppConfiguration.getTextFromNode(resourceChild) + ".";
              }
            }
          }
          localMethodSetList.add(methodSet == null ? ".ALL." : methodSet);
        }
        else if (child.getNodeName().equals("auth-constraint"))
        {
          for (int k = 0; k < child.getChildNodes().getLength(); k++)
          {
            Node roleChild = child.getChildNodes().item(k);
            if ((roleChild.getNodeType() == 1) && (roleChild.getNodeName().equals("role-name")))
            {
              String roleName = WebAppConfiguration.getTextFromNode(roleChild);
              if (roleName.equals("*")) {
                localRolesAllowed.addAll(rolesAllowed);
              } else {
                localRolesAllowed.add(roleName);
              }
            }
          }
        }
        else if (child.getNodeName().equals("user-data-constraint"))
        {
          for (int k = 0; k < child.getChildNodes().getLength(); k++)
          {
            Node roleChild = child.getChildNodes().item(k);
            if ((roleChild.getNodeType() == 1) && (roleChild.getNodeName().equals("transport-guarantee"))) {
              needsSSL = (!WebAppConfiguration.getTextFromNode(roleChild).equalsIgnoreCase("NONE"));
            }
          }
        }
      }
    }
    urlPatterns = ((Mapping[])localUrlPatternList.toArray(new Mapping[0]));
    methodSets = ((String[])localMethodSetList.toArray(new String[0]));
    this.rolesAllowed = ((String[])localRolesAllowed.toArray(new String[0]));
    if (displayName == null) {
      displayName = ("Security Constraint #" + counter);
    }
  }
  
  public boolean isAllowed(HttpServletRequest request)
  {
    for (int n = 0; n < rolesAllowed.length; n++) {
      if (request.isUserInRole(rolesAllowed[n]))
      {
        logger.debug("Passed security constraint: {} role: {}", displayName, rolesAllowed[n]);
        return Boolean.TRUE.booleanValue();
      }
    }
    logger.debug("Failed security constraint: {}", displayName);
    return Boolean.FALSE.booleanValue();
  }
  
  public boolean isApplicable(String url, String method)
  {
    for (int n = 0; n < urlPatterns.length; n++) {
      if ((urlPatterns[n].match(url, null, null)) && (methodCheck(method, methodSets[n]))) {
        return Boolean.TRUE.booleanValue();
      }
    }
    return Boolean.FALSE.booleanValue();
  }
  
  private boolean methodCheck(String protocol, String methodSet)
  {
    return (methodSet.equals(".ALL.")) || (methodSet.indexOf("." + protocol.toUpperCase() + ".") != -1);
  }
  
  public boolean needsSSL()
  {
    return needsSSL;
  }
  
  public String getName()
  {
    return displayName;
  }
}

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

import java.io.IOException;
import java.io.OutputStream;

public class ClientOutputStream
  extends OutputStream
{
  private final OutputStream out;
  
  public ClientOutputStream(OutputStream out)
  {
    this.out = out;
  }
  
  public void write(int b)
    throws ClientSocketException
  {
    try
    {
      out.write(b);
    }
    catch (IOException e)
    {
      throw new ClientSocketException(e);
    }
  }
  
  public void write(byte[] b)
    throws ClientSocketException
  {
    try
    {
      out.write(b);
    }
    catch (IOException e)
    {
      throw new ClientSocketException(e);
    }
  }
  
  public void write(byte[] b, int off, int len)
    throws ClientSocketException
  {
    try
    {
      out.write(b, off, len);
    }
    catch (IOException e)
    {
      throw new ClientSocketException(e);
    }
  }
  
  public void flush()
    throws IOException
  {
    out.flush();
  }
  
  public void close()
    throws IOException
  {
    out.close();
  }
}

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

import java.io.IOException;

public class ClientSocketException
  extends IOException
{
  private static final long serialVersionUID = -8077788444680218850L;
  
  public ClientSocketException(Throwable cause)
  {
    super("Failed to write to client");
    initCause(cause);
  }
}

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

import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.UnavailableException;
import net.winstone.WinstoneException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class FilterConfiguration
  implements FilterConfig
{
  protected static Logger logger = LoggerFactory.getLogger(FilterConfiguration.class);
  private final String ELEM_NAME = "filter-name";
  private final String ELEM_CLASS = "filter-class";
  private final String ELEM_INIT_PARAM = "init-param";
  private final String ELEM_INIT_PARAM_NAME = "param-name";
  private final String ELEM_INIT_PARAM_VALUE = "param-value";
  private final Map<String, String> initParameters = new HashMap();
  private final ServletContext context;
  private final ClassLoader loader;
  private final Object filterSemaphore = Boolean.TRUE;
  private boolean unavailableException = Boolean.FALSE.booleanValue();
  private String filterName;
  private String classFile;
  private Filter instance;
  
  public FilterConfiguration(ServletContext context, ClassLoader loader, Node elm)
  {
    this.context = context;
    this.loader = loader;
    for (int n = 0; n < elm.getChildNodes().getLength(); n++)
    {
      Node child = elm.getChildNodes().item(n);
      if (child.getNodeType() == 1)
      {
        String nodeName = child.getNodeName();
        if (nodeName.equals("filter-name"))
        {
          filterName = WebAppConfiguration.getTextFromNode(child);
        }
        else if (nodeName.equals("filter-class"))
        {
          classFile = WebAppConfiguration.getTextFromNode(child);
        }
        else if (nodeName.equals("init-param"))
        {
          String paramName = null;
          String paramValue = null;
          for (int k = 0; k < child.getChildNodes().getLength(); k++)
          {
            Node paramNode = child.getChildNodes().item(k);
            if (paramNode.getNodeType() == 1) {
              if (paramNode.getNodeName().equals("param-name")) {
                paramName = WebAppConfiguration.getTextFromNode(paramNode);
              } else if (paramNode.getNodeName().equals("param-value")) {
                paramValue = WebAppConfiguration.getTextFromNode(paramNode);
              }
            }
          }
          if ((paramName != null) && (paramValue != null)) {
            initParameters.put(paramName, paramValue);
          }
        }
      }
    }
    logger.debug("Loaded filter instance {} class: {}]", filterName, classFile);
  }
  
  public String getFilterName()
  {
    return filterName;
  }
  
  public String getInitParameter(String paramName)
  {
    return (String)initParameters.get(paramName);
  }
  
  public Enumeration<String> getInitParameterNames()
  {
    return Collections.enumeration(initParameters.keySet());
  }
  
  public ServletContext getServletContext()
  {
    return context;
  }
  
  public Filter getFilter()
    throws ServletException
  {
    synchronized (filterSemaphore)
    {
      if (isUnavailable()) {
        throw new WinstoneException("This filter has been marked unavailable because of an earlier error");
      }
      if (instance == null) {
        try
        {
          ClassLoader cl = Thread.currentThread().getContextClassLoader();
          Thread.currentThread().setContextClassLoader(loader);
          
          Class<?> filterClass = Class.forName(classFile, Boolean.TRUE.booleanValue(), loader);
          Object object = filterClass.newInstance();
          logger.debug("{}: assignable {}", filterClass.getName(), Boolean.valueOf(Filter.class.isAssignableFrom(object.getClass())));
          instance = ((Filter)object);
          logger.debug("{}: init", filterName);
          instance.init(this);
          Thread.currentThread().setContextClassLoader(cl);
        }
        catch (ClassCastException err)
        {
          logger.error("Failed to load class: " + classFile, err);
        }
        catch (ClassNotFoundException err)
        {
          logger.error("Failed to load class: " + classFile, err);
        }
        catch (IllegalAccessException err)
        {
          logger.error("Failed to load class: " + classFile, err);
        }
        catch (InstantiationException err)
        {
          logger.error("Failed to load class: " + classFile, err);
        }
        catch (ServletException err)
        {
          instance = null;
          if ((err instanceof UnavailableException)) {
            setUnavailable();
          }
          throw err;
        }
      }
    }
    return instance;
  }
  
  public void destroy()
  {
    synchronized (filterSemaphore)
    {
      setUnavailable();
    }
  }
  
  public String toString()
  {
    return "FilterConfiguration[filterName=" + filterName + ", classFile=" + classFile + ']';
  }
  
  public boolean isUnavailable()
  {
    return unavailableException;
  }
  
  protected void setUnavailable()
  {
    unavailableException = Boolean.TRUE.booleanValue();
    if (instance != null)
    {
      logger.debug("{}: destroy", filterName);
      ClassLoader cl = Thread.currentThread().getContextClassLoader();
      Thread.currentThread().setContextClassLoader(loader);
      instance.destroy();
      Thread.currentThread().setContextClassLoader(cl);
      instance = null;
    }
  }
  
  public void execute(ServletRequest request, ServletResponse response, FilterChain chain)
    throws ServletException, IOException
  {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    Thread.currentThread().setContextClassLoader(loader);
    try
    {
      getFilter().doFilter(request, response, chain);
    }
    catch (UnavailableException err)
    {
      setUnavailable();
      throw new ServletException("Error in filter - marking unavailable", err);
    }
    finally
    {
      Thread.currentThread().setContextClassLoader(cl);
    }
  }
  
  public int hashCode()
  {
    int prime = 31;
    int result = 1;
    result = 31 * result + (filterName == null ? 0 : filterName.hashCode());
    return result;
  }
  
  public boolean equals(Object obj)
  {
    if (this == obj) {
      return Boolean.TRUE.booleanValue();
    }
    if (obj == null) {
      return Boolean.FALSE.booleanValue();
    }
    if (getClass() != obj.getClass()) {
      return Boolean.FALSE.booleanValue();
    }
    FilterConfiguration other = (FilterConfiguration)obj;
    if (filterName == null)
    {
      if (filterName != null) {
        return Boolean.FALSE.booleanValue();
      }
    }
    else if (!filterName.equals(filterName)) {
      return Boolean.FALSE.booleanValue();
    }
    return Boolean.TRUE.booleanValue();
  }
}

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

class HostConfiguration$1
  implements Runnable
{
  HostConfiguration$1(HostConfiguration paramHostConfiguration) {}
  
  public void run()
  {
    boolean interrupted = Boolean.FALSE.booleanValue();
    while (!interrupted) {
      try
      {
        Thread.sleep(60000L);
        HostConfiguration.access$000(this$0);
      }
      catch (InterruptedException err)
      {
        interrupted = Boolean.TRUE.booleanValue();
      }
    }
    HostConfiguration.access$102(this$0, null);
  }
}

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

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.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import net.winstone.WinstoneException;
import net.winstone.cluster.Cluster;
import net.winstone.jndi.JndiManager;
import net.winstone.util.FileUtils;
import net.winstone.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

public class HostConfiguration
{
  protected static Logger logger = LoggerFactory.getLogger(HostConfiguration.class);
  private static final long FLUSH_PERIOD = 60000L;
  private static final String WEB_INF = "WEB-INF";
  private static final String WEB_XML = "web.xml";
  private final String hostname;
  private final Map<String, String> args;
  private final Map<String, WebAppConfiguration> webapps;
  private final Cluster cluster;
  private final ObjectPool objectPool;
  private final JndiManager jndiManager;
  private Thread thread;
  private String defaultWebApp;
  
  public HostConfiguration(String hostname, Cluster cluster, ObjectPool objectPool, JndiManager jndiManager, Map<String, String> args, String webappsDirName)
  {
    webapps = new HashMap();
    
    this.hostname = hostname;
    this.args = args;
    this.cluster = cluster;
    this.objectPool = objectPool;
    this.jndiManager = jndiManager;
    defaultWebApp = StringUtils.stringArg(args, "defaultWebApp", "");
    if (webappsDirName == null)
    {
      File warfile = StringUtils.fileArg(args, "warfile");
      File webroot = StringUtils.fileArg(args, "webroot");
      if ((warfile != null) || (webroot != null))
      {
        String prefix = StringUtils.stringArg(args, "prefix", "");
        try
        {
          addWebAppConfiguration(prefix, getWebRoot(webroot, warfile), "webapp");
        }
        catch (IOException e)
        {
          logger.error("Error initializing web application: prefix [" + prefix + "]", e);
        }
      }
      String webroots = StringUtils.stringArg(args, "webroots", null);
      if (webroots != null)
      {
        StringTokenizer tokenizer = new StringTokenizer(webroots, ";");
        while (tokenizer.hasMoreTokens())
        {
          String root = tokenizer.nextToken();
          if (!"".equals(root))
          {
            File froot = new File(root);
            if (!froot.exists()) {
              logger.warn("WebRoot {} not exist. Skipping it", root);
            } else {
              deploy(froot, Boolean.FALSE.booleanValue());
            }
          }
        }
      }
    }
    else
    {
      File webappsDir = new File(webappsDirName);
      if (!webappsDir.exists()) {
        throw new WinstoneException("Webapps dir " + webappsDirName + " not found");
      }
      if (!webappsDir.isDirectory()) {
        throw new WinstoneException("Webapps dir " + webappsDirName + " is not a directory");
      }
      for (File aChildren : webappsDir.listFiles()) {
        deploy(aChildren, Boolean.TRUE.booleanValue());
      }
    }
    logger.debug("Initialized {} webapps: prefixes - {}", webapps.size() + "", webapps.keySet() + "");
    
    thread = new Thread(new Runnable()
    {
      public void run()
      {
        boolean interrupted = Boolean.FALSE.booleanValue();
        while (!interrupted) {
          try
          {
            Thread.sleep(60000L);
            HostConfiguration.this.invalidateExpiredSessions();
          }
          catch (InterruptedException err)
          {
            interrupted = Boolean.TRUE.booleanValue();
          }
        }
        thread = null;
      }
    }, "WinstoneHostConfigurationMgmt:" + this.hostname);
    
    thread.setDaemon(Boolean.TRUE.booleanValue());
    thread.start();
  }
  
  public WebAppConfiguration addWebAppConfiguration(String prefix, File webRoot, String contextName)
    throws WinstoneException
  {
    if (webapps.containsKey(prefix)) {
      throw new WinstoneException("Prefix " + prefix + " is ever used");
    }
    WebAppConfiguration webAppConfiguration = null;
    try
    {
      webAppConfiguration = initWebApp(prefix, webRoot, contextName);
      webapps.put(webAppConfiguration.getContextPath(), webAppConfiguration);
      logger.info("Deploy web application: prefix [{}] webroot [{}]", prefix, webRoot);
    }
    catch (IOException e)
    {
      logger.error("Error initializing web application: prefix [" + prefix + "]", e);
    }
    return webAppConfiguration;
  }
  
  public WebAppConfiguration getWebAppByURI(String uri)
  {
    if (uri == null) {
      return null;
    }
    if ((uri.equals("/")) || (uri.equals(""))) {
      return (WebAppConfiguration)webapps.get("");
    }
    if (uri.startsWith("/"))
    {
      String decoded = WinstoneRequest.decodeURLToken(uri);
      String noLeadingSlash = decoded.substring(1);
      int slashPos = noLeadingSlash.indexOf("/");
      if (slashPos == -1) {
        return (WebAppConfiguration)webapps.get(decoded);
      }
      return (WebAppConfiguration)webapps.get(decoded.substring(0, slashPos + 1));
    }
    return null;
  }
  
  public Set<String> getContextNames()
  {
    return webapps.keySet();
  }
  
  public void reloadWebApp(String prefix)
    throws IOException
  {
    WebAppConfiguration webAppConfig = (WebAppConfiguration)webapps.get(prefix);
    if (webAppConfig != null)
    {
      String webRoot = webAppConfig.getWebroot();
      String contextName = webAppConfig.getContextName();
      destroyWebApp(prefix);
      try
      {
        WebAppConfiguration webAppConfiguration = initWebApp(prefix, new File(webRoot), contextName);
        webapps.put(webAppConfiguration.getContextPath(), webAppConfiguration);
      }
      catch (Throwable err)
      {
        logger.error("Error initializing web application: prefix [" + prefix + "]", err);
      }
    }
    else
    {
      throw new WinstoneException("Unknown webapp prefix: " + prefix);
    }
  }
  
  protected final WebAppConfiguration initWebApp(String prefix, File webRoot, String contextName)
    throws IOException
  {
    Node webXMLParentNode = null;
    File webInfFolder = new File(webRoot, "WEB-INF");
    if (webInfFolder.exists())
    {
      File webXmlFile = new File(webInfFolder, "web.xml");
      if (webXmlFile.exists())
      {
        logger.debug("Parsing web.xml");
        Document webXMLDoc = new WebXmlParser().parseStreamToXML(webXmlFile);
        if (webXMLDoc != null)
        {
          webXMLParentNode = webXMLDoc.getDocumentElement();
          logger.debug("Finished parsing web.xml");
        }
        else
        {
          logger.debug("Failure parsing the web.xml file. Ignoring and continuing as if no web.xml was found.");
        }
      }
    }
    return new WebAppConfiguration(this, cluster, jndiManager, webRoot.getCanonicalPath(), prefix, objectPool, args, webXMLParentNode, contextName);
  }
  
  public String getHostname()
  {
    return hostname;
  }
  
  private void destroyWebApp(String prefix)
  {
    WebAppConfiguration webAppConfig = (WebAppConfiguration)webapps.get(prefix);
    if (webAppConfig != null)
    {
      webAppConfig.destroy();
      webapps.remove(prefix);
    }
  }
  
  public void destroy()
  {
    Set<String> prefixes = new HashSet(webapps.keySet());
    for (String prefixe : prefixes) {
      destroyWebApp(prefixe);
    }
    if (thread != null) {
      thread.interrupt();
    }
  }
  
  private void invalidateExpiredSessions()
  {
    for (WebAppConfiguration webapp : webapps.values()) {
      webapp.invalidateExpiredSessions();
    }
  }
  
  private File getWebRoot(File requestedWebroot, File warfile)
    throws IOException
  {
    if (warfile != null)
    {
      logger.info("Beginning extraction from war file");
      if ((!warfile.exists()) || (!warfile.isFile())) {
        throw new WinstoneException("The warfile supplied is unavailable or invalid (" + warfile + ")");
      }
      File unzippedDir = null;
      if (requestedWebroot != null)
      {
        unzippedDir = requestedWebroot;
      }
      else
      {
        String tempDirectory = StringUtils.stringArg(args, "tempDirectory", null);
        String child = "winstone" + File.separator;
        if (tempDirectory == null)
        {
          File tempFile = File.createTempFile("dummy", "dummy");
          tempDirectory = tempFile.getParent();
          tempFile.delete();
          String userName = System.getProperty("user.name");
          if (userName != null) {
            child = child + StringUtils.replace(userName, new String[][] { { "/", "" }, { "\\", "" }, { ",", "" } }) + File.separator;
          }
        }
        if (hostname != null) {
          child = child + hostname + File.separator;
        }
        child = child + warfile.getName();
        unzippedDir = new File(tempDirectory, child);
      }
      if (unzippedDir.exists())
      {
        if (!unzippedDir.isDirectory()) {
          throw new WinstoneException("The webroot supplied is not a valid directory (" + unzippedDir.getPath() + ")");
        }
        logger.debug("The webroot supplied already exists - overwriting where newer ({})", unzippedDir.getCanonicalPath());
      }
      File timestampFile = new File(unzippedDir, ".timestamp");
      if ((!timestampFile.exists()) || (Math.abs(timestampFile.lastModified() - warfile.lastModified()) > 1000L))
      {
        FileUtils.delete(unzippedDir);
        unzippedDir.mkdirs();
      }
      else
      {
        return unzippedDir;
      }
      JarFile warArchive = new JarFile(warfile);
      for (Enumeration<JarEntry> e = warArchive.entries(); e.hasMoreElements();)
      {
        JarEntry element = (JarEntry)e.nextElement();
        if (!element.isDirectory())
        {
          String elemName = element.getName();
          
          File outFile = new File(unzippedDir, elemName);
          if ((!outFile.exists()) || (outFile.lastModified() <= warfile.lastModified()))
          {
            outFile.getParentFile().mkdirs();
            byte[] buffer = new byte['?'];
            
            InputStream inContent = warArchive.getInputStream(element);
            OutputStream outStream = new FileOutputStream(outFile);
            int readBytes = inContent.read(buffer);
            while (readBytes != -1)
            {
              outStream.write(buffer, 0, readBytes);
              readBytes = inContent.read(buffer);
            }
            inContent.close();
            outStream.close();
          }
        }
      }
      new FileOutputStream(timestampFile).close();
      timestampFile.setLastModified(warfile.lastModified());
      
      return unzippedDir;
    }
    return requestedWebroot;
  }
  
  private void deploy(File aChildren, boolean checkMatchingWarfile)
  {
    String childName = aChildren.getName();
    if (aChildren.isDirectory())
    {
      File matchingWarFile = new File(aChildren.getParentFile(), aChildren.getName() + ".war");
      if ((checkMatchingWarfile) && (matchingWarFile.exists()) && (matchingWarFile.isFile()))
      {
        logger.debug("Webapp dir deployment {} skipped, since there is a war file of the same name to check for re-extraction", childName);
      }
      else
      {
        String prefix = "/" + childName;
        if (!webapps.containsKey(prefix))
        {
          WebAppConfiguration webAppConfig = addWebAppConfiguration(prefix, aChildren, childName);
          if (webAppConfig != null) {
            logger.info("Deployed web application found at {}", aChildren.getAbsolutePath());
          }
        }
      }
    }
    else if (childName.endsWith(".war"))
    {
      String outputName = childName.substring(0, childName.lastIndexOf(".war"));
      String prefix = "/" + outputName;
      if (!webapps.containsKey(prefix))
      {
        File outputDir = new File(aChildren.getParentFile(), outputName);
        outputDir.mkdirs();
        WebAppConfiguration webAppConfig = null;
        try
        {
          webAppConfig = addWebAppConfiguration(prefix, getWebRoot(new File(aChildren.getParentFile(), outputName), aChildren), outputName);
        }
        catch (IOExcepti
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