Пример #1
0
  public void contextDestroyed(ServletContextEvent sce) {
    ServletContext context = sce.getServletContext();
    InitFacesContext initContext = null;
    try {
      initContext = new InitFacesContext(context);

      if (webAppListener != null) {
        webAppListener.contextDestroyed(sce);
        webAppListener = null;
      }
      if (webResourcePool != null) {
        webResourcePool.shutdownNow();
      }
      if (!ConfigManager.getInstance().hasBeenInitialized(context)) {
        return;
      }
      GroovyHelper helper = GroovyHelper.getCurrentInstance(context);
      if (helper != null) {
        helper.setClassLoader();
      }
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(
            Level.FINE, "ConfigureListener.contextDestroyed({0})", context.getServletContextName());
      }

      ELContext elctx = new ELContextImpl(initContext.getApplication().getELResolver());
      elctx.putContext(FacesContext.class, initContext);
      initContext.setELContext(elctx);
      Application app = initContext.getApplication();
      app.publishEvent(initContext, PreDestroyApplicationEvent.class, Application.class, app);

      Util.setNonFacesContextApplicationMap(null);

    } catch (Exception e) {
      if (LOGGER.isLoggable(Level.SEVERE)) {
        LOGGER.log(
            Level.SEVERE,
            "Unexpected exception when attempting to tear down the Mojarra runtime",
            e);
      }
    } finally {
      ApplicationAssociate.clearInstance(initContext.getExternalContext());
      ApplicationAssociate.setCurrentInstance(null);
      com.sun.faces.application.ApplicationImpl.clearInstance(initContext.getExternalContext());
      com.sun.faces.application.InjectionApplicationFactory.clearInstance(
          initContext.getExternalContext());
      // Release the initialization mark on this web application
      ConfigManager.getInstance().destory(context);
      if (initContext != null) {
        initContext.release();
      }
      ReflectionUtils.clearCache(Thread.currentThread().getContextClassLoader());
      WebConfiguration.clear(context);
    }
  }
  protected Class<?> findRootType(String source, Node sourceNode, Class<?>[] ctorArguments) {

    try {
      Class<?> sourceClass = loadClass(source, this, null);
      for (Class<?> ctorArg : ctorArguments) {
        if (ReflectionUtils.lookupConstructor(sourceClass, ctorArg) != null) {
          return ctorArg;
        }
      }
    } catch (ClassNotFoundException cnfe) {
      throw new ConfigurationException(
          buildMessage(MessageFormat.format("Unable to find class ''{0}''", source), sourceNode),
          cnfe);
    }

    return null;
  }
Пример #3
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));
    }
  }
Пример #4
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);
      }
    }
  }
Пример #5
0
  protected UIComponent createVerbatimComponentFromBodyContent() {

    UIOutput verbatim = (UIOutput) super.createVerbatimComponentFromBodyContent();
    String value = null;

    FacesContext ctx = getFacesContext();
    Object response = ctx.getExternalContext().getResponse();
    // flush out any content above the view tag
    Method customFlush =
        ReflectionUtils.lookupMethod(
            response.getClass(), "flushContentToWrappedResponse", RIConstants.EMPTY_CLASS_ARGS);
    Method isBytes =
        ReflectionUtils.lookupMethod(response.getClass(), "isBytes", RIConstants.EMPTY_CLASS_ARGS);
    Method isChars =
        ReflectionUtils.lookupMethod(response.getClass(), "isChars", RIConstants.EMPTY_CLASS_ARGS);
    Method resetBuffers =
        ReflectionUtils.lookupMethod(
            response.getClass(), "resetBuffers", RIConstants.EMPTY_CLASS_ARGS);
    Method getChars =
        ReflectionUtils.lookupMethod(response.getClass(), "getChars", RIConstants.EMPTY_CLASS_ARGS);
    boolean cont = true;
    if (isBytes == null) {
      cont = false;
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, "jsf.core.taglib.subviewtag.interweaving_failed_isbytes");
      }
    }
    if (isChars == null) {
      cont = false;
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, "jsf.core.taglib.subviewtag.interweaving_failed_ischars");
      }
    }
    if (resetBuffers == null) {
      cont = false;
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, "jsf.core.taglib.subviewtag.interweaving_failed_resetbuffers");
      }
    }
    if (getChars == null) {
      cont = false;
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, "jsf.core.taglib.subviewtag.interweaving_failed_getchars");
      }
    }
    if (customFlush == null) {
      cont = false;
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.log(Level.WARNING, "jsf.core.taglib.viewtag.interweaving_failed");
      }
    }

    if (cont) {
      try {
        if ((Boolean) isBytes.invoke(response)) {
          customFlush.invoke(response);
        } else if ((Boolean) isChars.invoke(response)) {
          char[] chars = (char[]) getChars.invoke(response);
          if (null != chars && 0 < chars.length) {
            if (null != verbatim) {
              value = (String) verbatim.getValue();
            }
            verbatim = super.createVerbatimComponent();
            if (null != value) {
              verbatim.setValue(value + new String(chars));
            } else {
              verbatim.setValue(new String(chars));
            }
          }
        }
        resetBuffers.invoke(response);

      } catch (Exception e) {
        throw new FacesException("Response interweaving failed!", e);
      }
    }

    return verbatim;
  }
  protected Object createInstance(String className, Class rootType, Object root, Node source) {
    Class clazz;
    Object returnObject = null;
    if (className != null) {
      try {
        clazz = loadClass(className, returnObject, null);
        if (clazz != null) {
          if (isDevModeEnabled()) {
            Class<?>[] interfaces = clazz.getInterfaces();
            if (interfaces != null) {
              for (Class<?> c : interfaces) {
                if ("groovy.lang.GroovyObject".equals(c.getName())) {
                  // all groovy classes will implement this interface
                  returnObject = createScriptProxy(rootType, className, root);
                  break;
                }
              }
            }
          }
          if (returnObject == null) {
            // Look for an adapter constructor if we've got
            // an object to adapt
            if ((rootType != null) && (root != null)) {
              Constructor construct = ReflectionUtils.lookupConstructor(clazz, rootType);
              if (construct != null) {
                returnObject = construct.newInstance(root);
              }
            }
          }
          if (clazz != null && returnObject == null) {
            returnObject = clazz.newInstance();
          }
        }

      } catch (ClassNotFoundException cnfe) {
        throw new ConfigurationException(
            buildMessage(MessageFormat.format("Unable to find class ''{0}''", className), source),
            cnfe);
      } catch (NoClassDefFoundError ncdfe) {
        throw new ConfigurationException(
            buildMessage(
                MessageFormat.format(
                    "Class ''{0}'' is missing a runtime dependency: {1}",
                    className, ncdfe.toString()),
                source),
            ncdfe);
      } catch (ClassCastException cce) {
        throw new ConfigurationException(
            buildMessage(
                MessageFormat.format(
                    "Class ''{0}'' is not an instance of ''{1}''", className, rootType),
                source),
            cce);
      } catch (Exception e) {
        throw new ConfigurationException(
            buildMessage(
                MessageFormat.format(
                    "Unable to create a new instance of ''{0}'': {1}", className, e.toString()),
                source),
            e);
      }
    }

    return returnObject;
  }