wms-winstone-1.0.5

butes.put("javax.servlet.context.tempdir", tmpDir);
    if (elm != null)
    {
      NodeList children = elm.getChildNodes();
      Map<String, String> webApplicationMimeType = null;
      for (int n = 0; n < children.getLength(); n++)
      {
        Node child = children.item(n);
        if (child.getNodeType() == 1)
        {
          String nodeName = child.getNodeName();
          if (nodeName.equals("display-name"))
          {
            displayName = getTextFromNode(child);
          }
          else if (nodeName.equals("distributable"))
          {
            distributable = Boolean.TRUE.booleanValue();
          }
          else if (nodeName.equals("security-constraint"))
          {
            constraintNodes.add(child);
          }
          else if (nodeName.equals("env-entry"))
          {
            envEntryNodes.add(child);
          }
          else if (nodeName.equals("login-config"))
          {
            loginConfigNode = child;
          }
          else if (nodeName.equals("session-config"))
          {
            for (int m = 0; m < child.getChildNodes().getLength(); m++)
            {
              Node timeoutElm = child.getChildNodes().item(m);
              if ((timeoutElm.getNodeType() == 1) && (timeoutElm.getNodeName().equals("session-timeout")))
              {
                String timeoutStr = getTextFromNode(timeoutElm);
                if (!timeoutStr.equals("")) {
                  sessionTimeout = Integer.valueOf(timeoutStr);
                }
              }
            }
          }
          else if (child.getNodeName().equals("security-role"))
          {
            for (int m = 0; m < child.getChildNodes().getLength(); m++)
            {
              Node roleElm = child.getChildNodes().item(m);
              if ((roleElm.getNodeType() == 1) && (roleElm.getNodeName().equals("role-name"))) {
                rolesAllowed.add(getTextFromNode(roleElm));
              }
            }
          }
          else if (nodeName.equals("servlet"))
          {
            ServletConfiguration instance = new ServletConfiguration(this, child);
            servletInstances.put(instance.getServletName(), instance);
            if (instance.getLoadOnStartup() >= 0) {
              startupServlets.add(instance);
            }
          }
          else if (nodeName.equals("filter"))
          {
            FilterConfiguration instance = new FilterConfiguration(this, loader, child);
            filterInstances.put(instance.getFilterName(), instance);
          }
          else if (nodeName.equals("listener"))
          {
            String listenerClass = null;
            for (int m = 0; m < child.getChildNodes().getLength(); m++)
            {
              Node listenerElm = child.getChildNodes().item(m);
              if ((listenerElm.getNodeType() == 1) && (listenerElm.getNodeName().equals("listener-class"))) {
                listenerClass = getTextFromNode(listenerElm);
              }
            }
            if (listenerClass != null) {
              try
              {
                Class<?> listener = Class.forName(listenerClass, Boolean.TRUE.booleanValue(), loader);
                Object listenerInstance = listener.newInstance();
                addListenerInstance(listenerInstance, contextAttributeListeners, contextListeners, requestAttributeListeners, requestListeners, sessionActivationListeners, sessionAttributeListeners, sessionListeners);
                logger.debug("Adding web application listener: {}", listenerClass);
              }
              catch (Throwable err)
              {
                logger.warn("Error instantiating listener class:  " + listenerClass, err);
              }
            }
          }
          else
          {
            String name;
            Iterator<String> i;
            if (nodeName.equals("servlet-mapping"))
            {
              name = null;
              List<String> mappings = new ArrayList();
              
              NodeList mappingChildren = child.getChildNodes();
              for (int k = 0; k < mappingChildren.getLength(); k++)
              {
                Node mapChild = mappingChildren.item(k);
                if (mapChild.getNodeType() == 1)
                {
                  String mapNodeName = mapChild.getNodeName();
                  if (mapNodeName.equals("servlet-name")) {
                    name = getTextFromNode(mapChild);
                  } else if (mapNodeName.equals("url-pattern")) {
                    mappings.add(getTextFromNode(mapChild));
                  }
                }
              }
              for (i = mappings.iterator(); i.hasNext();) {
                processMapping(name, (String)i.next(), exactServletMatchMounts, localFolderPatterns, localExtensionPatterns);
              }
            }
            else
            {
              String filterName;
              boolean onRequest;
              boolean onForward;
              boolean onInclude;
              boolean onError;
              Iterator<String> i;
              if (nodeName.equals("filter-mapping"))
              {
                filterName = null;
                List<String> mappings = new ArrayList();
                onRequest = Boolean.FALSE.booleanValue();
                onForward = Boolean.FALSE.booleanValue();
                onInclude = Boolean.FALSE.booleanValue();
                onError = Boolean.FALSE.booleanValue();
                for (int k = 0; k < child.getChildNodes().getLength(); k++)
                {
                  Node mapChild = child.getChildNodes().item(k);
                  if (mapChild.getNodeType() == 1)
                  {
                    String mapNodeName = mapChild.getNodeName();
                    if (mapNodeName.equals("filter-name"))
                    {
                      filterName = getTextFromNode(mapChild);
                    }
                    else if (mapNodeName.equals("servlet-name"))
                    {
                      mappings.add("srv:" + getTextFromNode(mapChild));
                    }
                    else if (mapNodeName.equals("url-pattern"))
                    {
                      mappings.add("url:" + getTextFromNode(mapChild));
                    }
                    else if (mapNodeName.equals("dispatcher"))
                    {
                      String dispatcherValue = getTextFromNode(mapChild);
                      if (dispatcherValue.equals("REQUEST")) {
                        onRequest = Boolean.TRUE.booleanValue();
                      } else if (dispatcherValue.equals("FORWARD")) {
                        onForward = Boolean.TRUE.booleanValue();
                      } else if (dispatcherValue.equals("INCLUDE")) {
                        onInclude = Boolean.TRUE.booleanValue();
                      } else if (dispatcherValue.equals("ERROR")) {
                        onError = Boolean.TRUE.booleanValue();
                      }
                    }
                  }
                }
                if ((!onRequest) && (!onInclude) && (!onForward) && (!onError)) {
                  onRequest = Boolean.TRUE.booleanValue();
                }
                if (mappings.isEmpty()) {
                  throw new WinstoneException("Error in filter mapping - no pattern and no servlet name for filter " + filterName);
                }
                for (i = mappings.iterator(); i.hasNext();)
                {
                  String item = (String)i.next();
                  Mapping mapping = null;
                  try
                  {
                    if (item.startsWith("srv:")) {
                      mapping = Mapping.createFromLink(filterName, item.substring(4));
                    } else {
                      mapping = Mapping.createFromURL(filterName, item.substring(4));
                    }
                    if (onRequest) {
                      lfpRequest.add(mapping);
                    }
                    if (onForward) {
                      lfpForward.add(mapping);
                    }
                    if (onInclude) {
                      lfpInclude.add(mapping);
                    }
                    if (onError) {
                      lfpError.add(mapping);
                    }
                  }
                  catch (WinstoneException err)
                  {
                    logger.warn("Error processing URL mapping: {}", err.getMessage());
                  }
                }
              }
              else if (nodeName.equals("welcome-file-list"))
              {
                for (int m = 0; m < child.getChildNodes().getLength(); m++)
                {
                  Node welcomeFile = child.getChildNodes().item(m);
                  if ((welcomeFile.getNodeType() == 1) && (welcomeFile.getNodeName().equals("welcome-file")))
                  {
                    String welcomeStr = getTextFromNode(welcomeFile);
                    if (!welcomeStr.equals("")) {
                      localWelcomeFiles.add(welcomeStr);
                    }
                  }
                }
              }
              else if (nodeName.equals("error-page"))
              {
                String code = null;
                String exception = null;
                String location = null;
                for (int k = 0; k < child.getChildNodes().getLength(); k++)
                {
                  Node errorChild = child.getChildNodes().item(k);
                  if (errorChild.getNodeType() == 1)
                  {
                    String errorChildName = errorChild.getNodeName();
                    if (errorChildName.equals("error-code")) {
                      code = getTextFromNode(errorChild);
                    } else if (errorChildName.equals("exception-type")) {
                      exception = getTextFromNode(errorChild);
                    } else if (errorChildName.equals("location")) {
                      location = getTextFromNode(errorChild);
                    }
                  }
                }
                if ((code != null) && (location != null)) {
                  errorPagesByCode.put(code.trim(), location.trim());
                }
                if ((exception != null) && (location != null)) {
                  try
                  {
                    Class<?> exceptionClass = Class.forName(exception.trim(), Boolean.FALSE.booleanValue(), loader);
                    localErrorPagesByExceptionList.add(exceptionClass);
                    errorPagesByException.put(exceptionClass, location.trim());
                  }
                  catch (ClassNotFoundException err)
                  {
                    logger.error("Exception {} not found in classpath", exception);
                  }
                }
              }
              else if (nodeName.equals("mime-mapping"))
              {
                String extension = null;
                String mimeType = null;
                for (int m = 0; m < child.getChildNodes().getLength(); m++)
                {
                  Node mimeTypeNode = child.getChildNodes().item(m);
                  if (mimeTypeNode.getNodeType() == 1) {
                    if (mimeTypeNode.getNodeName().equals("extension")) {
                      extension = getTextFromNode(mimeTypeNode);
                    } else if (mimeTypeNode.getNodeName().equals("mime-type")) {
                      mimeType = getTextFromNode(mimeTypeNode);
                    }
                  }
                }
                if ((extension != null) && (mimeType != null))
                {
                  if (webApplicationMimeType == null) {
                    webApplicationMimeType = new HashMap();
                  }
                  webApplicationMimeType.put(extension.toLowerCase(), mimeType);
                }
                else
                {
                  logger.warn("WebAppConfig: Ignoring invalid mime mapping: extension={} mimeType={}", extension, mimeType);
                }
              }
              else if (nodeName.equals("context-param"))
              {
                String name = null;
                String value = null;
                for (int m = 0; m < child.getChildNodes().getLength(); m++)
                {
                  Node contextParamNode = child.getChildNodes().item(m);
                  if (contextParamNode.getNodeType() == 1) {
                    if (contextParamNode.getNodeName().equals("param-name")) {
                      name = getTextFromNode(contextParamNode);
                    } else if (contextParamNode.getNodeName().equals("param-value")) {
                      value = getTextFromNode(contextParamNode);
                    }
                  }
                }
                if ((name != null) && (value != null)) {
                  initParameters.put(name, value);
                } else {
                  logger.warn("WebAppConfig: Ignoring invalid init parameter: name={} value={}", name, value);
                }
              }
              else if (nodeName.equals("locale-encoding-mapping-list"))
              {
                for (int m = 0; m < child.getChildNodes().getLength(); m++)
                {
                  Node mappingNode = child.getChildNodes().item(m);
                  if (mappingNode.getNodeType() == 1) {
                    if (mappingNode.getNodeName().equals("locale-encoding-mapping"))
                    {
                      String localeName = "";
                      String encoding = "";
                      for (int l = 0; l < mappingNode.getChildNodes().getLength(); l++)
                      {
                        Node mappingChildNode = mappingNode.getChildNodes().item(l);
                        if (mappingChildNode.getNodeType() == 1) {
                          if (mappingChildNode.getNodeName().equals("locale")) {
                            localeName = getTextFromNode(mappingChildNode);
                          } else if (mappingChildNode.getNodeName().equals("encoding")) {
                            encoding = getTextFromNode(mappingChildNode);
                          }
                        }
                      }
                      if ((!encoding.equals("")) && (!localeName.equals(""))) {
                        localeEncodingMap.put(localeName, encoding);
                      }
                    }
                  }
                }
              }
              else if (nodeName.equals("jsp-config"))
              {
                for (int m = 0; m < child.getChildNodes().getLength(); m++)
                {
                  Node propertyGroupNode = child.getChildNodes().item(m);
                  if ((propertyGroupNode.getNodeType() == 1) && (propertyGroupNode.getNodeName().equals("jsp-property-group"))) {
                    for (int l = 0; l < propertyGroupNode.getChildNodes().getLength(); l++)
                    {
                      Node urlPatternNode = propertyGroupNode.getChildNodes().item(l);
                      if ((urlPatternNode.getNodeType() == 1) && (urlPatternNode.getNodeName().equals("url-pattern")))
                      {
                        String jm = getTextFromNode(urlPatternNode);
                        if (!jm.equals("")) {
                          jspMappings.add(jm);
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
      if (webApplicationMimeType != null) {
        mimeTypes = MimeTypes.getInstance(webApplicationMimeType);
      }
    }
    if (mimeTypes == null) {
      mimeTypes = MimeTypes.getInstance();
    }
    if ((!distributable) && (cluster != null))
    {
      logger.info("Clustering disabled for webapp {} - the web application must be distributable", this.contextName);
      this.cluster = null;
    }
    else
    {
      this.cluster = cluster;
    }
    if ((!constraintNodes.isEmpty()) && (loginConfigNode != null))
    {
      String authMethod = null;
      for (int n = 0; n < loginConfigNode.getChildNodes().getLength(); n++) {
        if (loginConfigNode.getChildNodes().item(n).getNodeName().equals("auth-method")) {
          authMethod = getTextFromNode(loginConfigNode.getChildNodes().item(n));
        }
      }
      if (authMethod == null) {
        authMethod = "BASIC";
      } else {
        authMethod = StringUtils.replace(authMethod, "-", "");
      }
      String realmClassName = StringUtils.stringArg(startupArgs, "realmClassName", ArgumentsRealm.class.getCanonicalName()).trim();
      String authClassName = "net.winstone.core.authentication." + authMethod.substring(0, 1).toUpperCase() + authMethod.substring(1).toLowerCase() + "AuthenticationHandler";
      try
      {
        Class<?> realmClass = Class.forName(realmClassName);
        Constructor<?> realmConstr = realmClass.getConstructor(new Class[] { Set.class, Map.class });
        authenticationRealm = ((AuthenticationRealm)realmConstr.newInstance(new Object[] { rolesAllowed, startupArgs }));
        
        Class<?> authClass = Class.forName(authClassName);
        Constructor<?> authConstr = authClass.getConstructor(new Class[] { Node.class, List.class, Set.class, AuthenticationRealm.class });
        authenticationHandler = ((AuthenticationHandler)authConstr.newInstance(new Object[] { loginConfigNode, constraintNodes, rolesAllowed, authenticationRealm }));
      }
      catch (ClassNotFoundException err)
      {
        logger.error("Authentication disabled - can't load authentication handler for {} authentication", authMethod);
      }
      catch (Throwable err)
      {
        logger.error("Authentication disabled - couldn't load authentication handler: " + authClassName + " or realm: " + realmClassName, err);
      }
    }
    else if (!StringUtils.stringArg(startupArgs, "realmClassName", "").trim().equals(""))
    {
      logger.warn("WARNING: Realm configuration ignored, because there are no roles defined in the web.xml ");
    }
    if (useJNDI) {
      webAppJNDIManager = new WebAppJNDIManager(jndiManager, envEntryNodes, loader);
    } else {
      webAppJNDIManager = null;
    }
    String loggerClassName = StringUtils.stringArg(startupArgs, "accessLoggerClassName", "").trim();
    if (!loggerClassName.equals("")) {
      try
      {
        accessLogger = AccessLoggerProviderFactory.getAccessLogger(getOwnerHostname(), getContextName(), PatternType.valueOf(StringUtils.stringArg(startupArgs, "simpleAccessLogger.format", "combined")), StringUtils.stringArg(startupArgs, "simpleAccessLogger.file", "logs/###host###/###webapp###_access.log"));
      }
      catch (Throwable err)
      {
        logger.error("Error instantiating access logger class: " + loggerClassName, err);
      }
    } else {
      logger.info("Access logging disabled - no logger class defined");
    }
    if (localWelcomeFiles.isEmpty())
    {
      if (useJasper) {
        localWelcomeFiles.add("index.jsp");
      }
      localWelcomeFiles.add("index.html");
    }
    filterPatternsRequest = ((Mapping[])lfpRequest.toArray(new Mapping[0]));
    filterPatternsForward = ((Mapping[])lfpForward.toArray(new Mapping[0]));
    filterPatternsInclude = ((Mapping[])lfpInclude.toArray(new Mapping[0]));
    filterPatternsError = ((Mapping[])lfpError.toArray(new Mapping[0]));
    
    welcomeFiles = ((String[])localWelcomeFiles.toArray(new String[0]));
    errorPagesByExceptionKeysSorted = ((Class[])localErrorPagesByExceptionList.toArray(new Class[0]));
    Arrays.sort(errorPagesByExceptionKeysSorted, this);
    
    this.contextAttributeListeners = ((ServletContextAttributeListener[])contextAttributeListeners.toArray(new ServletContextAttributeListener[0]));
    this.contextListeners = ((ServletContextListener[])contextListeners.toArray(new ServletContextListener[0]));
    this.requestListeners = ((ServletRequestListener[])requestListeners.toArray(new ServletRequestListener[0]));
    this.requestAttributeListeners = ((ServletRequestAttributeListener[])requestAttributeListeners.toArray(new ServletRequestAttributeListener[0]));
    this.sessionActivationListeners = ((HttpSessionActivationListener[])sessionActivationListeners.toArray(new HttpSessionActivationListener[0]));
    this.sessionAttributeListeners = ((HttpSessionAttributeListener[])sessionAttributeListeners.toArray(new HttpSessionAttributeListener[0]));
    this.sessionListeners = ((HttpSessionListener[])sessionListeners.toArray(new HttpSessionListener[0]));
    if (defaultServletName == null) {
      defaultServletName = "default";
    }
    if (errorServletName == null) {
      errorServletName = "winstoneErrorServlet";
    }
    boolean useDirLists = StringUtils.booleanArg(startupArgs, "directoryListings", Boolean.TRUE.booleanValue());
    Map<String, String> staticParams = new HashMap();
    staticParams.put("webRoot", webRoot);
    staticParams.put("prefix", this.prefix);
    staticParams.put("directoryList", "" + useDirLists);
    if (servletInstances.get(defaultServletName) == null)
    {
      ServletConfiguration defaultServlet = new ServletConfiguration(this, defaultServletName, StaticResourceServlet.class.getName(), staticParams, 0);
      servletInstances.put(defaultServletName, defaultServlet);
      startupServlets.add(defaultServlet);
    }
    if ((StringUtils.booleanArg(startupArgs, "alwaysMountDefaultServlet", Boolean.TRUE.booleanValue())) && (servletInstances.get("default") == null))
    {
      ServletConfiguration defaultServlet = new ServletConfiguration(this, "default", StaticResourceServlet.class.getName(), staticParams, 0);
      servletInstances.put("default", defaultServlet);
      startupServlets.add(defaultServlet);
    }
    if (servletInstances.get(errorServletName) == null)
    {
      ServletConfiguration errorServlet = new ServletConfiguration(this, errorServletName, ErrorServlet.class.getName(), new HashMap(), 0);
      servletInstances.put(errorServletName, errorServlet);
      startupServlets.add(errorServlet);
    }
    Iterator<String> mapIt;
    if (useJasper)
    {
      setAttribute("org.apache.catalina.classloader", loader);
      setAttribute("org.apache.catalina.jsp_classpath", StringUtils.stringArg(startupArgs, "jspClasspath", ""));
      
      Map<String, String> jspParams = new HashMap();
      addJspServletParams(jspParams);
      ServletConfiguration sc = new ServletConfiguration(this, "JspServlet", "org.apache.jasper.servlet.JspServlet", jspParams, 3);
      servletInstances.put("JspServlet", sc);
      startupServlets.add(sc);
      for (mapIt = jspMappings.iterator(); mapIt.hasNext();) {
        processMapping("JspServlet", (String)mapIt.next(), exactServletMatchMounts, localFolderPatterns, localExtensionPatterns);
      }
    }
    if (useInvoker)
    {
      String invokerPrefix = StringUtils.stringArg(startupArgs, "invokerPrefix", "/servlet/");
      Map<String, String> invokerParams = new HashMap();
      invokerParams.put("prefix", this.prefix);
      invokerParams.put("invokerPrefix", invokerPrefix);
      ServletConfiguration sc = new ServletConfiguration(this, "invoker", InvokerServlet.class.getName(), invokerParams, 3);
      servletInstances.put("invoker", sc);
      processMapping("invoker", invokerPrefix + "*", exactServletMatchMounts, localFolderPatterns, localExtensionPatterns);
    }
    localFolderPatterns.addAll(localExtensionPatterns);
    patternMatches = ((Mapping[])localFolderPatterns.toArray(new Mapping[0]));
    if (patternMatches.length > 0) {
      Arrays.sort(patternMatches, patternMatches[0]);
    }
    try
    {
      for (int n = 0; n < this.contextListeners.length; n++)
      {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(loader);
        this.contextListeners[n].contextInitialized(new ServletContextEvent(this));
        Thread.currentThread().setContextClassLoader(cl);
      }
    }
    catch (Throwable err)
    {
      logger.error("Error during context startup for webapp " + this.contextName, err);
      contextStartupError = err;
    }
    if (contextStartupError == null)
    {
      if (useSavedSessions) {
        WinstoneSession.loadSessions(this);
      }
      for (Iterator<FilterConfiguration> i = filterInstances.values().iterator(); i.hasNext();)
      {
        FilterConfiguration config = (FilterConfiguration)i.next();
        try
        {
          config.getFilter();
        }
        catch (ServletException err)
        {
          logger.error("Error during filter initialization: " + config.getFilterName(), err);
        }
      }
      Object[] autoStarters = startupServlets.toArray();
      Arrays.sort(autoStarters);
      for (int n = 0; n < autoStarters.length; n++) {
        ((ServletConfiguration)autoStarters[n]).ensureInitialization();
      }
    }
  }
  
  private ClassLoader buildWebAppClassLoader(Map<String, String> startupArgs, ClassLoader parentClassLoader, String webRoot, List<File> classPathFileList)
  {
    List<URL> urlList = new ArrayList();
    try
    {
      File webInfFolder = new File(webRoot, "WEB-INF");
      
      File classesFolder = new File(webInfFolder, "classes/");
      if (classesFolder.exists())
      {
        logger.debug("Adding webapp classes folder to classpath");
        String classesFolderURL = classesFolder.getCanonicalFile().toURI().toURL().toString();
        urlList.add(new URL(classesFolderURL + "/"));
        classPathFileList.add(classesFolder);
      }
      else
      {
        logger.warn("No webapp classes folder found - {}", classesFolder.toString());
      }
      File libFolder = new File(webInfFolder, "lib");
      if (libFolder.exists())
      {
        File[] jars = libFolder.listFiles();
        for (int n = 0; n < jars.length; n++)
        {
          String jarName = jars[n].getName().toLowerCase();
          if ((jarName.endsWith(".jar")) || (jarName.endsWith(".zip")))
          {
            logger.debug("Adding webapp lib {} to classpath", jars[n].getName());
            urlList.add(jars[n].toURI().toURL());
            classPathFileList.add(jars[n]);
          }
        }
      }
      else
      {
        logger.warn("No webapp lib folder found - {}", libFolder.toString());
      }
    }
    catch (MalformedURLException err)
    {
      throw new WinstoneException("Bad URL in WinstoneClassLoader", err);
    }
    catch (IOException err)
    {
      throw new WinstoneException("IOException in WinstoneClassLoader", err);
    }
    URL[] jarURLs = (URL[])urlList.toArray(new URL[urlList.size()]);
    
    String preferredClassLoader = StringUtils.stringArg(startupArgs, "preferredClassLoader", WebappClassLoader.class.getName());
    if ((StringUtils.booleanArg(startupArgs, "useServletReloading", Boolean.FALSE.booleanValue())) && (StringUtils.stringArg(startupArgs, "preferredClassLoader", "").equals(""))) {
      preferredClassLoader = ReloadingClassLoader.class.getName();
    }
    ClassLoader outputCL = null;
    if (!preferredClassLoader.equals("")) {
      try
      {
        Class<?> preferredCL = Class.forName(preferredClassLoader, Boolean.TRUE.booleanValue(), parentClassLoader);
        Constructor<?> reloadConstr = preferredCL.getConstructor(new Class[] { URL[].class, ClassLoader.class });
        outputCL = (ClassLoader)reloadConstr.newInstance(new Object[] { jarURLs, parentClassLoader });
      }
      catch (Throwable err)
      {
        if ((!StringUtils.stringArg(startupArgs, "preferredClassLoader", "").equals("")) || (!preferredClassLoader.equals(WebappClassLoader.class.getName()))) {
          logger.error("Erroring setting class loader", err);
        }
      }
    }
    if (outputCL == null) {
      outputCL = new URLClassLoader(jarURLs, parentClassLoader);
    }
    logger.debug("Using Webapp classloader: {}", outputCL.toString());
    return outputCL;
  }
  
  private void addListenerInstance(Object listenerInstance, List<ServletContextAttributeListener> contextAttributeListeners, List<ServletContextListener> contextListeners, List<ServletRequestAttributeListener> requestAttributeListeners, List<ServletRequestListener> requestListeners, List<HttpSessionActivationListener> sessionActivationListeners, List<HttpSessionAttributeListener> sessionAttributeListeners, List<HttpSessionListener> sessionListeners)
  {
    if ((listenerInstance instanceof ServletContextAttributeListener)) {
      contextAttributeListeners.add((ServletContextAttributeListener)listenerInstance);
    }
    if ((listenerInstance instanceof ServletContextListener)) {
      contextListeners.add((ServletContextListener)listenerInstance);
    }
    if ((listenerInstance instanceof ServletRequestAttributeListener)) {
      requestAttributeListeners.add((ServletRequestAttributeListener)listenerInstance);
    }
    if ((listenerInstance instanceof ServletRequestListener)) {
      requestListeners.add((ServletRequestListener)listenerInstance);
    }
    if ((listenerInstance instanceof HttpSessionActivationListener)) {
      sessionActivationListeners.add((HttpSessionActivationListener)listenerInstance);
    }
    if ((listenerInstance instanceof HttpSessionAttributeListener)) {
      sessionAttributeListeners.add((HttpSessionAttributeListener)listenerInstance);
    }
    if ((listenerInstance instanceof HttpSessionListener)) {
      sessionListeners.add((HttpSessionListener)listenerInstance);
    }
  }
  
  public String getContextPath()
  {
    return prefix;
  }
  
  public String getWebroot()
  {
    return webRoot;
  }
  
  public ClassLoader getLoader()
  {
    return loader;
  }
  
  public AccessLogger getAccessLogger()
  {
    return accessLogger;
  }
  
  public Map<String, FilterConfiguration> getFilters()
  {
    return filterInstances;
  }
  
  public final String getContextName()
  {
    return contextName;
  }
  
  public Class<?>[] getErrorPageExceptions()
  {
    return errorPagesByExceptionKeysSorted;
  }
  
  public Map<Class<?>, String> getErrorPagesByException()
  {
    return errorPagesByException;
  }
  
  public Map<String, String> getErrorPagesByCode()
  {
    return errorPagesByCode;
  }
  
  public Map<String, String> getLocaleEncodingMap()
  {
    return localeEncodingMap;
  }
  
  public String[] getWelcomeFiles()
  {
    return welcomeFiles;
  }
  
  public boolean isDistributable()
  {
    return cluster != null;
  }
  
  public Map<String, FilterConfiguration[]> getFilterMatchCache()
  {
    return filterMatchCache;
  }
  
  public final String getOwnerHostname()
  {
    return ownerHostConfig.getHostname();
  }
  
  public ServletRequestListener[] getRequestListeners()
  {
    return requestListeners;
  }
  
  public ServletRequestAttributeListener[] getRequestAttributeListeners()
  {
    return requestAttributeListeners;
  }
  
  public static void addJspServletParams(Map<String, String> jspParams)
  {
    jspParams.put("logVerbosityLevel", "WARNING");
    jspParams.put("fork", "Boolean.FALSE");
  }
  
  public int compare(Object one, Object two)
  {
    if ((!(one instanceof Class)) || (!(two instanceof Class))) {
      throw new IllegalArgumentException("This comparator is only for sorting classes");
    }
    Class classOne = (Class)one;
    
    Class classTwo = (Class)two;
    if (classOne.isAssignableFrom(classTwo)) {
      return 1;
    }
    if (classTwo.isAssignableFrom(classOne)) {
      return -1;
    }
    return 0;
  }
  
  public String getServletURIFromRequestURI(String requestURI)
  {
    if (prefix.equals("")) {
      return requestURI;
    }
    if (requestURI.startsWith(prefix)) {
      return requestURI.substring(prefix.length());
    }
    throw new WinstoneException("This shouldn't happen, since we aborted earlier if we didn't match");
  }
  
  public void destroy()
  {
    synchronized (filterMatchCache)
    {
      filterMatchCache.clear();
    }
    Collection<FilterConfiguration> filterInstances = new ArrayList(this.filterInstances.values());
    for (Object i = filterInstances.iterator(); ((Iterator)i).hasNext();) {
      try
      {
        ((FilterConfiguration)((Iterator)i).next()).destroy();
      }
      catch (Throwable err)
      {
        logger.error("Error during servlet context shutdown", err);
      }
    }
    this.filterInstances.clear();
    
    Object servletInstances = new ArrayList(this.servletInstances.values());
    for (Iterator<ServletConfiguration> i = ((Collection)servletInstances).iterator(); i.hasNext();) {
      try
      {
        ((ServletConfiguration)i.next()).destroy();
      }
      catch (Throwable err)
      {
        logger.error("Error during servlet context shutdown", err);
      }
    }
    this.servletInstances.clear();
    
    Collection<WinstoneSession> sessions = new ArrayList(this.sessions.values());
    for (Iterator<WinstoneSession> i = sessions.iterator(); i.hasNext();)
    {
      WinstoneSession session = (WinstoneSession)i.next();
      try
      {
        if (useSavedSessions) {
          session.saveToTemp();
        } else {
          session.invalidate();
        }
      }
      catch (Throwable err)
      {
        logger.error("Error during servlet context shutdown", err);
      }
    }
    this.sessions.clear();
    for (int n = contextListeners.length - 1; n >= 0; n--) {
      try
      {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(loader);
        contextListeners[n].contextDestroyed(new ServletContextEvent(this));
        contextListeners[n] = null;
        Thread.currentThread().setContextClassLoader(cl);
      }
      catch (Throwable err)
      {
        logger.error("Error during servlet context shutdown", err);
      }
    }
    contextListeners = null;
    if (loader != null) {
      loader = null;
    }
    if (webAppJNDIManager != null)
    {
      webAppJNDIManager.destroy();
      webAppJNDIManager = null;
    }
    if (accessLogger != null)
    {
      AccessLoggerProviderFactory.destroy(accessLogger);
      accessLogger = null;
    }
  }
  
  public void resetClassLoader()
    throws IOException
  {
    ownerHostConfig.reloadWebApp(getContextPath());
  }
  
  private void processMapping(String name, String pattern, Map<String, String> exactPatterns, List<Mapping> folderPatterns, List<Mapping> extensionPatterns)
  {
    Mapping urlPattern = null;
    try
    {
      urlPattern = Mapping.createFromURL(name, pattern);
    }
    catch (WinstoneException err)
    {
      logger.warn("WebAppConfig.ErrorMapURL {}", err.getMessage());
      return;
    }
    if (urlPattern.getPatternType() == 1) {
      exactPatterns.put(urlPattern.getUrlPattern(), name);
    } else if (urlPattern.getPatternType() == 2) {
      folderPatterns.add(urlPattern);
    } else if (urlPattern.getPatternType() == 3) {
      extensionPatterns.add(urlPattern);
    } else if (urlPattern.getPatternType() == 4) {
      defaultServletName = name;
    } else {
      logger.warn("WebAppConfig: Invalid pattern mount for {} pattern {} - ignoring", name, pattern);
    }
  }
  
  public ServletConfiguration urlMatch(String path, StringBuilder servletPath, StringBuilder pathInfo)
  {
    logger.debug("URL Match - path: {}", path);
    
    String exact = (String)exactServletMatchMounts.get(path);
    if ((exact != null) && 
      (servletInstances.get(exact) != null))
    {
      servletPath.append(WinstoneRequest.decodePathURLToken(path));
      
      return (ServletConfiguration)servletInstances.get(exact);
    }
    for (int n = 0; n < patternMatches.length; n++)
    {
      Mapping urlPattern = patternMatches[n];
      if ((urlPattern.match(path, servletPath, pathInfo)) && (servletInstances.get(urlPattern.getMappedTo()) != null)) {
        return (ServletConfiguration)servletInstances.get(urlPattern.getMappedTo());
      }
    }
    if (servletInstances.get(defaultServletName) == null) {
      throw new WinstoneException("Matched URL to a servlet that doesn't exist: " + defaultServletName);
    }
    servletPath.append(WinstoneRequest.decodePathURLToken(path));
    return (ServletConfiguration)servletInstances.get(defaultServletName);
  }
  
  public WinstoneSession makeNewSession(String sessionId)
  {
    WinstoneSession ws = new WinstoneSession(sessionId);
    ws.setWebAppConfiguration(this);
    setSessionListeners(ws);
    if (sessionTimeout == null) {
      ws.setMaxInactiveInterval(3600);
    } else if (sessionTimeout.intValue() > 0) {
      ws.setMaxInactiveInterval(sessionTimeout.intValue() * 60);
    } else {
      ws.setMaxInactiveInterval(-1);
    }
    ws.setLastAccessedDate(System.currentTimeMillis());
    ws.sendCreatedNotifies();
    sessions.put(sessionId, ws);
    return ws;
  }
  
  public WinstoneSession getSessionById(String sessionId, boolean localOnly)
  {
    if (sessionId == null) {
      return null;
    }
    WinstoneSession session = (WinstoneSession)sessions.get(sessionId);
    if (session != null) {
      return session;
    }
    if ((isDistributable()) && (!localOnly))
    {
      session = cluster.askClusterForSession(sessionId, this);
      if (session != null) {
        sessions.put(sessionId, session);
      }
      return session;
    }
    return null;
  }
  
  public void removeSessionById(String sessionId)
  {
    sessions.remove(sessionId);
  }
  
  public void addSession(String sessionId, WinstoneSession session)
  {
    sessions.put(sessionId, session);
  }
  
  public void invalidateExpiredSessions()
  {
    Object[] allSessions = sessions.values().toArray();
    int expiredCount = 0;
    for (int n = 0; n < allSessions.length; n++)
    {
      WinstoneSession session = (WinstoneSession)allSessions[n];
      if ((session.isUnusedByRequests()) && (session.isExpired()))
      {
        session.invalidate();
        expiredCount++;
      }
    }
    if (expiredCount > 0) {
      logger.debug("Invalidating {} sessions due to excessive inactivity", expiredCount + "");
    }
  }
  
  public void setSessionListeners(WinstoneSession session)
  {
    session.setSessionActivationListeners(sessionActivationListeners);
    session.setSessionAttributeListeners(sessionAttributeListeners);
    session.setSessionListeners(sessionListeners);
  }
  
  public void removeServletConfigurationAndMappings(ServletConfiguration config)
  {
    servletInstances.remove(config.getServletName());
  }
  
  public Object getAttribute(String name)
  {
    return attributes.get(name);
  }
  
  public Enumeration<String> getAttributeNames()
  {
    return Collections.enumeration(attributes.keySet());
  }
  
  public void removeAttribute(String name)
  {
    Object me = attributes.get(name);
    attributes.remove(name);
    if (me != null) {
      for (int n = 0; n < contextAttributeListeners.length; n++)
      {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        Thread.currentThread().setContextClassLoader(getLoader());
        contextAttributeListeners[n].attributeRemoved(new ServletContextAttributeEvent(this, name, me));
        Thread.currentThread().setContextClassLoader(cl);
      }
    }
  }
  
  public final void setAttribute(String name, Object object)
  {
    if (object == null)
    {
      removeAttribute(name);
    }
    else
    {
      Object me = attributes.get(name);
      attributes.put(name, object);
      if (me != null) {
        for (int n = 0; n < contextAttributeListeners.length; n++)
        {
          ClassLoader cl = Thread.currentThread().getContextClassLoader();
          Thread.currentThread().setContextClassLoader(getLoader());
          contextAttributeListeners[n].attributeReplaced(new ServletContextAttributeEvent(this, name, me));
          Thread.currentThread().setContextClassLoader(cl);
        }
      } else {
        for (int n = 0; n < contextAttributeListeners.length; n++)
        {
          ClassLoader cl = Thread.curr
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