Exemple #1
0
  public void setValue(ELContext context, Object base, Object property, Object val)
      throws ELException {
    if (base != null) {
      return;
    }
    if (property == null) {
      String message =
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "property");
      throw new PropertyNotFoundException(message);
    }

    Integer index = IMPLICIT_OBJECTS.get(property.toString());
    if (index == null) {
      return;
    }
    switch (index) {
      case FACES_CONTEXT:
        throw new PropertyNotWritableException(
            MessageUtils.getExceptionMessageString(
                MessageUtils.OBJECT_IS_READONLY, "facesContext"));
      case VIEW:
        throw new PropertyNotWritableException(
            MessageUtils.getExceptionMessageString(MessageUtils.OBJECT_IS_READONLY, "view"));
      default:
    }
  }
  private Class<?> loadBeanClass() {
    if (beanClass == null) {
      String className = beanInfo.getClassName();
      Class<?> clazz = loadClass(className);
      ApplicationAssociate associate = ApplicationAssociate.getCurrentInstance();

      if (!associate.isDevModeEnabled()) {
        beanClass = clazz;
      }

      // validate the bean class is public and has a public
      // no-arg ctor
      int classModifiers = clazz.getModifiers();
      if (!Modifier.isPublic(classModifiers)) {
        String message =
            MessageUtils.getExceptionMessageString(
                MessageUtils.MANAGED_BEAN_CLASS_IS_NOT_PUBLIC_ERROR_ID,
                className,
                beanInfo.getName());
        queueMessage(message);
      }
      if (Modifier.isInterface(classModifiers) || Modifier.isAbstract(classModifiers)) {
        String message =
            MessageUtils.getExceptionMessageString(
                MessageUtils.MANAGED_BEAN_CLASS_IS_ABSTRACT_ERROR_ID,
                className,
                beanInfo.getName());
        queueMessage(message);
      }

      try {
        Constructor ctor = clazz.getConstructor(RIConstants.EMPTY_CLASS_ARGS);
        if (!Modifier.isPublic(ctor.getModifiers())) {
          String message =
              MessageUtils.getExceptionMessageString(
                  MessageUtils.MANAGED_BEAN_CLASS_NO_PUBLIC_NOARG_CTOR_ERROR_ID,
                  className,
                  beanInfo.getName());
          queueMessage(message);
        }
      } catch (NoSuchMethodException nsme) {
        String message =
            MessageUtils.getExceptionMessageString(
                MessageUtils.MANAGED_BEAN_CLASS_NO_PUBLIC_NOARG_CTOR_ERROR_ID,
                className,
                beanInfo.getName());
        queueMessage(message);
      }

      if (!hasMessages()) {
        // class is ok, scan for annotations
        this.isInjectible = scanForAnnotations(clazz);
      }
      return clazz;
    }
    return beanClass;
  }
Exemple #3
0
  /**
   * Write properly escaped text from a character array. If there is an open element that has been
   * created by a call to <code>startElement()</code>, that element will be closed first.
   *
   * <p>
   *
   * <p>All angle bracket occurrences in the argument must be escaped using the &amp;gt; &amp;lt;
   * syntax.
   *
   * @param text Text to be written
   * @param off Starting offset (zero-relative)
   * @param len Number of characters to be written
   * @throws IndexOutOfBoundsException if the calculated starting or ending position is outside the
   *     bounds of the character array
   * @throws IOException if an input/output error occurs
   * @throws NullPointerException if <code>text</code> is <code>null</code>
   */
  public void writeText(char text[], int off, int len) throws IOException {

    if (text == null) {
      throw new NullPointerException(
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "text"));
    }
    if (off < 0 || off > text.length || len < 0 || len > text.length) {
      throw new IndexOutOfBoundsException();
    }
    closeStartIfNecessary();
    if (writingCdata) {

      // RELEASE_PENDING
      // Might take a page from the HtmlUtils book and if the content being written
      // is more than 16 chars, then use an existing buffer and copy the contents
      // to said buffer.  If 16 or less, then just iterate over the string using charAt()

      char[] cbuf = new char[off + len];
      System.arraycopy(text, off, cbuf, 0, len);

      writer.write(escapeArray(cbuf));
    } else if (dontEscape) {
      writer.write(text, off, len);
    } else {
      HtmlUtils.writeText(writer, escapeUnicode, escapeIso, buffer, text, off, len);
    }
  }
Exemple #4
0
 public boolean isReadOnly(ELContext context, Object base, Object property) throws ELException {
   if (base != null) {
     return false;
   }
   if (property == null) {
     String message =
         MessageUtils.getExceptionMessageString(
             MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "property");
     throw new PropertyNotFoundException(message);
   }
   // return value will be ignored unless context.propertyResolved is
   // set to true.
   Integer index = IMPLICIT_OBJECTS.get(property.toString());
   if (index == null) {
     return false;
   }
   switch (index) {
     case FACES_CONTEXT:
       context.setPropertyResolved(true);
       return true;
     case VIEW:
       context.setPropertyResolved(true);
       return true;
     default:
       return false;
   }
 }
  //
  // Methods from FacesContextFactory
  //
  public FacesContext getFacesContext(
      Object sc, Object request, Object response, Lifecycle lifecycle) throws FacesException {

    try {
      Util.parameterNonNull(sc);
      Util.parameterNonNull(request);
      Util.parameterNonNull(response);
      Util.parameterNonNull(lifecycle);
    } catch (Exception e) {
      throw new NullPointerException(
          MessageUtils.getExceptionMessageString(
              MessageUtils.FACES_CONTEXT_CONSTRUCTION_ERROR_MESSAGE_ID));
    }
    FacesContext ctx =
        new FacesContextImpl(
            new ExternalContextImpl(
                (ServletContext) sc, (ServletRequest) request, (ServletResponse) response),
            lifecycle);
    // store the default FacesContext and ExternalContext implementations
    // in the request so that the API can delegate if the happen to be
    // decorated by 1.1 implementations
    RequestStateManager.set(ctx, RequestStateManager.FACESCONTEXT_IMPL_ATTR_NAME, ctx);
    RequestStateManager.set(
        ctx, RequestStateManager.EXTERNALCONTEXT_IMPL_ATTR_NAME, ctx.getExternalContext());
    return ctx;
  }
Exemple #6
0
  public Class<?> getType(ELContext context, Object base, Object property) throws ELException {
    if (base != null) {
      return null;
    }
    if (property == null) {
      String message =
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "property");
      throw new PropertyNotFoundException(message);
    }

    Integer index = IMPLICIT_OBJECTS.get(property.toString());

    if (index == null) {
      return null;
    }
    switch (index) {
      case FACES_CONTEXT:
      case VIEW:
        context.setPropertyResolved(true);
        return null;
      default:
        return null;
    }
  }
Exemple #7
0
  /**
   * Write the start of an element, up to and including the element name. Clients call <code>
   * writeAttribute()</code> or <code>writeURIAttribute()</code> methods to add attributes after
   * calling this method.
   *
   * @param name Name of the starting element
   * @param componentForElement The UIComponent instance that applies to this element. This argument
   *     may be <code>null</code>.
   * @throws IOException if an input/output error occurs
   * @throws NullPointerException if <code>name</code> is <code>null</code>
   */
  public void startElement(String name, UIComponent componentForElement) throws IOException {

    if (name == null) {
      throw new NullPointerException(
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "name"));
    }
    closeStartIfNecessary();
    isScriptOrStyle(name);
    scriptOrStyleSrc = false;
    if ("cdata".equalsIgnoreCase(name)) {
      isCdata = true;
      startCDATA();
      return;
    } else if (writingCdata) {
      // starting an element within a cdata section,
      // keep escaping disabled
      isCdata = false;
      writingCdata = true;
      dontEscape = true;
    }

    writer.write('<');
    writer.write(name);
    closeStart = true;
  }
  @Override
  @SuppressWarnings("deprecation")
  public Object getValue(ELContext context, Object base, Object property) throws ELException {

    // Don't call into the chain unless it's been decorated.
    if (legacyVR instanceof ChainAwareVariableResolver) {
      return null;
    }

    if (base != null) {
      return null;
    }
    if (base == null && property == null) {
      String message =
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "base and property"); // ?????
      throw new PropertyNotFoundException(message);
    }
    context.setPropertyResolved(true);
    Object result = null;

    FacesContext facesContext = (FacesContext) context.getContext(FacesContext.class);
    String propString = property.toString();
    Map<String, Object> stateMap = RequestStateManager.getStateMap(facesContext);
    try {
      // If we are already in the midst of an expression evaluation
      // that touched this resolver...
      //noinspection unchecked
      List<String> varNames = (List<String>) stateMap.get(RequestStateManager.REENTRANT_GUARD);
      if (varNames != null && !varNames.isEmpty() && varNames.contains(propString)) {
        // take no action and return.
        context.setPropertyResolved(false);
        return null;
      }
      // Make sure subsequent calls don't take action.
      if (varNames == null) {
        varNames = new ArrayList<>();
        stateMap.put(RequestStateManager.REENTRANT_GUARD, varNames);
      }
      varNames.add(propString);

      result = legacyVR.resolveVariable(facesContext, propString);
    } catch (EvaluationException ex) {
      context.setPropertyResolved(false);
      throw new ELException(ex);
    } finally {
      // Make sure to remove the guard after the call returns
      //noinspection unchecked
      List<String> varNames = (List<String>) stateMap.get(RequestStateManager.REENTRANT_GUARD);
      if (varNames != null && !varNames.isEmpty()) {
        varNames.remove(propString);
      }
      // Make sure that the ELContext "resolved" indicator is set
      // in accordance wth the result of the resolution.
      context.setPropertyResolved(result != null);
    }
    return result;
  }
Exemple #9
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();
  }
Exemple #10
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);
    }
  }
Exemple #11
0
  /**
   * Write a properly encoded URI attribute name and the corresponding value. The value text will be
   * converted to a String if necessary). This method may only be called after a call to <code>
   * startElement()</code>, and before the opened element has been closed.
   *
   * @param name Attribute name to be added
   * @param value Attribute value to be added
   * @param componentPropertyName The name of the component property to which this attribute
   *     argument applies. This argument may be <code>null</code>.
   * @throws IllegalStateException if this method is called when there is no currently open element
   * @throws IOException if an input/output error occurs
   * @throws NullPointerException if <code>name</code> or <code>value</code> is <code>null</code>
   */
  public void writeURIAttribute(String name, Object value, String componentPropertyName)
      throws IOException {

    if (name == null) {
      throw new NullPointerException(
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "name"));
    }
    if (value == null) {
      throw new NullPointerException(
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "value"));
    }

    if (isCdata) {
      return;
    }

    if (name.equalsIgnoreCase("src") && isScriptOrStyle()) {
      scriptOrStyleSrc = true;
    }

    attributesBuffer.write(' ');
    attributesBuffer.write(name);
    attributesBuffer.write("=\"");

    String stringValue = value.toString();
    ensureTextBufferCapacity(stringValue);
    // Javascript URLs should not be URL-encoded
    if (stringValue.startsWith("javascript:")) {
      HtmlUtils.writeAttribute(
          attributesBuffer,
          escapeUnicode,
          escapeIso,
          buffer,
          stringValue,
          textBuffer,
          isScriptInAttributeValueEnabled);
    } else {
      HtmlUtils.writeURL(attributesBuffer, stringValue, textBuffer, encoding);
    }

    attributesBuffer.write('"');
  }
Exemple #12
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);
  }
Exemple #13
0
 protected Class loadClass(String className) {
   Class valueType = String.class;
   if (null != className && 0 < className.length()) {
     if (className.equals(Boolean.TYPE.getName())) {
       valueType = Boolean.TYPE;
     } else if (className.equals(Byte.TYPE.getName())) {
       valueType = Byte.TYPE;
     } else if (className.equals(Double.TYPE.getName())) {
       valueType = Double.TYPE;
     } else if (className.equals(Float.TYPE.getName())) {
       valueType = Float.TYPE;
     } else if (className.equals(Integer.TYPE.getName())) {
       valueType = Integer.TYPE;
     } else if (className.equals(Character.TYPE.getName())) {
       valueType = Character.TYPE;
     } else if (className.equals(Short.TYPE.getName())) {
       valueType = Short.TYPE;
     } else if (className.equals(Long.TYPE.getName())) {
       valueType = Long.TYPE;
     } else {
       try {
         valueType = Util.loadClass(className, this);
       } catch (ClassNotFoundException cnfe) {
         String message =
             MessageUtils.getExceptionMessageString(
                 MessageUtils.MANAGED_BEAN_CLASS_NOT_FOUND_ERROR_ID,
                 className,
                 beanInfo.getName());
         throw new ManagedBeanPreProcessingException(message, cnfe);
       } catch (NoClassDefFoundError ncdfe) {
         String message =
             MessageUtils.getExceptionMessageString(
                 MessageUtils.MANAGED_BEAN_CLASS_DEPENDENCY_NOT_FOUND_ERROR_ID,
                 className,
                 beanInfo.getName(),
                 ncdfe.getMessage());
         throw new ManagedBeanPreProcessingException(message, ncdfe);
       }
     }
   }
   return valueType;
 }
Exemple #14
0
  protected Object newBeanInstance() {

    try {
      return loadBeanClass().newInstance();
    } catch (Exception e) {
      String message =
          MessageUtils.getExceptionMessageString(
              MessageUtils.CANT_INSTANTIATE_CLASS_ERROR_MESSAGE_ID, loadBeanClass().getName());
      throw new ManagedBeanCreationException(message, e);
    }
  }
Exemple #15
0
  /**
   * Write a properly escaped attribute name and the corresponding value. The value text will be
   * converted to a String if necessary. This method may only be called after a call to <code>
   * startElement()</code>, and before the opened element has been closed.
   *
   * @param name Attribute name to be added
   * @param value Attribute value to be added
   * @param componentPropertyName The name of the component property to which this attribute
   *     argument applies. This argument may be <code>null</code>.
   * @throws IllegalStateException if this method is called when there is no currently open element
   * @throws IOException if an input/output error occurs
   * @throws NullPointerException if <code>name</code> is <code>null</code>
   */
  public void writeAttribute(String name, Object value, String componentPropertyName)
      throws IOException {

    if (name == null) {
      throw new NullPointerException(
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "name"));
    }
    if (value == null) {
      return;
    }

    if (isCdata) {
      return;
    }

    if (name.equalsIgnoreCase("src") && isScriptOrStyle()) {
      scriptOrStyleSrc = true;
    }

    Class valueClass = value.getClass();

    // Output Boolean values specially
    if (valueClass == Boolean.class) {
      if (Boolean.TRUE.equals(value)) {
        // NOTE:  HTML 4.01 states that boolean attributes
        //        may legally take a single value which is the
        //        name of the attribute itself or appear using
        //        minimization.
        //  http://www.w3.org/TR/html401/intro/sgmltut.html#h-3.3.4.2
        attributesBuffer.write(' ');
        attributesBuffer.write(name);
        attributesBuffer.write("=\"");
        attributesBuffer.write(name);
        attributesBuffer.write('"');
      }
    } else {
      attributesBuffer.write(' ');
      attributesBuffer.write(name);
      attributesBuffer.write("=\"");
      // write the attribute value
      String val = value.toString();
      ensureTextBufferCapacity(val);
      HtmlUtils.writeAttribute(
          attributesBuffer,
          escapeUnicode,
          escapeIso,
          buffer,
          val,
          textBuffer,
          isScriptInAttributeValueEnabled);
      attributesBuffer.write('"');
    }
  }
Exemple #16
0
 public Object getAsObject(FacesContext context, UIComponent component, String value) {
   Converter delegate = getDelegate(context);
   if (delegate != null) {
     return delegate.getAsObject(context, component, value);
   } else {
     throw new ConverterException(
         MessageUtils.getExceptionMessage(
             MessageUtils.CANNOT_CONVERT_ID,
             converterId != null ? converterId.getExpressionString() : "",
             binding != null ? binding.getExpressionString() : ""));
   }
 }
Exemple #17
0
  /**
   * This code is currently common to all {@link ViewHandlingStrategy} instances.
   *
   * @see ViewHandler#getActionURL(javax.faces.context.FacesContext, String)
   */
  public String getActionURL(FacesContext context, String viewId) {

    Util.notNull("context", context);
    Util.notNull("viewId", viewId);

    if (viewId.charAt(0) != '/') {
      String message =
          MessageUtils.getExceptionMessageString(MessageUtils.ILLEGAL_VIEW_ID_ID, viewId);
      if (logger.isLoggable(Level.SEVERE)) {
        logger.log(Level.SEVERE, "jsf.illegal_view_id_error", viewId);
      }
      throw new IllegalArgumentException(message);
    }

    // Acquire the context path, which we will prefix on all results
    ExternalContext extContext = context.getExternalContext();
    String contextPath = extContext.getRequestContextPath();

    // Acquire the mapping used to execute this request (if any)
    String mapping = Util.getFacesMapping(context);

    // If no mapping can be identified, just return a server-relative path
    if (mapping == null) {
      return (contextPath + viewId);
    }

    // Deal with prefix mapping
    if (Util.isPrefixMapped(mapping)) {
      if (mapping.equals("/*")) {
        return (contextPath + viewId);
      } else {
        return (contextPath + mapping + viewId);
      }
    }

    // Deal with extension mapping
    int period = viewId.lastIndexOf('.');
    if (period < 0) {
      return (contextPath + viewId + mapping);
    } else if (!viewId.endsWith(mapping)) {

      for (String ext : configuredExtensions) {
        if (viewId.endsWith(ext)) {
          return (contextPath + viewId.substring(0, viewId.indexOf(ext)) + mapping);
        }
      }

      return (contextPath + viewId.substring(0, period) + mapping);
    } else {
      return (contextPath + viewId);
    }
  }
Exemple #18
0
  protected void invokePostConstruct(Object bean, InjectionProvider injectionProvider) {

    if (isInjectible) {
      try {
        injectionProvider.invokePostConstruct(bean);
      } catch (InjectionProviderException ipe) {
        String message =
            MessageUtils.getExceptionMessageString(
                MessageUtils.MANAGED_BEAN_INJECTION_ERROR_ID, beanInfo.getName());
        throw new ManagedBeanCreationException(message, ipe);
      }
    }
  }
Exemple #19
0
  /**
   * Determine the next view based on the current view (<code>from-view-id</code> stored in <code>
   * FacesContext</code>), <code>fromAction</code> and <code>outcome</code>.
   *
   * @param context The <code>FacesContext</code>
   * @param fromAction the action reference string
   * @param outcome the outcome string
   */
  public void handleNavigation(FacesContext context, String fromAction, String outcome) {
    if (context == null) {
      String message =
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "context");
      throw new NullPointerException(message);
    }
    if (outcome == null) {
      return; // Explicitly remain on the current view
    }
    CaseStruct caseStruct = getViewId(context, fromAction, outcome);
    ExternalContext extContext = context.getExternalContext();
    if (caseStruct != null) {
      ViewHandler viewHandler = Util.getViewHandler(context);
      assert (null != viewHandler);

      if (caseStruct.navCase.isRedirect()) {
        // perform a 302 redirect.
        String newPath = viewHandler.getActionURL(context, caseStruct.viewId);
        try {
          if (logger.isLoggable(Level.FINE)) {
            logger.fine(
                "Redirecting to path "
                    + newPath
                    + " for outcome "
                    + outcome
                    + "and viewId "
                    + caseStruct.viewId);
          }
          // encode the redirect to ensure session state
          // is maintained
          extContext.redirect(extContext.encodeActionURL(newPath));
        } catch (java.io.IOException ioe) {
          if (logger.isLoggable(Level.SEVERE)) {
            logger.log(Level.SEVERE, "jsf.redirect_failed_error", newPath);
          }
          throw new FacesException(ioe.getMessage(), ioe);
        }
        context.responseComplete();
        if (logger.isLoggable(Level.FINE)) {
          logger.fine("Response complete for " + caseStruct.viewId);
        }
      } else {
        UIViewRoot newRoot = viewHandler.createView(context, caseStruct.viewId);
        context.setViewRoot(newRoot);
        if (logger.isLoggable(Level.FINE)) {
          logger.fine("Set new view in FacesContext for " + caseStruct.viewId);
        }
      }
    }
  }
Exemple #20
0
  /**
   * Write properly escaped text from a character array. The output from this command is identical
   * to the invocation: <code>writeText(c, 0, c.length)</code>. If there is an open element that has
   * been created by a call to <code>startElement()</code>, that element will be closed first.
   *
   * <p>
   *
   * <p>All angle bracket occurrences in the argument must be escaped using the &amp;gt; &amp;lt;
   * syntax.
   *
   * @param text Text to be written
   * @throws IOException if an input/output error occurs
   * @throws NullPointerException if <code>text</code> is <code>null</code>
   */
  public void writeText(char text[]) throws IOException {

    if (text == null) {
      throw new NullPointerException(
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "text"));
    }
    closeStartIfNecessary();
    if (dontEscape) {
      writer.write(text);
    } else {
      HtmlUtils.writeText(writer, escapeUnicode, escapeIso, buffer, text);
    }
  }
Exemple #21
0
    /**
     * Perform the correctness checks implemented by this {@link javax.faces.validator.Validator}
     * against the specified {@link javax.faces.component.UIComponent}. If any violations are found,
     * a {@link javax.faces.validator.ValidatorException} will be thrown containing the {@link
     * javax.faces.application.FacesMessage} describing the failure.
     *
     * @param context FacesContext for the request we are processing
     * @param component UIComponent we are checking for correctness
     * @param value the value to validate
     * @throws javax.faces.validator.ValidatorException if validation fails
     * @throws NullPointerException if <code>context</code> or <code>component</code> is <code>null
     *     </code>
     */
    public void validate(FacesContext context, UIComponent component, Object value)
        throws ValidatorException {

      Validator instance = createValidator(validatorId, binding, context);

      if (instance != null) {
        instance.validate(context, component, value);
      } else {
        throw new ValidatorException(
            MessageUtils.getExceptionMessage(
                MessageUtils.CANNOT_VALIDATE_ID,
                validatorId != null ? validatorId.getExpressionString() : "",
                binding != null ? binding.getExpressionString() : ""));
      }
    }
Exemple #22
0
 private void validateLifespan(ELUtils.Scope expressionScope, boolean runtime) {
   if (!ELUtils.hasValidLifespan(expressionScope, scope)) {
     String message =
         MessageUtils.getExceptionMessageString(
             MessageUtils.INVALID_SCOPE_LIFESPAN_ERROR_MESSAGE_ID,
             this.expressionString,
             expressionScope,
             beanInfo.getName(),
             scope.toString());
     if (runtime) {
       throw new ManagedBeanCreationException(message);
     } else {
       queueMessage(message);
     }
   }
 }
  /**
   * Locates the component identified by <code>forComponent</code>
   *
   * @param context the FacesContext for the current request
   * @param forComponent - the component to search for
   * @param component - the starting point in which to begin the search
   * @return the component with the the <code>id</code that matches
   *         <code>
   *     forComponent</code> otheriwse null if no match is found.
   */
  protected UIComponent getForComponent(
      FacesContext context, String forComponent, UIComponent component) {

    if (null == forComponent || forComponent.length() == 0) {
      return null;
    }

    UIComponent result = null;
    UIComponent currentParent = component;
    try {
      // Check the naming container of the current
      // component for component identified by
      // 'forComponent'
      while (currentParent != null) {
        // If the current component is a NamingContainer,
        // see if it contains what we're looking for.
        result = currentParent.findComponent(forComponent);
        if (result != null) {
          break;
        }
        // if not, start checking further up in the view
        currentParent = currentParent.getParent();
      }

      // no hit from above, scan for a NamingContainer
      // that contains the component we're looking for from the root.
      if (result == null) {
        result = findUIComponentBelow(context.getViewRoot(), forComponent);
      }
    } catch (Exception e) {
      if (logger.isLoggable(Level.FINEST)) {
        logger.log(Level.FINEST, "Unable to find for component", e);
      }
    }
    // log a message if we were unable to find the specified
    // component (probably a misconfigured 'for' attribute
    if (result == null) {
      if (logger.isLoggable(Level.WARNING)) {
        logger.warning(
            MessageUtils.getExceptionMessageString(
                MessageUtils.COMPONENT_NOT_FOUND_IN_VIEW_WARNING_ID, forComponent));
      }
    }
    return result;
  }
Exemple #24
0
  /**
   * Write a properly escaped object. The object will be converted to a String if necessary. If
   * there is an open element that has been created by a call to <code>startElement()</code>, that
   * element will be closed first.
   *
   * @param text Text to be written
   * @param componentPropertyName The name of the component property to which this text argument
   *     applies. This argument may be <code>null</code>.
   * @throws IOException if an input/output error occurs
   * @throws NullPointerException if <code>text</code> is <code>null</code>
   */
  public void writeText(Object text, String componentPropertyName) throws IOException {

    if (text == null) {
      throw new NullPointerException(
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "text"));
    }
    closeStartIfNecessary();
    if (writingCdata) {
      writer.write(escapeArray(text.toString().toCharArray()));
    } else if (dontEscape) {
      writer.write(text.toString());
    } else {
      String val = text.toString();
      ensureTextBufferCapacity(val);
      HtmlUtils.writeText(writer, escapeUnicode, escapeIso, buffer, val, textBuffer);
    }
  }
  protected String writeIdAttributeIfNecessary(
      FacesContext context, ResponseWriter writer, UIComponent component) {

    String id = null;
    if (shouldWriteIdAttribute(component)) {
      try {
        writer.writeAttribute("id", id = component.getClientId(context), "id");
      } catch (IOException e) {
        if (logger.isLoggable(Level.WARNING)) {
          String message =
              MessageUtils.getExceptionMessageString(
                  MessageUtils.CANT_WRITE_ID_ATTRIBUTE_ERROR_MESSAGE_ID, e.getMessage());
          logger.warning(message);
        }
      }
    }
    return id;
  }
Exemple #26
0
  /**
   * Write a comment string containing the specified text. The text will be converted to a String if
   * necessary. If there is an open element that has been created by a call to <code>startElement()
   * </code>, that element will be closed first.
   *
   * @param comment Text content of the comment
   * @throws IOException if an input/output error occurs
   * @throws NullPointerException if <code>comment</code> is <code>null</code>
   */
  public void writeComment(Object comment) throws IOException {

    if (comment == null) {
      throw new NullPointerException(
          MessageUtils.getExceptionMessageString(MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID));
    }

    if (writingCdata) {
      return;
    }

    closeStartIfNecessary();
    // Don't include a trailing space after the '<!--'
    // or a leading space before the '-->' to support
    // IE conditional commentsoth
    writer.write("<!--");
    writer.write(comment.toString());
    writer.write("-->");
  }
Exemple #27
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");
    }
  }
Exemple #28
0
  protected void renderAsDisabled(
      FacesContext context, UIComponent component, boolean failedToResolveNavigationCase)
      throws IOException {

    ResponseWriter writer = context.getResponseWriter();
    assert (writer != null);

    writer.startElement("span", component);
    writeIdAndNameAttributes(context, writer, component);
    renderLinkCommonAttributes(writer, component);
    renderPassThruAttributes(context, writer, component, ATTRIBUTES);
    writeValue(writer, component);

    // shame that we can't put this in encodeEnd, but then we have to attempt to resolve the
    // navigation case again
    if (failedToResolveNavigationCase) {
      if (!context.isProjectStage(ProjectStage.Production)) {
        writer.write(
            MessageUtils.getExceptionMessageString(MessageUtils.OUTCOME_TARGET_LINK_NO_MATCH));
      }
    }
  }
Exemple #29
0
  public Object getValue(ELContext context, Object base, Object property) throws ELException {
    // variable resolution is a special case of property resolution
    // where the base is null.
    if (base != null) {
      return null;
    }
    if (property == null) {
      String message =
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "property");
      throw new PropertyNotFoundException(message);
    }

    Integer index = IMPLICIT_OBJECTS.get(property.toString());

    if (index == null) {
      return null;
    }

    FacesContext facesContext = (FacesContext) context.getContext(FacesContext.class);

    switch (index.intValue()) {
      case FACES_CONTEXT:
        context.setPropertyResolved(true);
        return facesContext;
      case VIEW:
        context.setPropertyResolved(true);
        return facesContext.getViewRoot();
      case VIEW_SCOPE:
        context.setPropertyResolved(true);
        return facesContext.getViewRoot().getViewMap();
      case RESOURCE:
        context.setPropertyResolved(true);
        return facesContext.getApplication().getResourceHandler();
      default:
        return null;
    }
  }
Exemple #30
0
  /**
   * This method uses helper methods to determine the new <code>view</code> identifier. Refer to
   * section 7.4.2 of the specification for more details.
   *
   * @param context The Faces Context
   * @param fromAction The action reference string
   * @param outcome The outcome string
   * @return The <code>view</code> identifier.
   */
  private CaseStruct getViewId(FacesContext context, String fromAction, String outcome) {

    UIViewRoot root = context.getViewRoot();
    String viewId = (root != null ? root.getViewId() : null);

    // if viewId is not null, use its value to find
    // a navigation match, otherwise look for a match
    // based soley on the fromAction and outcome
    CaseStruct caseStruct = null;
    if (viewId != null) {
      caseStruct = findExactMatch(viewId, fromAction, outcome);

      if (caseStruct == null) {
        caseStruct = findWildCardMatch(viewId, fromAction, outcome);
      }
    }

    if (caseStruct == null) {
      caseStruct = findDefaultMatch(fromAction, outcome);
    }

    if (caseStruct == null && development) {
      String key;
      Object[] params;
      if (fromAction == null) {
        key = MessageUtils.NAVIGATION_NO_MATCHING_OUTCOME_ID;
        params = new Object[] {viewId, outcome};
      } else {
        key = MessageUtils.NAVIGATION_NO_MATCHING_OUTCOME_ACTION_ID;
        params = new Object[] {viewId, fromAction, outcome};
      }
      FacesMessage m = MessageUtils.getExceptionMessage(key, params);
      m.setSeverity(FacesMessage.SEVERITY_WARN);
      context.addMessage(null, m);
    }
    return caseStruct;
  }