wms-winstone-1.0.5

entThread().getContextClassLoader();
          Thread.currentThread().setContextClassLoader(getLoader());
          contextAttributeListeners[n].attributeAdded(new ServletContextAttributeEvent(this, name, object));
          Thread.currentThread().setContextClassLoader(cl);
        }
      }
    }
  }
  
  public String getInitParameter(String name)
  {
    return (String)initParameters.get(name);
  }
  
  public Enumeration<String> getInitParameterNames()
  {
    return Collections.enumeration(initParameters.keySet());
  }
  
  public String getServerInfo()
  {
    return WinstoneResourceBundle.getInstance().getString("ServerVersion");
  }
  
  public int getMajorVersion()
  {
    return 2;
  }
  
  public int getMinorVersion()
  {
    return 5;
  }
  
  public ServletContext getContext(String uri)
  {
    return ownerHostConfig.getWebAppByURI(uri);
  }
  
  public String getServletContextName()
  {
    return displayName;
  }
  
  public String getMimeType(String fileName)
  {
    return mimeTypes.getContentTypeFor(fileName);
  }
  
  public void log(String message)
  {
    if (logger.isInfoEnabled()) {
      logger.info(contextName + " " + message);
    }
  }
  
  public void log(String message, Throwable throwable)
  {
    if (logger.isErrorEnabled()) {
      logger.error(contextName + " " + message, throwable);
    }
  }
  
  public RequestDispatcher getNamedDispatcher(String name)
  {
    ServletConfiguration servlet = (ServletConfiguration)servletInstances.get(name);
    if (servlet != null)
    {
      SimpleRequestDispatcher rd = new SimpleRequestDispatcher(this, servlet);
      if (rd != null)
      {
        rd.setForNamedDispatcher(filterPatternsForward, filterPatternsInclude);
        return rd;
      }
    }
    return null;
  }
  
  public RequestDispatcher getRequestDispatcher(String uriInsideWebapp)
  {
    if (uriInsideWebapp == null) {
      return null;
    }
    if (!uriInsideWebapp.startsWith("/")) {
      return null;
    }
    String queryString = "";
    int questionPos = uriInsideWebapp.indexOf('?');
    if (questionPos != -1)
    {
      if (questionPos != uriInsideWebapp.length() - 1) {
        queryString = uriInsideWebapp.substring(questionPos + 1);
      }
      uriInsideWebapp = uriInsideWebapp.substring(0, questionPos);
    }
    StringBuilder servletPath = new StringBuilder();
    StringBuilder pathInfo = new StringBuilder();
    ServletConfiguration servlet = urlMatch(uriInsideWebapp, servletPath, pathInfo);
    if (servlet != null)
    {
      SimpleRequestDispatcher rd = new SimpleRequestDispatcher(this, servlet);
      if (rd != null)
      {
        rd.setForURLDispatcher(servletPath.toString(), pathInfo.toString().equals("") ? null : pathInfo.toString(), queryString, uriInsideWebapp, filterPatternsForward, filterPatternsInclude);
        return rd;
      }
    }
    return null;
  }
  
  public SimpleRequestDispatcher getInitialDispatcher(String uriInsideWebapp, WinstoneRequest request, WinstoneResponse response)
    throws IOException
  {
    if ((!uriInsideWebapp.equals("")) && (!uriInsideWebapp.startsWith("/"))) {
      return getErrorDispatcherByCode(uriInsideWebapp, 400, "URI must start with a slash: " + uriInsideWebapp, new IllegalArgumentException("method=" + request.getMethod() + "\nprotocol=" + request.getProtocol()));
    }
    if (contextStartupError != null)
    {
      StringWriter sw = new StringWriter();
      PrintWriter pw = new PrintWriter(sw, Boolean.TRUE.booleanValue());
      contextStartupError.printStackTrace(pw);
      return getErrorDispatcherByCode(uriInsideWebapp, 500, "The error below occurred during context initialisation, so no further requests can be \nprocessed:<br><pre>" + sw.toString() + "</pre>", contextStartupError);
    }
    String queryString = "";
    int questionPos = uriInsideWebapp.indexOf('?');
    if (questionPos != -1)
    {
      if (questionPos != uriInsideWebapp.length() - 1) {
        queryString = uriInsideWebapp.substring(questionPos + 1);
      }
      uriInsideWebapp = uriInsideWebapp.substring(0, questionPos);
    }
    StringBuilder servletPath = new StringBuilder();
    StringBuilder pathInfo = new StringBuilder();
    ServletConfiguration servlet = urlMatch(uriInsideWebapp, servletPath, pathInfo);
    if (servlet != null)
    {
      if (servlet.getServletName().equals(defaultServletName))
      {
        String directoryPath = servletPath.toString();
        if (directoryPath.endsWith("/")) {
          directoryPath = directoryPath.substring(0, directoryPath.length() - 1);
        }
        if (directoryPath.startsWith("/")) {
          directoryPath = directoryPath.substring(1);
        }
        File res = new File(webRoot, directoryPath);
        if ((res.exists()) && (res.isDirectory()) && ((request.getMethod().equals("GET")) || (request.getMethod().equals("HEAD"))))
        {
          if (!servletPath.toString().endsWith("/"))
          {
            logger.debug("Detected directory with no trailing slash (path={}) - redirecting", servletPath.toString());
            response.sendRedirect(prefix + servletPath.toString() + pathInfo.toString() + "/" + (queryString.equals("") ? "" : new StringBuilder().append("?").append(queryString).toString()));
            return null;
          }
          logger.debug("Beginning welcome file match for path: {}", servletPath.toString() + pathInfo.toString());
          String welcomeFile = matchWelcomeFiles(servletPath.toString() + pathInfo.toString(), request, queryString);
          if (welcomeFile != null)
          {
            response.sendRedirect(prefix + welcomeFile);
            
            return null;
          }
        }
      }
      SimpleRequestDispatcher rd = new SimpleRequestDispatcher(this, servlet);
      rd.setForInitialDispatcher(servletPath.toString(), pathInfo.toString().equals("") ? null : pathInfo.toString(), queryString, uriInsideWebapp, filterPatternsRequest, authenticationHandler);
      return rd;
    }
    return getErrorDispatcherByCode(uriInsideWebapp, 404, "File " + uriInsideWebapp + " not found", null);
  }
  
  public SimpleRequestDispatcher getErrorDispatcherByClass(Throwable exception)
  {
    Class<?>[] exceptionClasses = errorPagesByExceptionKeysSorted;
    Throwable errWrapper = new ServletException(exception);
    while ((errWrapper instanceof ServletException))
    {
      errWrapper = ((ServletException)errWrapper).getRootCause();
      if (errWrapper == null) {
        break;
      }
      for (int n = 0; n < exceptionClasses.length; n++)
      {
        logger.debug("Testing error page exception {} against thrown exception {}", errorPagesByExceptionKeysSorted[n].getName(), errWrapper.getClass().getName());
        if (exceptionClasses[n].isInstance(errWrapper))
        {
          String errorURI = (String)errorPagesByException.get(exceptionClasses[n]);
          if (errorURI != null)
          {
            SimpleRequestDispatcher rd = buildErrorDispatcher(errorURI, 500, null, errWrapper);
            if (rd != null) {
              return rd;
            }
          }
          else
          {
            logger.warn("Error-page {} not found for exception {}", exceptionClasses[n].getName(), errorPagesByException.get(exceptionClasses[n]));
          }
        }
        else
        {
          logger.warn("Exception {} not matched", exceptionClasses[n].getName());
        }
      }
    }
    Throwable errPassDown = exception;
    while (((errPassDown instanceof ServletException)) && (((ServletException)errPassDown).getRootCause() != null)) {
      errPassDown = ((ServletException)errPassDown).getRootCause();
    }
    return getErrorDispatcherByCode(null, 500, null, errPassDown);
  }
  
  public SimpleRequestDispatcher getErrorDispatcherByCode(String requestURI, int statusCode, String summaryMessage, Throwable exception)
  {
    String errorURI = (String)getErrorPagesByCode().get("" + statusCode);
    if (errorURI != null)
    {
      SimpleRequestDispatcher rd = buildErrorDispatcher(errorURI, statusCode, summaryMessage, exception);
      if (rd != null) {
        return rd;
      }
    }
    ServletConfiguration errorServlet = (ServletConfiguration)servletInstances.get(errorServletName);
    if (errorServlet != null)
    {
      SimpleRequestDispatcher rd = new SimpleRequestDispatcher(this, errorServlet);
      if (rd != null)
      {
        rd.setForErrorDispatcher(null, null, null, statusCode, summaryMessage, exception, requestURI, filterPatternsError);
        return rd;
      }
    }
    logger.error("No error servlet available: status code " + statusCode, exception);
    return null;
  }
  
  private SimpleRequestDispatcher buildErrorDispatcher(String errorURI, int statusCode, String summaryMessage, Throwable exception)
  {
    String queryString = "";
    int questionPos = errorURI.indexOf('?');
    if (questionPos != -1)
    {
      if (questionPos != errorURI.length() - 1) {
        queryString = errorURI.substring(questionPos + 1);
      }
      errorURI = errorURI.substring(0, questionPos);
    }
    ServletException errIterator = new ServletException(exception);
    while ((summaryMessage == null) && (errIterator != null))
    {
      summaryMessage = errIterator.getMessage();
      if ((errIterator.getRootCause() instanceof ServletException))
      {
        errIterator = (ServletException)errIterator.getRootCause();
      }
      else
      {
        if ((summaryMessage == null) && (errIterator.getCause() != null)) {
          summaryMessage = errIterator.getRootCause().getMessage();
        }
        errIterator = null;
      }
    }
    StringBuilder servletPath = new StringBuilder();
    StringBuilder pathInfo = new StringBuilder();
    ServletConfiguration servlet = urlMatch(errorURI, servletPath, pathInfo);
    if (servlet != null)
    {
      SimpleRequestDispatcher rd = new SimpleRequestDispatcher(this, servlet);
      if (rd != null)
      {
        rd.setForErrorDispatcher(servletPath.toString(), pathInfo.toString().equals("") ? null : pathInfo.toString(), queryString, statusCode, summaryMessage, exception, errorURI, filterPatternsError);
        return rd;
      }
    }
    return null;
  }
  
  private String matchWelcomeFiles(String path, WinstoneRequest request, String queryString)
  {
    if (!path.endsWith("/")) {
      path = path + "/";
    }
    String qs = "?" + queryString;
    for (int n = 0; n < welcomeFiles.length; n++)
    {
      String welcomeFile = welcomeFiles[n];
      while (welcomeFile.startsWith("/")) {
        welcomeFile = welcomeFile.substring(1);
      }
      welcomeFile = path + welcomeFile;
      
      String exact = (String)exactServletMatchMounts.get(welcomeFile);
      if (exact != null) {
        return welcomeFile + qs;
      }
      for (int j = 0; j < patternMatches.length; j++)
      {
        Mapping urlPattern = patternMatches[j];
        if ((urlPattern.getPatternType() == 2) && (urlPattern.match(welcomeFile, null, null))) {
          return welcomeFile + qs;
        }
      }
      try
      {
        if (getResource(welcomeFile) != null) {
          return welcomeFile + qs;
        }
      }
      catch (MalformedURLException err) {}
    }
    return null;
  }
  
  public URL getResource(String path)
    throws MalformedURLException
  {
    if (path == null) {
      return null;
    }
    if (!path.startsWith("/")) {
      throw new MalformedURLException("Bad resource path: path=" + path);
    }
    if ((!path.equals("/")) && (path.endsWith("/"))) {
      path = path.substring(0, path.length() - 1);
    }
    File res = new File(webRoot, StringUtils.canonicalPath(path));
    return (res != null) && (res.exists()) ? res.toURI().toURL() : null;
  }
  
  public InputStream getResourceAsStream(String path)
  {
    try
    {
      URL res = getResource(path);
      return res == null ? null : res.openStream();
    }
    catch (IOException err)
    {
      throw new WinstoneException("Error opening resource stream", err);
    }
  }
  
  public String getRealPath(String path)
  {
    if (path == null) {
      return null;
    }
    try
    {
      File res = new File(webRoot, path);
      if (res.isDirectory()) {
        return res.getCanonicalPath() + "/";
      }
      return res.getCanonicalPath();
    }
    catch (IOException err) {}
    return null;
  }
  
  public Set<String> getResourcePaths(String path)
  {
    if (path == null) {
      return null;
    }
    if (!path.startsWith("/")) {
      throw new WinstoneException("Bad resource path: path=" + path);
    }
    String workingPath = null;
    if (path.equals("/"))
    {
      workingPath = "";
    }
    else
    {
      boolean lastCharIsSlash = path.charAt(path.length() - 1) == '/';
      workingPath = path.substring(1, path.length() - (lastCharIsSlash ? 1 : 0));
    }
    File inPath = new File(webRoot, workingPath.equals("") ? "." : workingPath).getAbsoluteFile();
    if (!inPath.exists()) {
      return null;
    }
    if (!inPath.isDirectory()) {
      return null;
    }
    File[] children = inPath.listFiles();
    Set<String> out = new HashSet();
    for (int n = 0; n < children.length; n++)
    {
      String entry = "/" + (workingPath.length() != 0 ? workingPath + "/" : "") + children[n].getName() + (children[n].isDirectory() ? "/" : "");
      
      out.add(entry);
    }
    return out;
  }
  
  @Deprecated
  public Servlet getServlet(String name)
  {
    return null;
  }
  
  @Deprecated
  public Enumeration getServletNames()
  {
    return Collections.enumeration(new ArrayList());
  }
  
  @Deprecated
  public Enumeration getServlets()
  {
    return Collections.enumeration(new ArrayList());
  }
  
  @Deprecated
  public void log(Exception exception, String msg)
  {
    log(msg, exception);
  }
  
  public int hashCode()
  {
    int prime = 31;
    int result = 1;
    result = 31 * result + (prefix == null ? 0 : prefix.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();
    }
    WebAppConfiguration other = (WebAppConfiguration)obj;
    if (prefix == null)
    {
      if (prefix != null) {
        return Boolean.FALSE.booleanValue();
      }
    }
    else if (!prefix.equals(prefix)) {
      return Boolean.FALSE.booleanValue();
    }
    return Boolean.TRUE.booleanValue();
  }
  
  public String toString()
  {
    return "WebAppConfiguration [contextPath=" + prefix + "]";
  }
}

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

import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.naming.NamingException;
import net.winstone.jndi.JndiManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class WebAppJNDIManager
{
  protected static Logger logger = LoggerFactory.getLogger(WebAppJNDIManager.class);
  private static final transient String ELEM_ENV_ENTRY = "env-entry";
  private static final transient String ELEM_ENV_ENTRY_NAME = "env-entry-name";
  private static final transient String ELEM_ENV_ENTRY_TYPE = "env-entry-type";
  private static final transient String ELEM_ENV_ENTRY_VALUE = "env-entry-value";
  private final Set<String> objectCreated;
  private final JndiManager jndiManager;
  
  public WebAppJNDIManager(JndiManager jndiManager, List<Node> webXMLNodes, ClassLoader loader)
  {
    objectCreated = new HashSet();
    this.jndiManager = jndiManager;
    Iterator<Node> i;
    if (webXMLNodes != null) {
      for (i = webXMLNodes.iterator(); i.hasNext();)
      {
        Node node = (Node)i.next();
        if (node.getNodeType() == 1) {
          if (node.getNodeName().equals("env-entry"))
          {
            String name = null;
            String className = null;
            String value = null;
            for (int m = 0; m < node.getChildNodes().getLength(); m++)
            {
              Node envNode = node.getChildNodes().item(m);
              if (envNode.getNodeType() == 1) {
                if (envNode.getNodeName().equals("env-entry-name")) {
                  name = WebAppConfiguration.getTextFromNode(envNode);
                } else if (envNode.getNodeName().equals("env-entry-type")) {
                  className = WebAppConfiguration.getTextFromNode(envNode);
                } else if (envNode.getNodeName().equals("env-entry-value")) {
                  value = WebAppConfiguration.getTextFromNode(envNode);
                }
              }
            }
            if ((name != null) && (className != null) && (value != null))
            {
              logger.debug("Creating object {} from web.xml env-entry description", name);
              try
              {
                jndiManager.bind(name, className, value, loader);
                objectCreated.add(name);
              }
              catch (Throwable err)
              {
                logger.error("Error building JNDI object " + name + " (class: " + className + ")", err);
              }
            }
          }
        }
      }
    }
  }
  
  public void destroy()
  {
    for (String name : objectCreated) {
      try
      {
        jndiManager.unbind(name);
      }
      catch (IllegalStateException ex) {}catch (NamingException ex) {}
    }
    objectCreated.clear();
  }
}

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

import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;

public class WebXmlParser
  implements EntityResolver, ErrorHandler
{
  protected static Logger logger = LoggerFactory.getLogger(WebXmlParser.class);
  private boolean rethrowValidationExceptions = Boolean.TRUE.booleanValue();
  private static final String SCHEMA_SOURCE_PROPERTY = "http://java.sun.com/xml/jaxp/properties/schemaSource";
  
  public Document parseStreamToXML(File webXmlFile)
  {
    DocumentBuilderFactory factory = getBaseDBF();
    
    URL localXSD25 = Thread.currentThread().getContextClassLoader().getResource(LOCAL_ENTITY_TABLE[3][2]);
    URL localXSD24 = Thread.currentThread().getContextClassLoader().getResource(LOCAL_ENTITY_TABLE[2][2]);
    try
    {
      factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaLanguage", "http://www.w3.org/2001/XMLSchema");
      if (localXSD25 != null)
      {
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", localXSD25.toString());
        logger.info("Found and enabled the local Servlet 2.5 XSD replacement");
      }
      else if (localXSD24 != null)
      {
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", localXSD24.toString());
        logger.info("Found and enabled the local Servlet 2.4 XSD replacement");
      }
      else
      {
        logger.warn("WARNING: The Servlet 2.4/2.5 spec XSD was unavailable inside the winstone classpath. \nWill be retrieved from the web if required (slow)");
      }
    }
    catch (Throwable err)
    {
      logger.warn("WARNING: Non-XML-Schema-compliant parser detected. Servlet spec <= 2.3 supported");
      try
      {
        rethrowValidationExceptions = Boolean.FALSE.booleanValue();
        return parseAsV23Webapp(webXmlFile);
      }
      catch (Throwable v23Err)
      {
        logger.error("Error when parsing web.xml file using the v2.2/2.3 servlet specification:", v23Err);
        return null;
      }
    }
    try
    {
      if (localXSD25 != null) {
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", localXSD25.toString());
      } else {
        factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", null);
      }
      DocumentBuilder builder = factory.newDocumentBuilder();
      builder.setEntityResolver(this);
      builder.setErrorHandler(this);
      rethrowValidationExceptions = Boolean.TRUE.booleanValue();
      return builder.parse(webXmlFile);
    }
    catch (Throwable errV25)
    {
      try
      {
        if (localXSD24 != null) {
          factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", localXSD24.toString());
        } else {
          factory.setAttribute("http://java.sun.com/xml/jaxp/properties/schemaSource", null);
        }
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver(this);
        builder.setErrorHandler(this);
        rethrowValidationExceptions = Boolean.TRUE.booleanValue();
        return builder.parse(webXmlFile);
      }
      catch (Throwable errV24)
      {
        try
        {
          rethrowValidationExceptions = Boolean.FALSE.booleanValue();
          return parseAsV23Webapp(webXmlFile);
        }
        catch (Throwable errV23)
        {
          logger.error("ERROR: An XSD compliant parser was available, but web.xml parsing failed under both XSD and non-XSD conditions. See below for error reports.");
          logger.error("Error when parsing web.xml file using the v2.5 servlet specification:", errV25);
          logger.error("Error when parsing web.xml file using the v2.4 servlet specification:", errV24);
          logger.error("Error when parsing web.xml file using the v2.2/2.3 servlet specification:", errV23);
        }
      }
    }
    return null;
  }
  
  private Document parseAsV23Webapp(File webXmlFile)
    throws ParserConfigurationException, SAXException, IOException
  {
    DocumentBuilderFactory factory = getBaseDBF();
    DocumentBuilder builder = factory.newDocumentBuilder();
    builder.setEntityResolver(this);
    builder.setErrorHandler(this);
    return builder.parse(webXmlFile);
  }
  
  private DocumentBuilderFactory getBaseDBF()
  {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    factory.setExpandEntityReferences(Boolean.FALSE.booleanValue());
    factory.setValidating(Boolean.TRUE.booleanValue());
    factory.setNamespaceAware(Boolean.TRUE.booleanValue());
    factory.setIgnoringComments(Boolean.TRUE.booleanValue());
    factory.setCoalescing(Boolean.TRUE.booleanValue());
    factory.setIgnoringElementContentWhitespace(Boolean.TRUE.booleanValue());
    return factory;
  }
  
  private static final String[][] LOCAL_ENTITY_TABLE = { { "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN", null, "javax/servlet/resources/web-app_2_2.dtd" }, { "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN", null, "javax/servlet/resources/web-app_2_3.dtd" }, { null, "http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd", "javax/servlet/resources/web-app_2_4.xsd" }, { null, "http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd", "javax/servlet/resources/web-app_2_5.xsd" }, { null, "http://www.w3.org/2001/xml.xsd", "javax/servlet/resources/xml.xsd" }, { "-//W3C//DTD XMLSCHEMA 200102//EN", null, "javax/servlet/resources/XMLSchema.dtd" }, { null, "http://www.w3.org/2001/datatypes.dtd", "javax/servlet/resources/datatypes.dtd" }, { null, "http://java.sun.com/xml/ns/j2ee/j2ee_1_4.xsd", "javax/servlet/resources/j2ee_1_4.xsd" }, { null, "http://java.sun.com/xml/ns/j2ee/javaee_5.xsd", "javax/servlet/resources/javaee_5.xsd" }, { null, "http://java.sun.com/xml/ns/j2ee/jsp_2_0.xsd", "javax/servlet/resources/jsp_2_0.xsd" }, { null, "http://java.sun.com/xml/ns/j2ee/jsp_2_1.xsd", "javax/servlet/resources/jsp_2_1.xsd" }, { null, "http://www.ibm.com/webservices/xsd/j2ee_web_services_client_1_1.xsd", "javax/servlet/resources/j2ee_web_services_client_1_1.xsd" }, { null, "http://www.ibm.com/webservices/xsd/j2ee_web_services_client_1_2.xsd", "javax/servlet/resources/javaee_web_services_client_1_2.xsd" } };
  
  public InputSource resolveEntity(String publicName, String url)
    throws SAXException, IOException
  {
    logger.debug("Resolving entity - public={}, url={}", publicName, url);
    for (int n = 0; n < LOCAL_ENTITY_TABLE.length; n++) {
      if (((LOCAL_ENTITY_TABLE[n][0] != null) && (publicName != null) && (publicName.equals(LOCAL_ENTITY_TABLE[n][0]))) || ((LOCAL_ENTITY_TABLE[n][1] != null) && (url != null) && (url.equals(LOCAL_ENTITY_TABLE[n][1])))) {
        if (Thread.currentThread().getContextClassLoader().getResource(LOCAL_ENTITY_TABLE[n][2]) != null) {
          return getLocalResource(url, LOCAL_ENTITY_TABLE[n][2]);
        }
      }
    }
    if ((url != null) && (url.startsWith("jar:"))) {
      return getLocalResource(url, url.substring(url.indexOf("!/") + 2));
    }
    if ((url != null) && (url.startsWith("file:"))) {
      return new InputSource(url);
    }
    logger.debug("Cannot find local resource for url: {}", url);
    return new InputSource(url);
  }
  
  private InputSource getLocalResource(String url, String local)
  {
    if (Thread.currentThread().getContextClassLoader().getResource(local) == null) {
      return new InputSource(url);
    }
    InputSource is = new InputSource(Thread.currentThread().getContextClassLoader().getResourceAsStream(local));
    is.setSystemId(url);
    return is;
  }
  
  public void error(SAXParseException exception)
    throws SAXException
  {
    if (rethrowValidationExceptions) {
      throw exception;
    }
    logger.warn("XML Error (Line {}): {}", exception.getLineNumber() + "", exception.getMessage());
  }
  
  public void fatalError(SAXParseException exception)
    throws SAXException
  {
    error(exception);
  }
  
  public void warning(SAXParseException exception)
    throws SAXException
  {
    logger.warn("XML Error (Line {}): {}", exception.getLineNumber() + "", exception.getMessage());
  }
}

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

public class WinstoneConstant
{
  public static final transient String CONTENT_LENGTH_HEADER = "Content-Length";
  public static final transient String CONTENT_TYPE_HEADER = "Content-Type";
  public static final transient String CONTENT_LANGUAGE_HEADER = "Content-Language";
  public static final transient String KEEP_ALIVE_HEADER = "Connection";
  public static final transient String KEEP_ALIVE_OPEN = "Keep-Alive";
  public static final transient String KEEP_ALIVE_CLOSE = "Close";
  public static final transient String DATE_HEADER = "Date";
  public static final transient String LOCATION_HEADER = "Location";
  public static final transient String OUT_COOKIE_HEADER1 = "Set-Cookie";
  public static final transient String X_POWERED_BY_HEADER = "X-Powered-By";
  public static final transient String AUTHORIZATION_HEADER = "Authorization";
  public static final transient String LOCALE_HEADER = "Accept-Language";
  public static final transient String HOST_HEADER = "Host";
  public static final transient String IN_COOKIE_HEADER1 = "Cookie";
  public static final transient String IN_COOKIE_HEADER2 = "Cookie2";
  public static final transient String METHOD_HEAD = "HEAD";
  public static final transient String METHOD_GET = "GET";
  public static final transient String METHOD_POST = "POST";
  public static final transient String POST_PARAMETERS = "application/x-www-form-urlencoded";
  public static final transient String INCLUDE_REQUEST_URI = "javax.servlet.include.request_uri";
  public static final transient String INCLUDE_CONTEXT_PATH = "javax.servlet.include.context_path";
  public static final transient String INCLUDE_SERVLET_PATH = "javax.servlet.include.servlet_path";
  public static final transient String INCLUDE_PATH_INFO = "javax.servlet.include.path_info";
  public static final transient String INCLUDE_QUERY_STRING = "javax.servlet.include.query_string";
  public static final transient String FORWARD_REQUEST_URI = "javax.servlet.forward.request_uri";
  public static final transient String FORWARD_CONTEXT_PATH = "javax.servlet.forward.context_path";
  public static final transient String FORWARD_SERVLET_PATH = "javax.servlet.forward.servlet_path";
  public static final transient String FORWARD_PATH_INFO = "javax.servlet.forward.path_info";
  public static final transient String FORWARD_QUERY_STRING = "javax.servlet.forward.query_string";
  public static final transient String ERROR_STATUS_CODE = "javax.servlet.error.status_code";
  public static final transient String ERROR_EXCEPTION_TYPE = "javax.servlet.error.exception_type";
  public static final transient String ERROR_MESSAGE = "javax.servlet.error.message";
  public static final transient String ERROR_EXCEPTION = "javax.servlet.error.exception";
  public static final transient String ERROR_REQUEST_URI = "javax.servlet.error.request_uri";
  public static final transient String ERROR_SERVLET_NAME = "javax.servlet.error.servlet_name";
  public static final transient String JSP_SERVLET_NAME = "JspServlet";
  public static final transient String JSP_SERVLET_CLASS = "org.apache.jasper.servlet.JspServlet";
  public static final transient String JAVAX_JSP_FACTORY = "javax.servlet.jsp.JspFactory";
  public static final transient Integer DEFAULT_MAXIMUM_PARAMETER_ALLOWED = Integer.valueOf(10000);
}

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

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletInputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WinstoneInputStream
  extends ServletInputStream
{
  protected static Logger logger = LoggerFactory.getLogger(WinstoneInputStream.class);
  final int BUFFER_SIZE = 4096;
  private final InputStream inData;
  private Integer contentLength;
  private int readSoFar;
  
  public WinstoneInputStream(InputStream inData)
  {
    this.inData = inData;
  }
  
  public WinstoneInputStream(byte[] inData)
  {
    this(new ByteArrayInputStream(inData));
  }
  
  public InputStream getRawInputStream()
  {
    return inData;
  }
  
  public void setContentLength(int length)
  {
    contentLength = new Integer(length);
    readSoFar = 0;
  }
  
  public int read()
    throws IOException
  {
    if (contentLength == null)
    {
      int data = inData.read();
      return data;
    }
    if (contentLength.intValue() > readSoFar)
    {
      readSoFar += 1;
      int data = inData.read();
      return data;
    }
    return -1;
  }
  
  public int read(byte[] b, int off, int len)
    throws IOException
  {
    if (contentLength == null) {
      return inData.read(b, off, len);
    }
    len = Math.min(len, contentLength.intValue() - readSoFar);
    if (len <= 0) {
      return -1;
    }
    int r = inData.read(b, off, len);
    if (r < 0) {
      return r;
    }
    readSoFar += r;
    return r;
  }
  
  public int readAsMuchAsPossible(byte[] buf, int offset, int len)
    throws IOException
  {
    int total = 0;
    while (total < len)
    {
      int count = read(buf, offset + total, len - total);
      if (count < 0) {
        break;
      }
      total += count;
    }
    return total;
  }
  
  public void finishRequest() {}
  
  public int available()
    throws IOException
  {
    return inData.available();
  }
  
  public byte[] readLine()
    throws IOException
  {
    byte[] buffer = new byte['?'];
    int charsRead = super.readLine(buffer, 0, 4096);
    if (charsRead == -1)
    {
      logger.debug("End of stream");
      return new byte[0];
    }
    byte[] outBuf = new byte[charsRead];
    System.arraycopy(buffer, 0, outBuf, 0, charsRead);
    return outBuf;
  }
}

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

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.Stack;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import net.winstone.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WinstoneOutputStream
  extends ServletOutputStream
{
  private static Logger logger = LoggerFactory.getLogger(WinstoneOutputStream.class);
  private static final int DEFAULT_BUFFER_SIZE = 8192;
  private static final byte[] CR_LF = "\r\n".getBytes();
  protected OutputStream outStream;
  protected long bufferSize;
  protected long bufferPosition;
  protected long bytesCommitted;
  protected ByteArrayOutputStream buffer;
  protected boolean committed;
  protected boolean bodyOnly;
  protected WinstoneResponse owner;
  protected boolean disregardMode = Boolean.FALSE.booleanValue();
  protected boolean closed = Boolean.FALSE.booleanValue();
  protected Stack<ByteArrayOutputStream> includeByteStreams;
  
  public WinstoneOutputStream(OutputStream out, boolean bodyOnlyForInclude)
  {
    outStream = new ClientOutputStream(out);
    bodyOnly = bodyOnlyForInclude;
    bufferSize = 8192L;
    committed = Boolean.FALSE.booleanValue();
    
    buffer = new ByteArrayOutputStream();
  }
  
  public void setResponse(WinstoneResponse response)
  {
    owner = response;
  }
  
  public long getBufferSize()
  {
    return bufferSize;
  }
  
  public void setBufferSize(long bufferSize)
  {
    if (owner.isCommitted()) {
      throw new IllegalStateException("OutputStream already committed");
    }
    this.bufferSize = bufferSize;
  }
  
  public boolean isCommitted()
  {
    return committed;
  }
  
  public long getOutputStreamLength()
  {
    return bytesCommitted + bufferPosition;
  }
  
  public long getBytesCommitted()
  {
    return bytesCommitted;
  }
  
  public void setDisregardMode(boolean disregard)
  {
    disregardMode = disregard;
  }
  
  public void setClosed(boolean closed)
  {
    this.closed = closed;
  }
  
  public void write(int oneChar)
    throws IOException
  {
    if ((disregardMode) || (closed)) {
      return;
    }
    String contentLengthHeader = owner.getHeader("Content-Length");
    if ((contentLengthHeader != null) && (bytesCommitted >= Long.parseLong(contentLengthHeader))) {
      return;
    }
    buffer.write(oneChar);
    commit(contentLengthHeader, 1);
  }
  
  public void write(byte[] b, int off, int len)
    throws IOException
  {
    if ((disregardMode) || (closed)) {
      return;
    }
    String contentLengthHeader = owner.getHeader("Content-Length");
    if ((contentLengthHeader != null) && (bytesCommitted + len > Long.parseLong(contentLengthHeader))) {
      return;
    }
    buffer.write(b, off, len);
    commit(contentLengthHeader, len);
  }
  
  private void commit(String contentLengthHeader, int len)
    throws IOException
  {
    bufferPosition += len;
    if (bufferPosition >= bufferSize) {
      commit();
    } else if ((contentLengthHeader != null) && (bufferPosition + bytesCommitted >= Long.parseLong(contentLengthHeader))) {
      commit();
    }
  }
  
  public void commit()
    throws IOException
  {
    buffer.flush();
    if ((!committed) && (!bodyOnly))
    {
      owner.validateHeaders();
      committed = Boolean.TRUE.booleanValue();
      
      logger.debug("Committing response body");
      
      int statusCode = owner.getStatus();
      HttpProtocole reason = HttpProtocole.valueOf("HTTP_" + Integer.toString(statusCode));
      String statusLine = owner.getProtocol() + " " + statusCode + " " + (reason == null ? "No reason" : reason.getMessage());
      OutputStream o = new BufferedOutputStream(outStream);
      o.write(statusLine.getBytes("8859_1"));
      o.write(CR_LF);
      logger.debug("Response: " + statusLine);
      for (String header : owner.getHeaders())
      {
        o.write(StringUtils.noCRLF(header).getBytes("8859_1"));
        o.write(CR_LF);
        logger.debug("Header: " + header);
      }
      if (!owner.getHeaders().isEmpty()) {
        for (Object o1 : owner.getCookies())
        {
          Cookie cookie = (Cookie)o1;
          String cookieText = owner.writeCookie(cookie);
          o.write(cookieText.getBytes("8859_1"));
          o.write(CR_LF);
          logger.debug("Header: " + cookieText);
        }
      }
      o.write(CR_LF);
      o.flush();
    }
    byte[] content = buffer.toByteArray();
    
    long commitLength = content.length;
    String contentLengthHeader = owner.getHeader("Content-Length");
    if (contentLengthHeader != null) {
      commitLength = Math.min(Long.parseLong(contentLengthHeader) - bytesCommitted, content.length);
    }
    if (commitLength > 0L) {
      outStream.write(content, 0, (int)commitLength);
    }
    outStream.flush();
    logger.debug("Written {} bytes to response body", Long.toString(bytesCommitted + commitLength));
    
    bytesCommitted += commitLength;
    buffer.reset();
    bufferPosition = 0L;
  }
  
  public void reset()
  {
    if (isCommitted()) {
      throw new IllegalStateException("OutputStream already committed");
    }
    logger.debug("WResetting buffer - discarding {} bytes", Long.toString(bufferPosition));
    buffer.reset();
    bufferPosition = 0L;
    bytesCommitted = 0L;
  }
  
  public void finishResponse()
    throws IOException
  {
    outStream.flush();
    outStream = null;
  }
  
  public void flush()
    throws IOException
  {
    if (disregardMode) {
      return;
    }
    logger.debug("ServletOutputStream flushed");
    buffer.flush();
    commit();
  }
  
  public void close()
    throws IOException
  {
    if ((!isCommitted()) && (!disregardMode) && (!closed) && (owner.getHeader("Content-Length") == null) && 
      (owner != null) && (!bodyOnly)) {
      owner.setContentLength((int)getOutputStreamLength());
    }
    flush();
  }
  
  public boolean isIncluding()
  {
    return (includeByteStreams != null) && (!includeByteStreams.isEmpty());
  }
  
  public void startIncludeBuffer()
  {
    synchronized (buffer)
    {
      if (includeByteStreams == null) {
        includeByteStreams = new Stack();
      }
    }
    includeByteStreams.push(new ByteArrayOutputStream());
  }
  
  public void finishIncludeBuffer()
    throws IOException
  {
    if (isIncluding())
    {
      ByteArrayOutputStream body = (ByteArrayOutputStream)includeByteStreams.pop();
      OutputStream topStream = outStream;
      if (!includeByteStreams.isEmpty()) {
        topStream = (OutputStream)includeByteStreams.peek();
      }
      byte[] bodyArr = body.toByteArray();
      if (bodyArr.length > 0) {
        topStream.write(bodyArr);
      }
      body.close();
    }
  }
  
  public void clearIncludeStackForForward()
    throws IOException
  {
    if (isIncluding())
    {
      for (Object includeByteStream : includeByteStreams) {
        ((ByteArrayOutputStream)includeByteStream).close();
      }
      includeByteStreams.clear();
    }
  }
}

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

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
im
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