public ClasspathResourceHelper() {

    WebConfiguration webconfig = WebConfiguration.getInstance();
    cacheTimestamp = webconfig.isOptionEnabled(CacheResourceModificationTimestamp);
    enableMissingResourceLibraryDetection =
        webconfig.isOptionEnabled(EnableMissingResourceLibraryDetection);
  }
Ejemplo n.º 2
0
  public void registerELResolverAndListenerWithJsp(ServletContext context, boolean reloaded) {

    if (webConfig.isSet(WebContextInitParameter.ExpressionFactory) || !isJspTwoOne(context)) {

      // first try to load a factory defined in web.xml
      if (!installExpressionFactory(
          context, webConfig.getOptionValue(WebContextInitParameter.ExpressionFactory))) {

        throw new ConfigurationException(
            MessageUtils.getExceptionMessageString(
                MessageUtils.INCORRECT_JSP_VERSION_ID,
                WebContextInitParameter.ExpressionFactory.getDefaultValue(),
                WebContextInitParameter.ExpressionFactory.getQualifiedName()));
      }

    } else {

      // JSP 2.1 specific check
      if (JspFactory.getDefaultFactory().getJspApplicationContext(context) == null) {
        return;
      }

      // register an empty resolver for now. It will be populated after the
      // first request is serviced.
      FacesCompositeELResolver compositeELResolverForJsp =
          new ChainTypeCompositeELResolver(FacesCompositeELResolver.ELResolverChainType.JSP);
      ApplicationAssociate associate = ApplicationAssociate.getInstance(context);
      if (associate != null) {
        associate.setFacesELResolverForJsp(compositeELResolverForJsp);
      }

      // get JspApplicationContext.
      JspApplicationContext jspAppContext =
          JspFactory.getDefaultFactory().getJspApplicationContext(context);

      // cache the ExpressionFactory instance in ApplicationAssociate
      if (associate != null) {
        associate.setExpressionFactory(jspAppContext.getExpressionFactory());
      }

      // register compositeELResolver with JSP
      try {
        jspAppContext.addELResolver(compositeELResolverForJsp);
      } catch (IllegalStateException e) {
        ApplicationFactory factory =
            (ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY);
        Application app = factory.getApplication();
        if (app.getProjectStage() != ProjectStage.UnitTest && !reloaded) {
          throw e;
        }
      }

      // register JSF ELContextListenerImpl with Jsp
      ELContextListenerImpl elContextListener = new ELContextListenerImpl();
      jspAppContext.addELContextListener(elContextListener);
    }
  }
Ejemplo n.º 3
0
  public ResponseStateManagerImpl() {

    WebConfiguration webConfig = WebConfiguration.getInstance();
    String stateMode = webConfig.getOptionValue(StateSavingMethod);
    helper =
        ((StateManager.STATE_SAVING_METHOD_CLIENT.equalsIgnoreCase(stateMode)
            ? new ClientSideStateHelper()
            : new ServerSideStateHelper()));
  }
Ejemplo n.º 4
0
  public MultiViewHandler() {

    WebConfiguration config = WebConfiguration.getInstance();
    String defaultSuffixConfig =
        config.getOptionValue(WebConfiguration.WebContextInitParameter.DefaultSuffix);
    configuredExtensions = Util.split(defaultSuffixConfig, " ");
    pdlFactory =
        (PageDeclarationLanguageFactory)
            FactoryFinder.getFactory(FactoryFinder.PAGE_DECLARATION_LANGUAGE_FACTORY);
  }
Ejemplo n.º 5
0
  private boolean shouldInitConfigMonitoring() {

    boolean development = isDevModeEnabled();
    boolean threadingOptionSpecified = webConfig.isSet(EnableThreading);
    if (development && !threadingOptionSpecified) {
      return true;
    }
    boolean threadingOption = webConfig.isOptionEnabled(EnableThreading);
    return (development && threadingOptionSpecified && threadingOption);
  }
Ejemplo n.º 6
0
  public MultiViewHandler() {

    WebConfiguration config = WebConfiguration.getInstance();

    configuredExtensions =
        config.getOptionValue(WebConfiguration.WebContextInitParameter.DefaultSuffix, " ");
    extensionsSet = config.isSet(WebConfiguration.WebContextInitParameter.DefaultSuffix);
    vdlFactory =
        (ViewDeclarationLanguageFactory)
            FactoryFinder.getFactory(FactoryFinder.VIEW_DECLARATION_LANGUAGE_FACTORY);
  }
Ejemplo n.º 7
0
  /**
   * Utility method to check if JSF 2.0 Facelets should be disabled. If it's not explicitly disabled
   * by the context init parameter, then check the version of the WEB-INF/faces-config.xml document.
   * If the version is less than 2.0, then override the default value for the context init parameter
   * so that other parts of the system that use that config option will know it has been disabled.
   *
   * <p>NOTE: Since this method overrides a configuration value, it should be called before *any*
   * document parsing is performed the configuration value may be queried by the <code>ConfigParser
   * </code>s.
   *
   * @param webconfig configuration for this application
   * @param facesConfigInfo object representing WEB-INF/faces-config.xml
   * @return <code>true</code> if Facelets should be disabled
   */
  private boolean isFaceletsDisabled(WebConfiguration webconfig, FacesConfigInfo facesConfigInfo) {

    boolean isFaceletsDisabled = webconfig.isOptionEnabled(DisableFaceletJSFViewHandler);
    if (!isFaceletsDisabled) {
      // if not explicitly disabled, make a sanity check against
      // /WEB-INF/faces-config.xml
      isFaceletsDisabled = !facesConfigInfo.isVersionGreaterOrEqual(2.0);
      webconfig.overrideContextInitParameter(DisableFaceletJSFViewHandler, isFaceletsDisabled);
    }
    return isFaceletsDisabled;
  }
  /**
   * Tries to find a provider class in a web context parameter. If not present it tries to find it
   * as a System property. If still not found returns null.
   *
   * @param extContext The ExternalContext for this request
   * @return The provider class name specified in the container configuration, or <code>null</code>
   *     if not found.
   */
  private static String findProviderClass(ExternalContext extContext) {

    WebConfiguration webConfig = WebConfiguration.getInstance(extContext);

    String provider = webConfig.getOptionValue(WebContextInitParameter.SerializationProviderClass);

    if (provider != null) {
      return provider;
    } else {
      return System.getProperty(SERIALIZATION_PROVIDER_PROPERTY);
    }
  }
Ejemplo n.º 9
0
  /** Construct a new <code>ServerSideStateHelper</code> instance. */
  public ServerSideStateHelper() {

    numberOfLogicalViews = getIntegerConfigValue(NumberOfLogicalViews);
    numberOfViews = getIntegerConfigValue(NumberOfViews);
    WebConfiguration webConfig = WebConfiguration.getInstance();
    generateUniqueStateIds = webConfig.isOptionEnabled(GenerateUniqueServerStateIds);
    if (generateUniqueStateIds) {
      random = new Random(System.nanoTime() + webConfig.getServletContext().hashCode());
    } else {
      random = null;
    }
    namespaceParameters = webConfig.isOptionEnabled(NamespaceParameters);
  }
Ejemplo n.º 10
0
  protected FaceletFactory createFaceletFactory(Compiler c, WebConfiguration webConfig) {

    // refresh period
    String refreshPeriod = webConfig.getOptionValue(FaceletsDefaultRefreshPeriod);
    long period = Long.parseLong(refreshPeriod);

    // resource resolver
    ResourceResolver resolver = new DefaultResourceResolver();
    String resolverName = webConfig.getOptionValue(FaceletsResourceResolver);
    if (resolverName != null && resolverName.length() > 0) {
      resolver =
          (ResourceResolver)
              ReflectionUtil.decorateInstance(resolverName, ResourceResolver.class, resolver);
    }

    FaceletCache cache = null;
    String faceletCacheName = webConfig.getOptionValue(FaceletCache);
    if (faceletCacheName != null && faceletCacheName.length() > 0) {
      try {
        com.sun.faces.facelets.FaceletCache privateApiCache =
            (com.sun.faces.facelets.FaceletCache)
                ReflectionUtil.forName(faceletCacheName).newInstance();
        cache = new PrivateApiFaceletCacheAdapter(privateApiCache);
      } catch (Exception e) {
        if (LOGGER.isLoggable(Level.SEVERE)) {
          LOGGER.log(Level.SEVERE, "Error Loading Facelet cache: " + faceletCacheName, e);
        }
      }
    }
    if (null == cache) {
      FaceletCacheFactory cacheFactory =
          (FaceletCacheFactory) FactoryFinder.getFactory(FactoryFinder.FACELET_CACHE_FACTORY);
      cache = cacheFactory.getFaceletCache();
    }

    // Resource.getResourceUrl(ctx,"/")
    FaceletFactory factory = new DefaultFaceletFactory(c, resolver, period, cache);

    // Check to see if a custom Factory has been defined
    String factoryClass = webConfig.getOptionValue(FaceletFactory);
    if (factoryClass != null && factoryClass.length() > 0) {
      factory =
          (FaceletFactory)
              ReflectionUtil.decorateInstance(factoryClass, FaceletFactory.class, factory);
    }

    return factory;
  }
Ejemplo n.º 11
0
  public CompilationManager(String alias, Compiler compiler) {

    // this is our alias
    this.alias = alias;

    // grab compiler state
    this.compiler = compiler;
    this.tagDecorator = compiler.createTagDecorator();
    this.tagLibrary = compiler.createTagLibrary(this.getCompilationMessageHolder());

    // namespace management
    this.namespaceManager = new NamespaceManager();

    // tag uids
    this.tagId = 0;

    // for composition use
    this.finished = false;

    // our compilationunit stack
    this.units = new Stack<CompilationUnit>();
    this.units.push(new CompilationUnit());

    config = WebConfiguration.getInstance();
  }
Ejemplo n.º 12
0
  private WebConfiguration getWebConfig(FacesContext context) {

    if (webConfig == null) {
      webConfig = WebConfiguration.getInstance(context.getExternalContext());
    }
    return webConfig;
  }
Ejemplo n.º 13
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.º 14
0
 private void initScripting() {
   if (webConfig.isOptionEnabled(EnableGroovyScripting)) {
     GroovyHelper helper = GroovyHelperFactory.createHelper();
     if (helper != null) {
       helper.setClassLoader();
     }
   }
 }
Ejemplo n.º 15
0
  public ApplicationAssociate(ApplicationImpl appImpl) {
    app = appImpl;

    propertyEditorHelper = new PropertyEditorHelper(appImpl);

    FacesContext ctx = FacesContext.getCurrentInstance();
    if (ctx == null) {
      throw new IllegalStateException(
          MessageUtils.getExceptionMessageString(
              MessageUtils.APPLICATION_ASSOCIATE_CTOR_WRONG_CALLSTACK_ID));
    }
    ExternalContext externalContext = ctx.getExternalContext();
    if (null != externalContext.getApplicationMap().get(ASSOCIATE_KEY)) {
      throw new IllegalStateException(
          MessageUtils.getExceptionMessageString(MessageUtils.APPLICATION_ASSOCIATE_EXISTS_ID));
    }
    externalContext.getApplicationMap().put(ASSOCIATE_KEY, this);
    //noinspection CollectionWithoutInitialCapacity
    navigationMap = new ConcurrentHashMap<String, Set<NavigationCase>>();
    injectionProvider = InjectionProviderFactory.createInstance(externalContext);
    WebConfiguration webConfig = WebConfiguration.getInstance(externalContext);
    beanManager =
        new BeanManager(injectionProvider, webConfig.isOptionEnabled(EnableLazyBeanValidation));
    // install the bean manager as a system event listener for custom
    // scopes being destoryed.
    app.subscribeToEvent(PreDestroyCustomScopeEvent.class, ScopeContext.class, beanManager);
    annotationManager = new AnnotationManager();

    groovyHelper = GroovyHelper.getCurrentInstance();

    devModeEnabled = (appImpl.getProjectStage() == ProjectStage.Development);
    // initialize Facelets
    if (!webConfig.isOptionEnabled(DisableFaceletJSFViewHandler)) {
      compiler = createCompiler(webConfig);
      faceletFactory = createFaceletFactory(compiler, webConfig);
    }

    if (!devModeEnabled) {
      resourceCache = new ResourceCache();
    }

    resourceManager = new ResourceManager(resourceCache);
    namedEventManager = new NamedEventManager();
    applicationStateInfo = new ApplicationStateInfo();
  }
Ejemplo n.º 16
0
  protected Compiler createCompiler(WebConfiguration webConfig) {

    Compiler c = new SAXCompiler();

    // load decorators
    String decParam = webConfig.getOptionValue(FaceletsDecorators);
    if (decParam != null) {
      decParam = decParam.trim();
      String[] decs = Util.split(decParam, ";");
      TagDecorator decObj;
      for (String decorator : decs) {
        try {
          decObj = (TagDecorator) ReflectionUtil.forName(decorator).newInstance();
          c.addTagDecorator(decObj);

          if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "Successfully Loaded Decorator: {0}", decorator);
          }
        } catch (Exception e) {
          if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, "Error Loading Decorator: " + decorator, e);
          }
        }
      }
    }

    // skip params?
    c.setTrimmingComments(
        webConfig.isOptionEnabled(BooleanWebContextInitParameter.FaceletsSkipComments));

    c.addTagLibrary(new CoreLibrary());
    c.addTagLibrary(new HtmlLibrary());
    c.addTagLibrary(new UILibrary());
    c.addTagLibrary(new JstlCoreLibrary());
    c.addTagLibrary(
        new FunctionLibrary(JstlFunction.class, "http://java.sun.com/jsp/jstl/functions"));
    if (isDevModeEnabled()) {
      c.addTagLibrary(
          new FunctionLibrary(DevTools.class, "http://java.sun.com/mojarra/private/functions"));
    }
    c.addTagLibrary(new CompositeLibrary());
    c.addTagLibrary(new XmlLibrary());

    return c;
  }
Ejemplo n.º 17
0
  public void testClientResourceInfoCompression() throws Exception {
    WebConfiguration config = WebConfiguration.getInstance();
    config.overrideContextInitParameter(
        WebConfiguration.WebContextInitParameter.CompressableMimeTypes,
        "image/gif,text/css,text/plain");
    // create a new ResourceManager so that the mime type configuration is picked up
    ResourceManager manager = new ResourceManager(null);
    ClientResourceInfo resource =
        (ClientResourceInfo)
            manager.findResource("nvLibrary", "duke-nv.gif", "image/gif", getFacesContext());
    assertTrue(resource != null);
    assertTrue(resource.isCompressable());
    assertTrue(compressionPathIsValid(resource));

    // ensure compression disabled for a content type that is null
    resource =
        (ClientResourceInfo)
            manager.findResource("nvLibrary", "duke-nv.gif", "text/javascript", getFacesContext());
    assertTrue(resource != null);
    assertTrue(!resource.isCompressable());
    assertTrue(resource.getCompressedPath() == null);

    // if a resource is compressable, but the compressed result is larger
    // than the original resource, the returned ClientResourceInfo shouldn't
    // be marked as compressable and getCompressedPath() will be null
    resource =
        (ClientResourceInfo)
            manager.findResource(null, "simple.txt", "text/plain", getFacesContext());
    assertTrue(resource != null);
    assertTrue(!resource.isCompressable());
    assertTrue(resource.getCompressedPath() == null);

    // if a resource is compressable, but the compressed result is larger
    // than the original resource, the returned ClientResourceInfo should be
    // marked compressable.  However, since css files may have EL expressions
    // embedded within, the the resource will be marked as supporting such.
    resource =
        (ClientResourceInfo)
            manager.findResource(null, "simple.css", "text/plain", getFacesContext());
    assertTrue(resource != null);
    assertTrue(resource.isCompressable());
    assertTrue(resource.supportsEL());
    assertTrue(resource.getCompressedPath() == null);
  }
Ejemplo n.º 18
0
  /**
   * Renders the Javascript necessary to add and remove request parameters to the current form.
   *
   * @param writer the <code>ResponseWriter</code>
   * @param context the <code>FacesContext</code> for the current request
   * @throws java.io.IOException if an error occurs writing to the response
   */
  public static void renderFormInitScript(ResponseWriter writer, FacesContext context)
      throws IOException {
    WebConfiguration webConfig = WebConfiguration.getInstance(context.getExternalContext());

    if (webConfig.isOptionEnabled(BooleanWebContextInitParameter.ExternalizeJavaScript)) {
      // PENDING
      // We need to look into how to make this work in a portlet environment.
      // For the time being, this feature will need to be disabled when running
      // in a portlet.
      /*
      String mapping = Util.getFacesMapping(context);
      String uri;
      if ((mapping != null) && (Util.isPrefixMapped(mapping))) {
          uri = mapping + '/' + RIConstants.SUN_JSF_JS_URI;
      } else {
          uri = '/' + RIConstants.SUN_JSF_JS_URI + mapping;
      }
      writer.write('\n');
      writer.startElement("script", null);
      writer.writeAttribute("type", "text/javascript", null);
      writer.writeAttribute("src",
                            context.getExternalContext()
                                  .getRequestContextPath() + uri,
                            null);
      writer.endElement("script");
      writer.write("\n");
      */
      ResourceHandler handler = context.getApplication().getResourceHandler();
      Resource resource = handler.createResource("scripts/sunjsf.js", "jsfri");
      writer.write('\n');
      writer.startElement("script", null);
      writer.writeAttribute("type", "text/javascript", null);
      writer.writeAttribute("src", ((resource != null) ? resource.getRequestPath() : ""), null);
      writer.endElement("script");
    } else {
      writer.write('\n');
      writer.startElement("script", null);
      writer.writeAttribute("type", "text/javascript", null);
      writer.writeAttribute("language", "Javascript", null);
      writeSunJS(context, writer);
      writer.endElement("script");
      writer.write("\n");
    }
  }
Ejemplo n.º 19
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);
    }
  }
Ejemplo n.º 20
0
  public ApplicationAssociate(ApplicationImpl appImpl) {
    app = appImpl;

    propertyEditorHelper = new PropertyEditorHelper(appImpl);

    FacesContext ctx = FacesContext.getCurrentInstance();
    if (ctx == null) {
      throw new IllegalStateException(
          MessageUtils.getExceptionMessageString(
              MessageUtils.APPLICATION_ASSOCIATE_CTOR_WRONG_CALLSTACK_ID));
    }
    ExternalContext externalContext = ctx.getExternalContext();
    if (null != externalContext.getApplicationMap().get(ASSOCIATE_KEY)) {
      throw new IllegalStateException(
          MessageUtils.getExceptionMessageString(MessageUtils.APPLICATION_ASSOCIATE_EXISTS_ID));
    }
    externalContext.getApplicationMap().put(ASSOCIATE_KEY, this);
    //noinspection CollectionWithoutInitialCapacity
    caseListMap = new HashMap<String, List<ConfigNavigationCase>>();
    wildcardMatchList = new TreeSet<String>(new SortIt());
    injectionProvider = InjectionProviderFactory.createInstance(externalContext);
    WebConfiguration webConfig = WebConfiguration.getInstance(externalContext);
    beanManager =
        new BeanManager(
            injectionProvider,
            webConfig.isOptionEnabled(BooleanWebContextInitParameter.EnableLazyBeanValidation));
    annotationManager = new AnnotationManager();

    groovyHelper = GroovyHelper.getCurrentInstance();

    // initialize Facelets
    if (!webConfig.isOptionEnabled(BooleanWebContextInitParameter.DisableFaceletJSFViewHandler)) {
      compiler = createCompiler(webConfig);
      faceletFactory = createFaceletFactory(compiler, webConfig);
      devModeEnabled = (appImpl.getProjectStage() == ProjectStage.Development);
    }

    if (devModeEnabled) {
      resourceCache = new ResourceCache();
    }
    resourceManager = new ResourceManager(resourceCache);
  }
Ejemplo n.º 21
0
  protected Compiler createCompiler(WebConfiguration webConfig) {

    Compiler c = new SAXCompiler();

    // load decorators
    String decParam =
        webConfig.getOptionValue(WebConfiguration.WebContextInitParameter.FaceletsDecorators);
    if (decParam != null) {
      decParam = decParam.trim();
      String[] decs = Util.split(decParam, ";");
      TagDecorator decObj;
      for (int i = 0; i < decs.length; i++) {
        try {
          decObj = (TagDecorator) ReflectionUtil.forName(decs[i]).newInstance();
          c.addTagDecorator(decObj);

          if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.log(Level.FINE, "Successfully Loaded Decorator: {0}", decs[i]);
          }
        } catch (Exception e) {
          if (LOGGER.isLoggable(Level.SEVERE)) {
            LOGGER.log(Level.SEVERE, "Error Loading Decorator: " + decs[i], e);
          }
        }
      }
    }

    // skip params?
    c.setTrimmingComments(
        webConfig.isOptionEnabled(BooleanWebContextInitParameter.FaceletsSkipComments));

    c.addTagLibrary(new CoreLibrary());
    c.addTagLibrary(new HtmlLibrary());
    c.addTagLibrary(new UILibrary());
    c.addTagLibrary(new JstlCoreLibrary());
    c.addTagLibrary(new JstlFnLibrary());
    c.addTagLibrary(new CompositeLibrary());

    return c;
  }
Ejemplo n.º 22
0
  public ExternalContextImpl(ServletContext sc, ServletRequest request, ServletResponse response) {

    // Validate the incoming parameters
    try {
      Util.notNull("sc", sc);
      Util.notNull("request", request);
      Util.notNull("response", response);
    } catch (Exception e) {
      throw new FacesException(
          MessageUtils.getExceptionMessageString(
              MessageUtils.FACES_CONTEXT_CONSTRUCTION_ERROR_MESSAGE_ID));
    }

    // Save references to our context, request, and response
    this.servletContext = sc;
    this.request = request;
    this.response = response;
    WebConfiguration config = WebConfiguration.getInstance(sc);
    if (config.isOptionEnabled(BooleanWebContextInitParameter.SendPoweredByHeader)) {
      ((HttpServletResponse) response).addHeader("X-Powered-By", "JSF/2.0");
    }
  }
Ejemplo n.º 23
0
  /**
   * Loads the contents of the sunjsf.js file into memory removing any comments/empty lines it
   * encoutners, and, if enabled, compressing the result. This method should only be called when the
   * application is being initialized.
   *
   * @param extContext the ExternalContext for this application
   */
  public static synchronized void loadSunJsfJs(ExternalContext extContext) {
    Map<String, Object> appMap = extContext.getApplicationMap();
    char[] sunJsfJs;

    BufferedReader reader = null;
    try {
      // Don't use Util.getCurrentLoader().  This JS resource should
      // be available from the same classloader that loaded RenderKitUtils.
      // Doing so allows us to be more OSGi friendly.
      URL url = RenderKitUtils.class.getClassLoader().getResource("com/sun/faces/sunjsf.js");
      if (url == null) {
        LOGGER.severe("jsf.renderkit.util.cannot_load_js");
        return;
      }
      URLConnection conn = url.openConnection();
      conn.setUseCaches(false);
      InputStream input = conn.getInputStream();
      reader = new BufferedReader(new InputStreamReader(input));
      StringBuilder builder = new StringBuilder(128);
      for (String line = reader.readLine(); line != null; line = reader.readLine()) {

        String temp = line.trim();
        if (temp.length() == 0
            || temp.startsWith("/*")
            || temp.startsWith("*")
            || temp.startsWith("*/")
            || temp.startsWith("//")) {
          continue;
        }
        builder.append(line).append('\n');
      }
      builder.deleteCharAt(builder.length() - 1);
      if (WebConfiguration.getInstance(extContext)
          .isOptionEnabled(BooleanWebContextInitParameter.CompressJavaScript)) {
        sunJsfJs = compressJS(builder.toString());
      } else {
        sunJsfJs = builder.toString().toCharArray();
      }
      appMap.put(SUN_JSF_JS, sunJsfJs);
    } catch (IOException ioe) {
      LOGGER.log(Level.SEVERE, "jsf.renderkit.util.cannot_load_js", ioe);
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException ioe) {
          // ignore
        }
      }
    }
  }
Ejemplo n.º 24
0
  protected FaceletFactory createFaceletFactory(Compiler c, WebConfiguration webConfig) {

    // refresh period
    String refreshPeriod =
        webConfig.getOptionValue(
            WebConfiguration.WebContextInitParameter.FaceletsDefaultRefreshPeriod);
    long period = Long.parseLong(refreshPeriod);

    // resource resolver
    ResourceResolver resolver = new DefaultResourceResolver();
    String resolverName =
        webConfig.getOptionValue(WebConfiguration.WebContextInitParameter.FaceletsResourceResolver);
    if (resolverName != null && resolverName.length() > 0) {
      try {
        resolver = (ResourceResolver) ReflectionUtil.forName(resolverName).newInstance();
      } catch (Exception e) {
        throw new FacesException("Error Initializing ResourceResolver[" + resolverName + "]", e);
      }
    }

    // Resource.getResourceUrl(ctx,"/")
    return new DefaultFaceletFactory(c, resolver, period);
  }
Ejemplo n.º 25
0
  /** Initialize the core Facelets runtime. */
  protected void initialize() {

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Initializing FaceletViewHandlingStrategy");
    }

    this.initializeMappings();
    WebConfiguration config = WebConfiguration.getInstance();
    partialStateSaving = config.isOptionEnabled(PartialStateSaving);

    if (partialStateSaving) {
      String[] viewIds = config.getOptionValue(FullStateSavingViewIds, ",");
      fullStateViewIds = new HashSet<String>(viewIds.length, 1.0f);
      fullStateViewIds.addAll(Arrays.asList(viewIds));
      this.stateManagementStrategy = new StateManagementStrategyImpl(this);
    }

    groovyAvailable = GroovyHelper.isGroovyAvailable(FacesContext.getCurrentInstance());

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Initialization Successful");
    }
  }
Ejemplo n.º 26
0
  private WebConfiguration getWebConfiguration(WebConfiguration webConfig) {
    if (webConfig != null) {
      return webConfig;
    }

    FacesContext context = FacesContext.getCurrentInstance();
    if (null != context) {
      ExternalContext extContext = context.getExternalContext();
      if (null != extContext) {
        webConfig = WebConfiguration.getInstance(extContext);
      }
    }
    return webConfig;
  }
Ejemplo n.º 27
0
  @Override
  public void encodeChildren(FacesContext context, UIComponent component) throws IOException {

    boolean renderChildren =
        WebConfiguration.getInstance()
            .isOptionEnabled(WebConfiguration.BooleanWebContextInitParameter.AllowTextChildren);

    if (!renderChildren) {
      return;
    }

    rendererParamsNotNull(context, component);

    if (!shouldEncodeChildren(component)) {
      return;
    }

    if (component.getChildCount() > 0) {
      for (UIComponent kid : component.getChildren()) {
        encodeRecursive(context, kid);
      }
    }
  }
Ejemplo n.º 28
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.º 29
0
  private boolean isDevModeEnabled() {

    // interrogate the init parameter directly vs looking up the application
    return "Development".equals(webConfig.getOptionValue(JavaxFacesProjectStage));
  }
Ejemplo n.º 30
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);
      }
    }
  }