protected Iterator<MessageForRender> getMessages(
      FacesContext context, String forClientId, UIComponent component) {

    Iterator<MessageForRender> msgIter;

    if (forClientId != null) {

      if (forClientId.length() != 0) {

        UIComponent result = RendererUtils.getInstance().findComponentFor(component, forClientId);
        if (result == null) {
          msgIter = Iterators.emptyIterator();
        } else {
          String clientId = result.getClientId(context);
          msgIter = getMessagesForId(context, clientId);
        }
      } else {
        msgIter = getMessagesForId(context, null);
      }
    } else {
      msgIter = Iterators.emptyIterator();
      Iterator<String> clientIdsWithMessages = context.getClientIdsWithMessages();
      while (clientIdsWithMessages.hasNext()) {
        String clientId = (String) clientIdsWithMessages.next();
        msgIter = Iterators.concat(msgIter, getMessagesForId(context, clientId));
      }
    }

    return msgIter;
  }
  private void printMessagesAssociatedWithComponents(FacesContext context) {

    final Iterator<String> clientsWithMessages = context.getClientIdsWithMessages();
    while (clientsWithMessages.hasNext()) {

      String clientId = clientsWithMessages.next();

      final Iterator<FacesMessage> messages = context.getMessages(clientId);
      while (messages.hasNext()) {
        final FacesMessage facesMessage = messages.next();
        logMessage(clientId, facesMessage);

        facesMessage.setSummary(
            facesMessage.getSummary() + "  -- tagged by " + this.getClass().getSimpleName());
      }
    }
  }
 /**
  * Caches messages from current faces context to a session object
  *
  * @param context
  * @return
  */
 private int cacheMessages(FacesContext context) {
   int cachedCount = 0;
   Iterator<String> clientIdsWithMessages = context.getClientIdsWithMessages();
   while (clientIdsWithMessages.hasNext()) {
     String clientId = clientIdsWithMessages.next();
     Iterator<FacesMessage> iterator = context.getMessages(clientId);
     Collection<FacesMessage> cachedMessages = getMessageCache(context).get(clientId);
     if (cachedMessages == null) {
       // cachedMessages = new TreeSet<FacesMessage>(new FacesMessageComparator());
       cachedMessages = new ArrayList<FacesMessage>();
       getMessageCache(context).put(clientId, cachedMessages);
     }
     while (iterator.hasNext()) {
       FacesMessage facesMessage = iterator.next();
       if (cachedMessages.add(facesMessage)) {
         cachedCount++;
       }
     }
   }
   LOGGER.trace("Saved " + cachedCount + " messages in cache");
   return cachedCount;
 }
Example #4
0
  // used in ITFocusValidationAware#testValidateMultipleInputsDuringFormSubmission and
  // ITFocusValidationAware#testValidateMultipleInputsDuringAjax
  public void invalidateBothInputsAndCheckFocus() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    AbstractFocus comp = getComponent();
    FocusRendererBase renderer = getRenderer();

    // assert intial focus on form
    String expectedFocusCandidates = "form";
    String actualFocusCandidates = renderer.getFocusCandidatesAsString(facesContext, comp);
    if (!expectedFocusCandidates.equals(actualFocusCandidates)) {
      invalidateBothInputsAndCheckFocusResult =
          MessageFormat.format(
              "Only form should be focused. Expected focus candidates <{0}>, but have: <{1}>.",
              expectedFocusCandidates, actualFocusCandidates);
      return;
    }

    // invalidate first two inputs
    for (String invalidate : new String[] {"form:input1", "form:input2"}) {
      facesContext.addMessage(invalidate, new FacesMessage("invalidated " + invalidate));
    }

    if (!facesContext.getClientIdsWithMessages().hasNext()) {
      invalidateBothInputsAndCheckFocusResult = "Messages should be generated.";
      return;
    }

    // assert focus on first input
    expectedFocusCandidates = "form:input1 form:input2";
    actualFocusCandidates = renderer.getFocusCandidatesAsString(facesContext, comp);
    if (!expectedFocusCandidates.equals(actualFocusCandidates)) {
      invalidateBothInputsAndCheckFocusResult =
          MessageFormat.format(
              "First input should be focused. Expected focus candidates <{0}>, but have: <{1}>.",
              expectedFocusCandidates, actualFocusCandidates);
      return;
    }
    invalidateBothInputsAndCheckFocusResult = PASSED;
  }
 private static String genJavaScriptCodeForMessages(FacesContext facesContext) {
   if (facesContext.getMessages().hasNext()) {
     StringBuffer jsTxt =
         new StringBuffer("Event.observe(window, 'load', function() {FX4Web.showMessages([");
     // add messages for each clientId that has them (including 'null' for global messages)
     Iterator<String> itrClientIds = facesContext.getClientIdsWithMessages();
     while (itrClientIds.hasNext()) {
       String clientId = itrClientIds.next();
       appendMessagesForClientId(facesContext, clientId, jsTxt);
     }
     // now finally remove the extr "," from the end
     if (jsTxt.length() > 0 && jsTxt.charAt(jsTxt.length() - 1) == ',') {
       jsTxt.deleteCharAt(jsTxt.length() - 1);
     }
     jsTxt.append("], {title: 'Application Messages'});});");
     return jsTxt.toString();
   } else {
     //            StringBuffer jsTxt = new StringBuffer(
     //                "Event.observe(window, 'load', function() {FX4Web.showWaitMessage()})");
     //            return jsTxt.toString();
     return null;
   }
 }
Example #6
0
  public void execute(FacesContext facesContext) throws FacesException {

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Entering RenderResponsePhase");
    }
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("About to render view " + facesContext.getViewRoot().getViewId());
    }
    // For requests intended to produce a partial response, we need prohibit
    // writing any content outside of the view itself (f:view).
    if (facesContext.isAjaxRequest()) {
      facesContext.enableResponseWriting(false);
    }

    try {
      // Setup message display LOGGER.
      if (LOGGER.isLoggable(Level.INFO)) {
        Iterator<String> clientIdIter = facesContext.getClientIdsWithMessages();

        // If Messages are queued
        if (clientIdIter.hasNext()) {
          Set<String> clientIds = new HashSet<String>();

          // Copy client ids to set of clientIds pending display.
          while (clientIdIter.hasNext()) {
            clientIds.add(clientIdIter.next());
          }
          RequestStateManager.set(
              facesContext, RequestStateManager.CLIENT_ID_MESSAGES_NOT_DISPLAYED, clientIds);
        }
      }

      // render the view
      facesContext
          .getApplication()
          .getViewHandler()
          .renderView(facesContext, facesContext.getViewRoot());

      // display results of message display LOGGER
      if (LOGGER.isLoggable(Level.INFO)
          && RequestStateManager.containsKey(
              facesContext, RequestStateManager.CLIENT_ID_MESSAGES_NOT_DISPLAYED)) {

        // remove so Set does not get modified when displaying messages.
        Set<String> clientIds =
            TypedCollections.dynamicallyCastSet(
                (Set)
                    RequestStateManager.remove(
                        facesContext, RequestStateManager.CLIENT_ID_MESSAGES_NOT_DISPLAYED),
                String.class);
        if (!clientIds.isEmpty()) {

          // Display each message possibly not displayed.
          StringBuilder builder = new StringBuilder();
          for (String clientId : clientIds) {
            Iterator<FacesMessage> messages = facesContext.getMessages(clientId);
            while (messages.hasNext()) {
              FacesMessage message = messages.next();
              builder.append("\n");
              builder.append("sourceId=").append(clientId);
              builder.append("[severity=(").append(message.getSeverity());
              builder.append("), summary=(").append(message.getSummary());
              builder.append("), detail=(").append(message.getDetail()).append(")]");
            }
          }
          LOGGER.log(Level.INFO, "jsf.non_displayed_message", builder.toString());
        }
      }
    } catch (IOException e) {
      throw new FacesException(e.getMessage(), e);
    }

    if (LOGGER.isLoggable(Level.FINEST)) {
      LOGGER.log(
          Level.FINEST,
          "+=+=+=+=+=+= View structure printout for " + facesContext.getViewRoot().getViewId());
      DebugUtil.printTree(facesContext.getViewRoot(), LOGGER, Level.FINEST);
    }

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Exiting RenderResponsePhase");
    }
  }
  /**
   * Saves the state of the FacesContext as required by section 5.1.2 of the JSR 329 spec. This
   * method is designed to be called during the ACTION_PHASE of the portlet lifecycle.
   *
   * @param facesContext The current faces context.
   */
  public void preserveScopedData(FacesContext facesContext) {

    logger.debug("preserveScopedData(facesContext)");

    // Get the ExternalContext.
    ExternalContext externalContext = facesContext.getExternalContext();

    // Save the view root.
    setAttribute(BRIDGE_REQ_SCOPE_ATTR_FACES_VIEW_ROOT, facesContext.getViewRoot());

    // If the PortletMode hasn't changed, then preserve the "javax.faces.ViewState" request
    // parameter value.
    if (!portletModeChanged) {
      PortletResponse portletResponse =
          (PortletResponse) facesContext.getExternalContext().getResponse();

      if (portletResponse instanceof ActionResponse) {
        String viewState =
            facesContext
                .getExternalContext()
                .getRequestParameterMap()
                .get(ResponseStateManager.VIEW_STATE_PARAM);

        if (viewState != null) {

          // NOTE: Although it is possible to save this as a render parameter, can't use that
          // approach because
          // portlet containers like Pluto will add the "javax.faces.ViewState" parameter to any
          // ResourceURLs
          // that are created during the RENDER_PHASE of the portlet lifecycle.
          setAttribute(ResponseStateManager.VIEW_STATE_PARAM, viewState);
        }
      }
    }

    // If specified in the WEB-INF/portlet.xml descriptor, then preserve the action parameters.
    BridgeContext bridgeContext =
        (BridgeContext) facesContext.getAttributes().get(BridgeExt.BRIDGE_CONTEXT_ATTRIBUTE);

    if (bridgeContext.isPreserveActionParams()) {
      Map<String, String> actionRequestParameterMap =
          new HashMap<String, String>(externalContext.getRequestParameterMap());
      actionRequestParameterMap.remove(ResponseStateManager.VIEW_STATE_PARAM);
      actionRequestParameterMap.remove(JAVAX_FACES_ENCODED_URL_PARAM);
      setAttribute(BRIDGE_REQ_SCOPE_ATTR_ACTION_PARAMS, actionRequestParameterMap);
    }

    // Save the list of faces messages.
    List<FacesMessageWrapper> facesMessageWrappers = new ArrayList<FacesMessageWrapper>();
    Iterator<String> clientIds = facesContext.getClientIdsWithMessages();

    while (clientIds.hasNext()) {
      String clientId = clientIds.next();
      Iterator<FacesMessage> facesMessages = facesContext.getMessages(clientId);

      while (facesMessages.hasNext()) {
        FacesMessage facesMessage = facesMessages.next();
        FacesMessageWrapper facesMessageWrapper = new FacesMessageWrapper(clientId, facesMessage);
        facesMessageWrappers.add(facesMessageWrapper);
      }
    }

    if (facesMessageWrappers.size() > 0) {
      setAttribute(BRIDGE_REQ_SCOPE_ATTR_FACES_MESSAGES, facesMessageWrappers);
    } else {
      logger.trace("Not saving any faces messages");
    }

    // Save the non-excluded request attributes. This would include, for example, managed-bean
    // instances that may
    // have been created during the ACTION_PHASE that need to survive to the RENDER_PHASE.
    if ((!redirect) && (!portletModeChanged)) {
      Map<String, Object> currentRequestAttributes = externalContext.getRequestMap();

      if (currentRequestAttributes != null) {
        List<RequestAttribute> savedRequestAttributes = new ArrayList<RequestAttribute>();
        Iterator<Map.Entry<String, Object>> itr = currentRequestAttributes.entrySet().iterator();

        if (itr != null) {

          while (itr.hasNext()) {
            Map.Entry<String, Object> mapEntry = itr.next();
            String name = mapEntry.getKey();
            Object value = mapEntry.getValue();

            if (isExcludedRequestAttribute(name, value)) {
              logger.trace("Not saving EXCLUDED attribute name=[{0}]", name);
            } else if ((value != null)
                && (value.getClass().getAnnotation(ExcludeFromManagedRequestScope.class) != null)) {
              logger.trace(
                  "Not saving EXCLUDED attribute name=[{0}] due to ExcludeFromManagedRequestScope annotation",
                  name);
            } else {
              logger.trace(
                  "Saving non-excluded request attribute name=[{0}] value=[{1}]", name, value);
              savedRequestAttributes.add(new RequestAttribute(name, value));
            }
          }

          if (savedRequestAttributes.size() > 0) {
            setAttribute(BRIDGE_REQ_SCOPE_ATTR_REQUEST_ATTRIBUTES, savedRequestAttributes);
          } else {
            logger.trace("Not saving any non-excluded request attributes");
          }
        }
      } else {
        logger.trace(
            "Not saving any non-excluded request attributes because there are no request attributes!");
      }
    } else {
      logger.trace("Not saving any non-excluded request attributes due to redirect");
    }

    // NOTE: PROPOSED-FOR-BRIDGE3-API: https://issues.apache.org/jira/browse/PORTLETBRIDGE-203 Build
    // up a list of
    // attributes found in the FacesContext attribute map and save them. It has to be copied in this
    // manner because
    // the Faces implementation likely calls the clear() method during the call to its
    // FacesContextImpl.release()
    // method.
    Map<Object, Object> currentFacesContextAttributes = facesContext.getAttributes();
    int mapSize = currentFacesContextAttributes.size();
    List<FacesContextAttribute> savedFacesContextAttributes =
        new ArrayList<FacesContextAttribute>(mapSize);
    Iterator<Map.Entry<Object, Object>> itr = currentFacesContextAttributes.entrySet().iterator();

    while (itr.hasNext()) {
      Map.Entry<Object, Object> mapEntry = itr.next();
      Object name = mapEntry.getKey();
      Object value = mapEntry.getValue();
      logger.trace("Saving FacesContext attribute name=[{0}] value=[{1}]", name, value);
      savedFacesContextAttributes.add(new FacesContextAttribute(name, value));
    }

    setAttribute(BRIDGE_REQ_SCOPE_ATTR_FACES_CONTEXT_ATTRIBUTES, savedFacesContextAttributes);
  }
  /**
   * Saves the state of the FacesContext as required by section 5.1.2 of the JSR 329 spec. This
   * method is designed to be called during the ACTION_PHASE of the portlet lifecycle.
   *
   * @param facesContext The current faces context.
   */
  public void saveState(FacesContext facesContext) {

    logger.debug("saveState(facesContext)");

    // Get the ExternalContext and PortletResponse.
    BridgeContext bridgeContext = BridgeContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    PortletResponse portletResponse =
        (PortletResponse) facesContext.getExternalContext().getResponse();

    if ((beganInPhase == Bridge.PortletPhase.ACTION_PHASE)
        || (beganInPhase == Bridge.PortletPhase.EVENT_PHASE)
        || (beganInPhase == Bridge.PortletPhase.RESOURCE_PHASE)) {

      // Save the view root.
      setAttribute(BRIDGE_REQ_SCOPE_ATTR_FACES_VIEW_ROOT, facesContext.getViewRoot());

      // If the PortletMode hasn't changed, then preserve the "javax.faces.ViewState" request
      // parameter value.
      if (!isPortletModeChanged()) {

        if (portletResponse instanceof ActionResponse) {
          String viewState =
              facesContext
                  .getExternalContext()
                  .getRequestParameterMap()
                  .get(ResponseStateManager.VIEW_STATE_PARAM);

          if (viewState != null) {

            // NOTE: Although it is possible to save this as a render parameter, can't use that
            // approach
            // because portlet containers like Pluto will add the "javax.faces.ViewState" parameter
            // to any
            // ResourceURLs that are created during the RENDER_PHASE of the portlet lifecycle.
            setAttribute(ResponseStateManager.VIEW_STATE_PARAM, viewState);
          }
        }
      }

      // If specified in the WEB-INF/portlet.xml descriptor, then preserve the action parameters.
      if (bridgeContext.isPreserveActionParams()) {
        Map<String, String> actionRequestParameterMap =
            new HashMap<String, String>(externalContext.getRequestParameterMap());
        actionRequestParameterMap.remove(ResponseStateManager.VIEW_STATE_PARAM);
        actionRequestParameterMap.remove(JAVAX_FACES_ENCODED_URL_PARAM);
        setAttribute(BRIDGE_REQ_SCOPE_ATTR_ACTION_PARAMS, actionRequestParameterMap);
      }

      // Save the list of faces messages.
      List<FacesMessageWrapper> facesMessageWrappers = new ArrayList<FacesMessageWrapper>();
      Iterator<String> clientIds = facesContext.getClientIdsWithMessages();

      while (clientIds.hasNext()) {
        String clientId = clientIds.next();
        Iterator<FacesMessage> facesMessages = facesContext.getMessages(clientId);

        while (facesMessages.hasNext()) {
          FacesMessage facesMessage = facesMessages.next();
          FacesMessageWrapper facesMessageWrapper = new FacesMessageWrapper(clientId, facesMessage);
          facesMessageWrappers.add(facesMessageWrapper);
        }
      }

      if (facesMessageWrappers.size() > 0) {
        setAttribute(BRIDGE_REQ_SCOPE_ATTR_FACES_MESSAGES, facesMessageWrappers);
      } else {
        logger.trace("Not saving any faces messages");
      }

      // NOTE: PROPOSED-FOR-BRIDGE3-API: https://issues.apache.org/jira/browse/PORTLETBRIDGE-203
      // Build up a list
      // of attributes found in the FacesContext attribute map and save them. It has to be copied in
      // this manner
      // because the Faces implementation likely calls the clear() method during the call to its
      // FacesContextImpl.release() method.
      saveJSF2FacesContextAttributes(facesContext);
    }

    if ((beganInPhase == Bridge.PortletPhase.ACTION_PHASE)
        || (beganInPhase == Bridge.PortletPhase.EVENT_PHASE)
        || (beganInPhase == Bridge.PortletPhase.RESOURCE_PHASE)) {

      boolean saveNonExcludedAttributes = true;

      // If a redirect occurred, then indicate that the non-excluded request attributes are not to
      // be preserved.
      if (isRedirectOccurred()) {

        // TCK TestPage062: eventScopeNotRestoredRedirectTest
        logger.trace("Due to redirect, not saving any non-excluded request attributes");
        saveNonExcludedAttributes = false;
      }

      // Otherwise, if the portlet mode has changed, then indicate that the non-exluded request
      // attributes are
      // not to be preserved.
      else if (isPortletModeChanged()) {
        logger.trace("Due to PortletMode change, not saving any non-excluded request attributes");
        saveNonExcludedAttributes = false;
      }

      // If appropriate, save the non-excluded request attributes. This would include, for example,
      // managed-bean
      // instances that may have been created during the ACTION_PHASE that need to survive to the
      // RENDER_PHASE.
      Map<String, Object> currentRequestAttributes = externalContext.getRequestMap();

      if (currentRequestAttributes != null) {
        List<RequestAttribute> savedRequestAttributes = new ArrayList<RequestAttribute>();
        List<String> nonExcludedAttributeNames = new ArrayList<String>();
        Iterator<Map.Entry<String, Object>> itr = currentRequestAttributes.entrySet().iterator();

        if (itr != null) {

          while (itr.hasNext()) {
            Map.Entry<String, Object> mapEntry = itr.next();
            String attributeName = mapEntry.getKey();
            Object attributeValue = mapEntry.getValue();

            if (isExcludedRequestAttributeByConfig(attributeName, attributeValue)
                || isExcludedRequestAttributeByAnnotation(attributeValue)
                || isExcludedRequestAttributeByNamespace(attributeName)
                || isExcludedRequestAttributeByInstance(attributeName, attributeValue)
                || isExcludedRequestAttributeByPreExisting(attributeName)) {

              logger.trace("NOT saving EXCLUDED attribute name=[{0}]", attributeName);
            } else {

              if (saveNonExcludedAttributes) {
                logger.trace(
                    "SAVING non-excluded request attribute name=[{0}] value=[{1}]",
                    attributeName, attributeValue);
                savedRequestAttributes.add(new RequestAttribute(attributeName, attributeValue));
              }

              nonExcludedAttributeNames.add(attributeName);
            }
          }

          if (savedRequestAttributes.size() > 0) {
            setAttribute(BRIDGE_REQ_SCOPE_ATTR_REQUEST_ATTRIBUTES, savedRequestAttributes);
          } else {
            logger.trace("Not saving any non-excluded request attributes");
          }

          setAttribute(BRIDGE_REQ_SCOPE_NON_EXCLUDED_ATTR_NAMES, nonExcludedAttributeNames);
        }
      } else {
        logger.trace(
            "Not saving any non-excluded request attributes because there are no request attributes!");
      }
    }

    // If running in the ACTION_PHASE or EVENT_PHASE, then the Flash scope must be saved as well so
    // that it can be
    // restored.
    Bridge.PortletPhase portletRequestPhase = bridgeContext.getPortletRequestPhase();

    if ((portletRequestPhase == Bridge.PortletPhase.ACTION_PHASE)
        || (portletRequestPhase == Bridge.PortletPhase.EVENT_PHASE)) {

      // PROPOSED-FOR-JSR344-API: http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1070
      // PROPOSED-FOR-BRIDGE3-API: https://issues.apache.org/jira/browse/PORTLETBRIDGE-201
      saveFlashState(facesContext);
    }

    // If running in the ACTION_PHASE or EVENT_PHASE, then the incongruity context must be saved as
    // well so that it
    // can be restored.
    if ((portletRequestPhase == Bridge.PortletPhase.ACTION_PHASE)
        || (portletRequestPhase == Bridge.PortletPhase.EVENT_PHASE)) {

      IncongruityContext incongruityContext = bridgeContext.getIncongruityContext();
      Map<String, Object> incongruityAttributeMap = incongruityContext.getAttributes();
      int mapSize = incongruityAttributeMap.size();
      List<IncongruityAttribute> savedIncongruityAttributes =
          new ArrayList<IncongruityAttribute>(mapSize);
      Iterator<Map.Entry<String, Object>> itr = incongruityAttributeMap.entrySet().iterator();

      while (itr.hasNext()) {
        Map.Entry<String, Object> mapEntry = itr.next();
        String name = mapEntry.getKey();
        Object value = mapEntry.getValue();
        logger.trace("Saving IncongruityContext attribute name=[{0}] value=[{1}]", name, value);
        savedIncongruityAttributes.add(new IncongruityAttribute(name, value));
      }

      setAttribute(
          BRIDGE_REQ_SCOPE_ATTR_INCONGRUITY_CONTEXT_ATTRIBUTES, savedIncongruityAttributes);
    }
  }