Ejemplo n.º 1
0
  public static void apply(final ServletContext context) {
    // Maybe configurable?
    context.removeAttribute("javax.faces.FACELETS_REFRESH_PERIOD");
    context.setAttribute("javax.faces.FACELETS_REFRESH_PERIOD", "1");

    context.removeAttribute("facelets.REFRESH_PERIOD");
    context.setAttribute("facelets.REFRESH_PERIOD", "1");

    context.removeAttribute("javax.faces.PROJECT_STAGE");
    context.setAttribute("javax.faces.PROJECT_STAGE", "Development");

    context.setInitParameter("javax.faces.FACELETS_REFRESH_PERIOD", "1");
    context.setInitParameter("javax.faces.PROJECT_STAGE", "Development");
    context.setInitParameter("facelets.REFRESH_PERIOD", "1");

    if (LOGGER.isLevelEnabled(Level.TRACE)) {
      Enumeration<String> names = context.getAttributeNames();
      if (names != null) {
        while (names.hasMoreElements()) {
          String k = names.nextElement();
          LOGGER.trace("CONTEXT ATTRIBUTE {} value: {}", k, context.getAttribute(k));
        }
      }

      names = context.getInitParameterNames();
      if (names != null) {
        while (names.hasMoreElements()) {
          String k = names.nextElement();
          LOGGER.trace("CONTEXT INIT PARAM {} value: {}", k, context.getInitParameter(k));
        }
      }
    }
  }
 @Override
 public void contextDestroyed(ServletContextEvent sce) {
   cdiContainer.stop();
   ServletContext context = sce.getServletContext();
   context.removeAttribute("org.ops4j.pax.cdi.ClassIntrospecter");
   context.removeAttribute("org.ops4j.pax.cdi.BeanManager");
   super.contextDestroyed(sce);
 }
Ejemplo n.º 3
0
 /**
  * Sets the preferred locale for the specified servlet context. It is the default locale for the
  * whole Web application.
  *
  * <p>Default: null (no preferred locale -- depending on browser's setting).
  *
  * @param locale the preferred Locale. If null, it means no preferred locale
  * @see #getPreferredLocale(HttpSession,ServletRequest)
  * @since 3.6.3
  */
 public static final void setPreferredLocale(ServletContext ctx, Locale locale) {
   if (locale != null) {
     ctx.setAttribute(Attributes.PREFERRED_LOCALE, locale);
   } else {
     ctx.removeAttribute(Attributes.PREFERRED_LOCALE);
     ctx.removeAttribute(PX_PREFERRED_LOCALE);
   }
 }
 public static void shutdown() {
   _servletContext.removeAttribute(ServletContextKeyEnum.THREADPOOL_EXECUTOR_CONTAINER);
   _servletContext.removeAttribute(ServletContextKeyEnum.LOGIC_THREADPOOL_NAME);
   ScheduledExecutorService cleanSessionTimer =
       (ScheduledExecutorService)
           _servletContext.getAttribute(ServletContextKeyEnum.USER_DEFINED_SESSION_CLEAN_TIMER);
   if (cleanSessionTimer != null) {
     cleanSessionTimer.shutdown();
   }
   _servletContext.removeAttribute(ServletContextKeyEnum.USER_DEFINED_SESSION_CLEAN_TIMER);
   _threadPoolContainer.shutdownNow();
 }
  private void doRemoveAttribute(String name, int scope) {
    switch (scope) {
      case PAGE_SCOPE:
        attributes.remove(name);
        break;

      case REQUEST_SCOPE:
        request.removeAttribute(name);
        break;

      case SESSION_SCOPE:
        if (session == null) {
          throw new IllegalStateException(Localizer.getMessage("jsp.error.page.noSession"));
        }
        session.removeAttribute(name);
        break;

      case APPLICATION_SCOPE:
        context.removeAttribute(name);
        break;

      default:
        throw new IllegalArgumentException("Invalid scope");
    }
  }
Ejemplo n.º 6
0
  @Test
  public void getSetAttributes() {
    ServletContext context = new ServletContext1(new MockWebContext());

    // name0 = value0
    context.setAttribute("name0", "value0");
    Enumeration<String> attributeNames = context.getAttributeNames();
    assertTrue(attributeNames.hasMoreElements());
    assertEquals("name0", attributeNames.nextElement());
    assertFalse(attributeNames.hasMoreElements());

    assertEquals("value0", context.getAttribute("name0"));
    assertNull(context.getAttribute("name1"));

    // name0 = value0, name1 = value1
    context.setAttribute("name1", "value1");
    attributeNames = context.getAttributeNames();
    assertTrue(attributeNames.hasMoreElements());
    String name = attributeNames.nextElement();
    assertTrue(name.equals("name0") || name.equals("name1"));
    assertTrue(attributeNames.hasMoreElements());
    name = attributeNames.nextElement();
    assertTrue(name.equals("name0") || name.equals("name1"));
    assertFalse(attributeNames.hasMoreElements());

    assertEquals("value0", context.getAttribute("name0"));
    assertEquals("value1", context.getAttribute("name1"));

    // name0 = edited, name1 = value1
    context.setAttribute("name0", "edited");
    attributeNames = context.getAttributeNames();
    assertTrue(attributeNames.hasMoreElements());
    name = attributeNames.nextElement();
    assertTrue(name.equals("name0") || name.equals("name1"));
    assertTrue(attributeNames.hasMoreElements());
    name = attributeNames.nextElement();
    assertTrue(name.equals("name0") || name.equals("name1"));
    assertFalse(attributeNames.hasMoreElements());

    assertEquals("edited", context.getAttribute("name0"));
    assertEquals("value1", context.getAttribute("name1"));

    // name0 = edited
    context.removeAttribute("name1");
    attributeNames = context.getAttributeNames();
    assertTrue(attributeNames.hasMoreElements());
    assertEquals("name0", attributeNames.nextElement());
    assertFalse(attributeNames.hasMoreElements());

    assertEquals("edited", context.getAttribute("name0"));
    assertNull(context.getAttribute("name1"));

    // empty
    context.setAttribute("name0", null);
    attributeNames = context.getAttributeNames();
    assertFalse(attributeNames.hasMoreElements());

    assertNull(context.getAttribute("name0"));
    assertNull(context.getAttribute("name1"));
  }
Ejemplo n.º 7
0
 @Override
 public void contextDestroyed(ServletContextEvent event) {
   ServletContext servletContext = event.getServletContext();
   if (servletContext.getAttribute(CONTROL_ATTRIBUTE_NAME) != null) {
     servletContext.removeAttribute(CONTROL_ATTRIBUTE_NAME);
   }
 }
Ejemplo n.º 8
0
  /**
   * Gracefully shut down this database, releasing any resources that were allocated at
   * initialization.
   *
   * @param event ServletContextEvent to process
   */
  public void contextDestroyed(ServletContextEvent event) {

    log.info("Finalizing memory database plug in");

    if (database != null) {
      try {
        database.close();
      } catch (Exception e) {
        log.error("Closing memory database", e);
      }
    }

    context.removeAttribute(DATABASE_KEY);
    context.removeAttribute(PROTOCOLS_KEY);
    database = null;
    context = null;
  }
Ejemplo n.º 9
0
 /**
  * Clearing the in-memory configuration parameters, we will receive notification that the servlet
  * context is about to be shut down
  */
 @Override
 public void contextDestroyed(ServletContextEvent sce) {
   synchronized (servletContext) {
     logger.info("Webapp shutdown");
     // XXX Paul: grabbed this from
     // http://opensource.atlassian.com/confluence/spring/display/DISC/Memory+leak+-+classloader+won%27t+let+go
     // in hopes that we can clear all the issues with J2EE containers
     // during shutdown
     try {
       ServletContext ctx = sce.getServletContext();
       // prepare spring for shutdown
       Introspector.flushCaches();
       // dereg any drivers
       for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements(); ) {
         Driver driver = (Driver) e.nextElement();
         if (driver.getClass().getClassLoader() == getClass().getClassLoader()) {
           DriverManager.deregisterDriver(driver);
         }
       }
       // shutdown jmx
       JMXAgent.shutdown();
       // shutdown the persistence thread
       FilePersistenceThread persistenceThread = FilePersistenceThread.getInstance();
       if (persistenceThread != null) {
         persistenceThread.shutdown();
       }
       // shutdown spring
       Object attr =
           ctx.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
       if (attr != null) {
         // get web application context from the servlet context
         ConfigurableWebApplicationContext applicationContext =
             (ConfigurableWebApplicationContext) attr;
         ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
         // for (String scope : factory.getRegisteredScopeNames()) {
         // logger.debug("Registered scope: " + scope);
         // }
         try {
           for (String singleton : factory.getSingletonNames()) {
             logger.debug("Registered singleton: " + singleton);
             factory.destroyScopedBean(singleton);
           }
         } catch (RuntimeException e) {
         }
         factory.destroySingletons();
         ctx.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
         applicationContext.close();
       }
       getContextLoader().closeWebApplicationContext(ctx);
       //				org.apache.commons.logging.LogFactory.releaseAll();
       //				org.apache.log4j.LogManager.getLoggerRepository().shutdown();
       //				org.apache.log4j.LogManager.shutdown();
     } catch (Throwable e) {
       e.printStackTrace();
     }
   }
 }
Ejemplo n.º 10
0
 public static void clearInstance(ServletContext sc) {
   ApplicationAssociate me = (ApplicationAssociate) sc.getAttribute(ASSOCIATE_KEY);
   if (null != me) {
     if (null != me.resourceBundles) {
       me.resourceBundles.clear();
     }
   }
   sc.removeAttribute(ASSOCIATE_KEY);
 }
  /** Removes bean from scope. */
  public Object remove(String name) {
    Object result = null;

    ServletContext sc = getServletContext();

    result = sc.getAttribute(name);

    sc.removeAttribute(name);

    return result;
  }
Ejemplo n.º 12
0
  private void initConfigMonitoring(ServletContext context) {

    //noinspection unchecked
    Collection<URI> webURIs = (Collection<URI>) context.getAttribute("com.sun.faces.webresources");
    if (isDevModeEnabled() && webURIs != null && !webURIs.isEmpty()) {
      webResourcePool =
          new ScheduledThreadPoolExecutor(1, new MojarraThreadFactory("WebResourceMonitor"));
      webResourcePool.scheduleAtFixedRate(
          new WebConfigResourceMonitor(context, webURIs), 2000, 2000, TimeUnit.MILLISECONDS);
    }
    context.removeAttribute("com.sun.faces.webresources");
  }
  protected void unregisterClpMessageListeners(ServletContext servletContext) throws Exception {

    List<MessageListener> clpMessageListeners =
        (List<MessageListener>) servletContext.getAttribute(WebKeys.CLP_MESSAGE_LISTENERS);

    if (clpMessageListeners != null) {
      servletContext.removeAttribute(WebKeys.CLP_MESSAGE_LISTENERS);

      for (MessageListener clpMessageListener : clpMessageListeners) {
        MessageBusUtil.unregisterMessageListener(DestinationNames.HOT_DEPLOY, clpMessageListener);
      }
    }
  }
Ejemplo n.º 14
0
 static void destroySession(HttpSession session) {
   ServletContext context = session.getServletContext();
   String user = (String) session.getAttribute(ATTRIBUTE_SESSIONUSER);
   if (user != null) {
     String current = (String) session.getAttribute(ATTRIBUTE_SESSIONMATCH);
     String match = (String) context.getAttribute(ATTRIBUTE_SESSIONMATCH + "." + user);
     if (current != null && current.equals(match)) {
       context.removeAttribute(ATTRIBUTE_SESSIONMATCH + "." + user);
     }
   }
   session.removeAttribute(ATTRIBUTE_SESSIONUSER);
   session.removeAttribute(ATTRIBUTE_SESSIONMATCH);
 }
Ejemplo n.º 15
0
  /**
   * This method bootstraps JSF based on the parsed configuration resources.
   *
   * @param sc the <code>ServletContext</code> for the application that requires initialization
   */
  public void initialize(ServletContext sc) {

    if (!hasBeenInitialized(sc)) {
      initializedContexts.add(sc);
      try {
        WebConfiguration webConfig = WebConfiguration.getInstance(sc);
        boolean validating = webConfig.isOptionEnabled(ValidateFacesConfigFiles);
        ExecutorService executor = createExecutorService();

        Document[] facesDocuments =
            getConfigDocuments(sc, getFacesConfigResourceProviders(), executor, validating);

        WebInfFacesConfigInfo facesConfigInfo =
            new WebInfFacesConfigInfo(facesDocuments[facesDocuments.length - 1]);

        facesDocuments = sortDocuments(facesDocuments, facesConfigInfo);

        boolean isFaceletsDisabled = isFaceletsDisabled(webConfig, facesConfigInfo);
        if (!facesConfigInfo.isMetadataComplete()) {
          // execute the Task responsible for finding annotation classes
          Future<Map<Class<? extends Annotation>, Set<Class<?>>>> annotationScan =
              executor.submit(new AnnotationScanTask(sc));
          pushTaskToContext(sc, annotationScan);
        }

        // process the ordered documents
        FACES_CONFIG_PROCESSOR_CHAIN.process(facesDocuments);
        if (!isFaceletsDisabled) {
          FACELET_TAGLIB_CONFIG_PROCESSOR_CHAIN.process(
              getConfigDocuments(sc, getFaceletConfigResourceProviders(), executor, validating));
        }

        executor.shutdown();
        publishPostConfigEvent();
      } catch (Exception e) {
        // clear out any configured factories
        releaseFactories();
        if (LOGGER.isLoggable(Level.INFO)) {
          LOGGER.log(Level.INFO, "Unsanitized stacktrace from failed start...", e);
        }
        Throwable t = unwind(e);
        throw new ConfigurationException("CONFIGURATION FAILED! " + t.getMessage(), t);
      } finally {
        sc.removeAttribute(ANNOTATIONS_SCAN_TASK_KEY);
      }
    }
  }
Ejemplo n.º 16
0
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    ServletContext context = request.getServletContext();

    String attrName = request.getParameter("attrName");
    String attrValue = request.getParameter("attrValue");
    String command = request.getParameter("command");

    switch (command) {
      case "set":
        context.setAttribute(attrName, attrValue);
        break;
      default:
        context.removeAttribute(attrName);
    }

    response.setContentType("text/plain;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("ServletContext에 값을 저장하거나 변경, 삭제하였습니다.");
  }
Ejemplo n.º 17
0
 public void clear() {
   Iterator keys = keySet().iterator();
   while (keys.hasNext()) {
     context.removeAttribute((String) keys.next());
   }
 }
Ejemplo n.º 18
0
 public Object remove(Object key) {
   String skey = key(key);
   Object previous = context.getAttribute(skey);
   context.removeAttribute(skey);
   return (previous);
 }
Ejemplo n.º 19
0
 /**
  * Destroys the {@link Config} for the given servlet context.
  *
  * @param servletContext the web apps servlet context
  */
 public void destroyConfig(ServletContext servletContext) {
   servletContext.log("Cleaning up Stormpath config.");
   servletContext.removeAttribute(CONFIG_ATTRIBUTE_NAME);
 }
Ejemplo n.º 20
0
 public void destroy() {
   log.info("开始停止应用");
   application.removeAttribute("ctx");
   super.destroy();
 }
Ejemplo n.º 21
0
 @Override
 public void removeAttribute(String s) {
   proxy.removeAttribute(s);
 }
 @Override
 public void contextDestroyed(ServletContextEvent event) {
   context.removeAttribute("auditLog");
   System.out.println("application stopping...");
 }
Ejemplo n.º 23
0
  /**
   * This method bootstraps JSF based on the parsed configuration resources.
   *
   * @param sc the <code>ServletContext</code> for the application that requires initialization
   */
  public void initialize(ServletContext sc) {

    if (!hasBeenInitialized(sc)) {
      initializedContexts.add(sc);
      ExecutorService executor = null;
      try {
        WebConfiguration webConfig = WebConfiguration.getInstance(sc);
        boolean validating = webConfig.isOptionEnabled(ValidateFacesConfigFiles);
        if (useThreads(sc)) {
          executor = createExecutorService();
        }

        DocumentInfo[] facesDocuments =
            getConfigDocuments(sc, getFacesConfigResourceProviders(), executor, validating);

        FacesConfigInfo webInfFacesConfigInfo =
            new FacesConfigInfo(facesDocuments[facesDocuments.length - 1]);

        facesDocuments = sortDocuments(facesDocuments, webInfFacesConfigInfo);
        InitFacesContext context = (InitFacesContext) FacesContext.getCurrentInstance();

        InjectionProvider containerConnector =
            InjectionProviderFactory.createInstance(context.getExternalContext());
        context.getAttributes().put(INJECTION_PROVIDER_KEY, containerConnector);

        boolean isFaceletsDisabled = isFaceletsDisabled(webConfig, webInfFacesConfigInfo);
        if (!webInfFacesConfigInfo.isWebInfFacesConfig()
            || !webInfFacesConfigInfo.isMetadataComplete()) {
          // execute the Task responsible for finding annotation classes
          ProvideMetadataToAnnotationScanTask taskMetadata =
              new ProvideMetadataToAnnotationScanTask(facesDocuments, containerConnector);
          Future<Map<Class<? extends Annotation>, Set<Class<?>>>> annotationScan;
          if (executor != null) {
            annotationScan = executor.submit(new AnnotationScanTask(sc, context, taskMetadata));
            pushTaskToContext(sc, annotationScan);
          } else {
            annotationScan =
                new FutureTask<Map<Class<? extends Annotation>, Set<Class<?>>>>(
                    new AnnotationScanTask(sc, context, taskMetadata));
            ((FutureTask) annotationScan).run();
          }
          pushTaskToContext(sc, annotationScan);
        }

        // see if the app is running in a HA enabled env
        if (containerConnector instanceof HighAvailabilityEnabler) {
          ((HighAvailabilityEnabler) containerConnector).enableHighAvailability(sc);
        }
        // process the ordered documents
        FACES_CONFIG_PROCESSOR_CHAIN.process(sc, facesDocuments);
        if (!isFaceletsDisabled) {
          FACELET_TAGLIB_CONFIG_PROCESSOR_CHAIN.process(
              sc,
              getConfigDocuments(sc, getFaceletConfigResourceProviders(), executor, validating));
        }

        publishPostConfigEvent();
      } catch (Exception e) {
        // clear out any configured factories
        releaseFactories();
        Throwable t = e;
        if (!(e instanceof ConfigurationException)) {
          t = new ConfigurationException("CONFIGURATION FAILED! " + t.getMessage(), t);
        }
        throw (ConfigurationException) t;
      } finally {
        if (executor != null) {
          executor.shutdown();
        }
        sc.removeAttribute(ANNOTATIONS_SCAN_TASK_KEY);
      }
    }
  }
Ejemplo n.º 24
0
 public String removeApplicationBean2() {
   ServletContext request =
       (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
   request.removeAttribute("applicationBean");
   return null;
 }
Ejemplo n.º 25
0
 public String clearStatusMessage() {
   if (null != servletContext) {
     servletContext.removeAttribute("previousRequestStatus");
   }
   return null;
 }
  public void contextDestroyed(ServletContextEvent event) {
    ServletContext servletContext = event.getServletContext();

    servletContext.removeAttribute(SHARED_CONTEXT_KEY);
  }
Ejemplo n.º 27
0
  public void contextInitialized(ServletContextEvent sce) {
    ServletContext context = sce.getServletContext();

    Timer timer = Timer.getInstance();
    if (timer != null) {
      timer.startTiming();
    }

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.log(
          Level.FINE,
          MessageFormat.format(
              "ConfigureListener.contextInitialized({0})", getServletContextIdentifier(context)));
    }

    webConfig = WebConfiguration.getInstance(context);
    ConfigManager configManager = ConfigManager.getInstance();

    if (configManager.hasBeenInitialized(context)) {
      return;
    }

    // Check to see if the FacesServlet is present in the
    // web.xml.   If it is, perform faces configuration as normal,
    // otherwise, simply return.
    Object mappingsAdded = context.getAttribute(RIConstants.FACES_INITIALIZER_MAPPINGS_ADDED);
    if (mappingsAdded != null) {
      context.removeAttribute(RIConstants.FACES_INITIALIZER_MAPPINGS_ADDED);
    }

    WebXmlProcessor webXmlProcessor = new WebXmlProcessor(context);
    if (mappingsAdded == null) {
      if (!webXmlProcessor.isFacesServletPresent()) {
        if (!webConfig.isOptionEnabled(ForceLoadFacesConfigFiles)) {
          if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(
                Level.FINE,
                "No FacesServlet found in deployment descriptor - bypassing configuration");
          }
          WebConfiguration.clear(context);
          return;
        }
      } else {
        if (LOGGER.isLoggable(Level.FINE)) {
          LOGGER.log(
              Level.FINE,
              "FacesServlet found in deployment descriptor - processing configuration.");
        }
      }
    }

    // bootstrap of faces required
    webAppListener = new WebappLifecycleListener(context);
    webAppListener.contextInitialized(sce);
    InitFacesContext initContext = new InitFacesContext(context);
    ReflectionUtils.initCache(Thread.currentThread().getContextClassLoader());
    Throwable caughtThrowable = null;

    try {

      if (LOGGER.isLoggable(Level.INFO)) {
        LOGGER.log(Level.INFO, "jsf.config.listener.version", getServletContextIdentifier(context));
      }

      // see if we need to disable our TLValidator
      Util.setHtmlTLVActive(webConfig.isOptionEnabled(EnableHtmlTagLibraryValidator));

      if (webConfig.isOptionEnabled(VerifyFacesConfigObjects)) {
        if (LOGGER.isLoggable(Level.WARNING)) {
          LOGGER.warning("jsf.config.verifyobjects.development_only");
        }
        // if we're verifying, force bean validation to occur at startup as well
        webConfig.overrideContextInitParameter(EnableLazyBeanValidation, false);
        Verifier.setCurrentInstance(new Verifier());
      }
      initScripting();

      configManager.initialize(context);

      if (shouldInitConfigMonitoring()) {
        initConfigMonitoring(context);
      }

      // Step 7, verify that all the configured factories are available
      // and optionall that configured objects can be created.
      Verifier v = Verifier.getCurrentInstance();
      if (v != null && !v.isApplicationValid()) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
          LOGGER.severe("jsf.config.verifyobjects.failures_detected");
          StringBuilder sb = new StringBuilder(128);
          for (String m : v.getMessages()) {
            sb.append(m).append('\n');
          }
          LOGGER.severe(sb.toString());
        }
      }
      registerELResolverAndListenerWithJsp(context, false);
      ELContext elctx = new ELContextImpl(initContext.getApplication().getELResolver());
      elctx.putContext(FacesContext.class, initContext);
      initContext.setELContext(elctx);
      ApplicationAssociate associate = ApplicationAssociate.getInstance(context);
      if (associate != null) {
        associate.setContextName(getServletContextIdentifier(context));
        BeanManager manager = associate.getBeanManager();
        List<String> eagerBeans = manager.getEagerBeanNames();
        if (!eagerBeans.isEmpty()) {
          for (String name : eagerBeans) {
            manager.create(name, initContext);
          }
        }
        boolean isErrorPagePresent = webXmlProcessor.isErrorPagePresent();
        associate.setErrorPagePresent(isErrorPagePresent);
        context.setAttribute(RIConstants.ERROR_PAGE_PRESENT_KEY_NAME, isErrorPagePresent);
      }
      Application app = initContext.getApplication();
      app.subscribeToEvent(PostConstructViewMapEvent.class, UIViewRoot.class, webAppListener);
      app.subscribeToEvent(PreDestroyViewMapEvent.class, UIViewRoot.class, webAppListener);

      webConfig.doPostBringupActions();

    } catch (Throwable t) {
      if (LOGGER.isLoggable(Level.SEVERE)) {
        LOGGER.log(Level.SEVERE, "Critical error during deployment: ", t);
      }
      caughtThrowable = t;

    } finally {
      Verifier.setCurrentInstance(null);
      initContext.release();
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "jsf.config.listener.version.complete");
      }
      if (timer != null) {
        timer.stopTiming();
        timer.logResult("Initialization of context " + getServletContextIdentifier(context));
      }
      if (null != caughtThrowable) {
        throw new RuntimeException(caughtThrowable);
      }
    }
  }
Ejemplo n.º 28
0
 @Override
 public void contextDestroyed(ServletContextEvent sce) {
   ServletContext servletContext = sce.getServletContext();
   servletContext.removeAttribute(BOOK_STORAGE_NAME);
 }
Ejemplo n.º 29
0
  /**
   * This method will be invoked {@link WebConfigResourceMonitor} when changes to any of the
   * faces-config.xml files included in WEB-INF are modified.
   */
  private void reload(ServletContext sc) {

    if (LOGGER.isLoggable(Level.INFO)) {
      LOGGER.log(
          Level.INFO,
          "Reloading JSF configuration for context {0}",
          getServletContextIdentifier(sc));
    }
    GroovyHelper helper = GroovyHelper.getCurrentInstance();
    if (helper != null) {
      helper.setClassLoader();
    }
    // tear down the application
    try {
      // this will only be true in the automated test usage scenario
      if (null != webAppListener) {
        List<HttpSession> sessions = webAppListener.getActiveSessions();
        if (sessions != null) {
          for (HttpSession session : sessions) {
            if (LOGGER.isLoggable(Level.INFO)) {
              LOGGER.log(Level.INFO, "Invalidating Session {0}", session.getId());
            }
            session.invalidate();
          }
        }
      }
      ApplicationAssociate associate = ApplicationAssociate.getInstance(sc);
      if (associate != null) {
        BeanManager manager = associate.getBeanManager();
        for (Map.Entry<String, BeanBuilder> entry : manager.getRegisteredBeans().entrySet()) {
          String name = entry.getKey();
          BeanBuilder bean = entry.getValue();
          if (ELUtils.Scope.APPLICATION.toString().equals(bean.getScope())) {
            if (LOGGER.isLoggable(Level.INFO)) {
              LOGGER.log(Level.INFO, "Removing application scoped managed bean: {0}", name);
            }
            sc.removeAttribute(name);
          }
        }
      }
      // Release any allocated application resources
      FactoryFinder.releaseFactories();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      FacesContext initContext = new InitFacesContext(sc);
      ApplicationAssociate.clearInstance(initContext.getExternalContext());
      ApplicationAssociate.setCurrentInstance(null);
      // Release the initialization mark on this web application
      ConfigManager.getInstance().destory(sc);
      initContext.release();
      ReflectionUtils.clearCache(Thread.currentThread().getContextClassLoader());
      WebConfiguration.clear(sc);
    }

    // bring the application back up, avoid re-registration of certain JSP
    // artifacts.  No verification will be performed either to make this
    // light weight.

    // init a new WebAppLifecycleListener so that the cached ApplicationAssociate
    // is removed.
    webAppListener = new WebappLifecycleListener(sc);

    FacesContext initContext = new InitFacesContext(sc);
    ReflectionUtils.initCache(Thread.currentThread().getContextClassLoader());

    try {
      ConfigManager configManager = ConfigManager.getInstance();
      configManager.initialize(sc);

      registerELResolverAndListenerWithJsp(sc, true);
      ApplicationAssociate associate = ApplicationAssociate.getInstance(sc);
      if (associate != null) {
        Boolean errorPagePresent =
            (Boolean) sc.getAttribute(RIConstants.ERROR_PAGE_PRESENT_KEY_NAME);
        if (null != errorPagePresent) {
          associate.setErrorPagePresent(errorPagePresent);
          associate.setContextName(getServletContextIdentifier(sc));
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      initContext.release();
    }

    if (LOGGER.isLoggable(Level.INFO)) {
      LOGGER.log(Level.INFO, "Reload complete.", getServletContextIdentifier(sc));
    }
  }
Ejemplo n.º 30
0
  static void clear(ServletContext servletContext) {

    servletContext.removeAttribute(WEB_CONFIG_KEY);
  }