Ejemplo n.º 1
0
  protected Iterator getMessageIter(
      FacesContext context, String forComponent, UIComponent component) {

    Iterator messageIter;
    // Attempt to use the "for" attribute to locate
    // messages.  Three possible scenarios here:
    // 1. valid "for" attribute - messages returned
    //    for valid component identified by "for" expression.
    // 2. zero length "for" expression - global errors
    //    not associated with any component returned
    // 3. no "for" expression - all messages returned.
    if (null != forComponent) {
      if (forComponent.length() == 0) {
        messageIter = context.getMessages(null);
      } else {
        UIComponent result = getForComponent(context, forComponent, component);
        if (result == null) {
          messageIter = Collections.EMPTY_LIST.iterator();
        } else {
          messageIter = context.getMessages(result.getClientId(context));
        }
      }
    } else {
      messageIter = context.getMessages();
    }
    return messageIter;
  }
 private Iterator<MessageForRender> getMessagesForId(FacesContext context, String clientId) {
   Iterator<MessageForRender> msgIter;
   msgIter =
       Iterators.transform(
           context.getMessages(clientId),
           new MessageTransformer(null == clientId ? "" : clientId));
   return msgIter;
 }
Ejemplo n.º 3
0
  private void printMessages(FacesContext context) {

    final Iterator<FacesMessage> messages = context.getMessages();
    while (messages.hasNext()) {
      final FacesMessage facesMessage = messages.next();
      logMessage(facesMessage);
    }
  }
Ejemplo n.º 4
0
  @Override
  public void encodeEnd(FacesContext facesContext, UIComponent component) throws IOException {
    if (!component.isRendered()) {
      return;
    }

    Growl uiGrowl = (Growl) component;
    ResponseWriter writer = facesContext.getResponseWriter();

    String clientId = uiGrowl.getClientId(facesContext);
    Iterator<FacesMessage> allMessages =
        uiGrowl.isGlobalOnly() ? facesContext.getMessages(null) : facesContext.getMessages();
    Map<String, List<FacesMessage>> messages = new HashMap<String, List<FacesMessage>>();
    messages.put("info", new ArrayList<FacesMessage>()); // Bootstrap info
    messages.put("warn", new ArrayList<FacesMessage>()); // Bootstrap warning
    messages.put("error", new ArrayList<FacesMessage>()); // Bootstrap Error
    messages.put("fatal", new ArrayList<FacesMessage>()); // Bootstrap Success

    while (allMessages.hasNext()) {

      FacesMessage message = allMessages.next();
      Severity severity = message.getSeverity();
      if (message.isRendered() && !uiGrowl.isRedisplay()) {
        continue;
      }

      if (severity.equals(FacesMessage.SEVERITY_INFO)) messages.get("info").add(message);
      else if (severity.equals(FacesMessage.SEVERITY_WARN)) messages.get("warn").add(message);
      else if (severity.equals(FacesMessage.SEVERITY_ERROR)) messages.get("error").add(message);
      else if (severity.equals(FacesMessage.SEVERITY_FATAL)) messages.get("fatal").add(message);
    }

    writer.startElement("script", uiGrowl);
    writer.writeAttribute("id", clientId, "id");
    writer.writeText("$(function() { ", null);
    for (String severity : messages.keySet()) {
      List<FacesMessage> severityMessages = messages.get(severity);
      if (severityMessages.size() > 0) {
        encodeSeverityMessages(facesContext, uiGrowl, severity, severityMessages);
      }
    }
    writer.writeText("});", null);

    writer.endElement("script");
  }
Ejemplo n.º 5
0
 /**
  * checks if the current context contains an error
  *
  * @param fc the FacesContext
  * @return true if the context has an error set or false otherwise
  */
 public boolean hasError(final FacesContext fc) {
   Iterator<FacesMessage> msgIterator = fc.getMessages();
   if (msgIterator != null) { // Check Messages
     while (msgIterator.hasNext()) { // Check Severity
       Severity fms = msgIterator.next().getSeverity();
       if (fms == FacesMessage.SEVERITY_ERROR || fms == FacesMessage.SEVERITY_FATAL) return true;
     }
   }
   return false;
 }
 private static boolean isInvalid(FacesContext facesContext, String clientId) {
   Iterator<FacesMessage> messages = facesContext.getMessages(clientId);
   while (messages.hasNext()) {
     FacesMessage message = messages.next();
     if (message.getSeverity().getOrdinal() > FacesMessage.SEVERITY_INFO.getOrdinal()) {
       return true;
     }
   }
   return false;
 }
Ejemplo n.º 7
0
  /**
   * Verifica se existe alguma mensagem de erro no {@link FacesMessage}
   *
   * @return <code>true</code> caso exista, e <code>false</code> caso contrário.
   */
  public boolean possuiMensagemErro() {
    Iterator<FacesMessage> messages = facesContext.getMessages();
    while (messages.hasNext()) {
      FacesMessage msg = messages.next();

      if (msg.getSeverity().equals(FacesMessage.SEVERITY_ERROR)) {
        return true;
      }
    }
    return false;
  }
Ejemplo n.º 8
0
  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());
      }
    }
  }
Ejemplo n.º 9
0
  /**
   * Tratamento para verificar se a mensagem já foi inserida no contexto do JSF
   *
   * @param msg
   * @param facesMessage
   */
  @SuppressWarnings("rawtypes")
  private void addMensagemDistinct(String msg, FacesMessage facesMessage) {
    boolean mensagemNova = true;
    for (Iterator iterator = facesContext.getMessages(); iterator.hasNext(); ) {
      FacesMessage message = (FacesMessage) iterator.next();

      if (message.getSummary().equals(msg)) {
        mensagemNova = false;
        break;
      }
    }

    // Só permite a inclusão da mensagem no contexto do JSF uma vez.
    if (mensagemNova) {
      facesContext.addMessage(null, facesMessage);
    }
  }
Ejemplo n.º 10
0
  private void logMessages(FacesContext context) {
    UIViewRoot root = context.getViewRoot();
    String viewId = "";

    if (root != null) viewId = root.getViewId();

    Iterator<FacesMessage> iter = context.getMessages();

    while (iter != null && iter.hasNext()) {
      FacesMessage msg = iter.next();

      if (log.isLoggable(Level.FINE)) {
        if (msg.getDetail() != null)
          log.fine(
              viewId + " [ " + msg.getSeverity() + "] " + msg.getSummary() + " " + msg.getDetail());
        else log.fine(viewId + " [ " + msg.getSeverity() + "] " + msg.getSummary());
      }
    }
  }
  @SuppressWarnings("unchecked")
  private int saveMessages(final FacesContext facesContext) {
    List<FacesMessage> messages = new ArrayList<FacesMessage>();
    for (Iterator<FacesMessage> iter = facesContext.getMessages(null); iter.hasNext(); ) {
      messages.add(iter.next());
      iter.remove();
    }

    if (messages.size() == 0) {
      return 0;
    }

    Map<String, Object> sessionMap = facesContext.getExternalContext().getSessionMap();
    List<FacesMessage> existingMessages = (List<FacesMessage>) sessionMap.get(sessionToken);
    if (existingMessages != null) {
      existingMessages.addAll(messages);
    } else {
      sessionMap.put(sessionToken, messages);
    }
    return messages.size();
  }
 /**
  * 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;
 }
 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;
   }
 }
 private static void appendMessagesForClientId(
     FacesContext facesContext, String clientId, StringBuffer jsTxt) {
   Iterator<FacesMessage> messages = facesContext.getMessages(clientId);
   boolean replaceIds = isReplaceId(facesContext);
   while (messages.hasNext()) {
     FacesMessage message = messages.next();
     if (clientId == null) {
       jsTxt.append("\n{severity:'");
     } else {
       if (replaceIds) {
         replaceIdWithLabel(clientId, message, facesContext);
       }
       jsTxt.append("\n{clientId:'");
       jsTxt.append(clientId);
       jsTxt.append("', severity:'");
     }
     jsTxt.append(message.getSeverity());
     jsTxt.append("', summary:'");
     jsTxt.append(message.getSummary());
     jsTxt.append("', detail:'");
     jsTxt.append(message.getDetail());
     jsTxt.append("'},");
   }
 }
Ejemplo n.º 15
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");
    }
  }
Ejemplo n.º 16
0
  public String valider() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    FacesMessage facesMessage = new FacesMessage();
    String message = null;
    DAO dao = new DAO();
    UserManagement userManagement = new UserManagement();
    construct(userManagement);

    if (userPassword != null && userPassword.trim() != "") {

      if (!(userName.length() > 0)) {

        BuildMessage.addMessage(
            null, "User validation: ", "Sorry, user name is required", FacesMessage.SEVERITY_ERROR);
        return null;
      }
      if (userPassword.length() < 8) {

        BuildMessage.addMessage(
            null,
            "Password validation: ",
            "Sorry, user password is invalid",
            FacesMessage.SEVERITY_ERROR);
        return null;
      }
      if (ipAddress != null && ipAddress.trim() == "" && ipAddressMang.equals("Y")) {

        BuildMessage.addMessage(
            null,
            "IP management: ",
            "Sorry, User IP address is required",
            FacesMessage.SEVERITY_ERROR);
        return null;
      }

      if (!(dateEndPass != null) && expirationMang.equals('Y')) {

        BuildMessage.addMessage(
            null,
            "Password management: ",
            "Sorry, Expiry date for password is required",
            FacesMessage.SEVERITY_ERROR);
        return null;
      }

      if (validate) {

        if (checkExistRecord(UserManagement.class, userManagement.getUserCode())) {
          returnMessageIfExistRecord(
              "UserManagement ", userManagement.getUserCode(), userManagement.getUserName());
        } else {
          dao.save(userManagement);
          facesContext.getMessages();
          returnMessageBeforeTrx(
              "User ",
              userManagement.getUserCode(),
              userManagement.getUserName(),
              dao.isSuccessOperation(),
              'I');
          attributeConnecteRole(userManagement);
          if (userManagement.getUserType().equals("S")) {
            attributeSupervisorRole1(userManagement);
            attributeSupervisorRole2(userManagement);
          }
        }

        dao.getSession().flush();
        UserParamSearchBB.actionDone = true;
      }

    } else {

      BuildMessage.addMessage(
          null,
          "Password validation: ",
          "Sorry, user password is invalid",
          FacesMessage.SEVERITY_ERROR);
      return null;
    }
    return null;
  }
  /**
   * 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);
    }
  }
  /**
   * 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);
  }