/**
   * Set the value of a scoped object for the specified name.
   *
   * @param context <code>ELContext</code> for evaluating this value
   * @param base Base object against which this evaluation occurs (must be null because we are
   *     evaluating a top level variable)
   * @param property Property name to be accessed
   * @param value New value to be set
   */
  public void setValue(ELContext context, Object base, Object property, Object value) {

    if (base != null) {
      return;
    }
    if (property == null) {
      throw new PropertyNotFoundException("No property specified");
    }

    context.setPropertyResolved(true);
    String key = property.toString();
    Object result = null;
    FacesContext fcontext = (FacesContext) context.getContext(FacesContext.class);
    ExternalContext econtext = fcontext.getExternalContext();

    if (econtext.getRequestMap().containsKey(property)) {
      econtext.getRequestMap().put(key, value);
    } else if (econtext.getSessionMap().containsKey(property)) {
      econtext.getSessionMap().put(key, value);
    } else if (econtext.getApplicationMap().containsKey(property)) {
      econtext.getApplicationMap().put(key, value);
    } else {
      econtext.getRequestMap().put(key, value);
    }
  }
Example #2
0
  /**
   * Perform actions that need to happen on the <code>afterPhase</code> event.
   *
   * <p>For after restore-view, if this is a postback, we extract the sequenceId from the request
   * and store it in the request scope.
   *
   * <p>For after render-response, we clear out the flash for the postback, while leaving the
   * current one intact.
   */
  public void afterPhase(PhaseEvent e) {
    FacesContext context = e.getFacesContext();
    ExternalContext extContext = context.getExternalContext();
    Map<String, Object> requestMap = extContext.getRequestMap();
    Object request = extContext.getRequest(), response = extContext.getResponse();
    ELFlash elFlash = ELFlash.getELFlash();

    if (e.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
      expireEntries(context);
    }

    // If this requset is ending normally...
    if (e.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
      // and the user requested we save all request scoped data...
      if (null != elFlash && elFlash.isKeepMessages()) {
        // save it all.
        elFlash.saveAllMessages(context);
      }
    }
    // Otherwise, if this request is ending early...
    else if ((context.getResponseComplete() || context.getRenderResponse())
        && elFlash.isRedirect()) {
      // and the user requested we save all request scoped data...
      if (null != elFlash && elFlash.isKeepMessages()) {
        // save it all.
        addCookie(extContext, elFlash);
        elFlash.saveAllMessages(context);
      }
    }
  }
  /**
   * Return an existing scoped object for the specified name (if any); otherwise, return <code>null
   * </code>.
   *
   * @param context <code>ELContext</code> for evaluating this value
   * @param base Base object against which this evaluation occurs (must be null because we are
   *     evaluating a top level variable)
   * @param property Property name to be accessed
   */
  public Object getValue(ELContext context, Object base, Object property) {

    if (base != null) {
      return null;
    }
    if (property == null) {
      throw new PropertyNotFoundException("No property specified");
    }

    FacesContext fcontext = (FacesContext) context.getContext(FacesContext.class);
    ExternalContext econtext = fcontext.getExternalContext();
    Object value = null;
    value = econtext.getRequestMap().get(property);
    if (value != null) {
      context.setPropertyResolved(true);
      return value;
    }
    value = econtext.getSessionMap().get(property);
    if (value != null) {
      context.setPropertyResolved(true);
      return value;
    }
    value = econtext.getApplicationMap().get(property);
    if (value != null) {
      context.setPropertyResolved(true);
      return value;
    }

    return null;
  }
Example #4
0
  private void addCookie(ExternalContext extContext, Flash flash) {
    // Do not update the cookie if redirect after post
    if (flash.isRedirect()) {
      return;
    }

    String thisRequestSequenceString = null;
    HttpServletResponse servletResponse = null;
    // PortletRequest portletRequest = null;
    Object thisRequestSequenceStringObj, response = extContext.getResponse();

    thisRequestSequenceStringObj =
        extContext.getRequestMap().get(Constants.FLASH_THIS_REQUEST_ATTRIBUTE_NAME);
    if (null == thisRequestSequenceStringObj) {
      return;
    }
    thisRequestSequenceString = thisRequestSequenceStringObj.toString();

    if (response instanceof HttpServletResponse) {
      servletResponse = (HttpServletResponse) response;
      Cookie cookie =
          new Cookie(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME, thisRequestSequenceString);
      cookie.setMaxAge(-1);
      servletResponse.addCookie(cookie);
    } else {
      /**
       * *** portletRequest = (PortletRequest) request; // You can't add a cookie in portlet. //
       * http://wiki.java.net/bin/view/Portlet/JSR168FAQ#How_can_I_set_retrieve_a_cookie
       * portletRequest.getPortletSession().setAttribute(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME,
       * thisRequestSequenceString, PortletSession.PORTLET_SCOPE); *******
       */
    }
  }
Example #5
0
 private void decodeScrollPosTracking(FacesContext facesContext) {
   if (!isAutoScrollPosTrackingEnabled(facesContext)) return;
   ExternalContext externalContext = facesContext.getExternalContext();
   Map<String, String> requestParameterMap = externalContext.getRequestParameterMap();
   String focusedComponentId = requestParameterMap.get(SCROLL_POS_TRACKER_FIELD_ID);
   Map<String, Object> requestMap = externalContext.getRequestMap();
   requestMap.put(SCROLL_POS_KEY, focusedComponentId);
 }
Example #6
0
 private void decodeFocusTracking(FacesContext facesContext) {
   if (!isAutoFocusTrackingEnabled(facesContext)) return;
   ExternalContext externalContext = facesContext.getExternalContext();
   Map<String, String> requestParameterMap = externalContext.getRequestParameterMap();
   String focusedComponentId = requestParameterMap.get(FOCUS_TRACKER_FIELD_ID);
   Map<String, Object> requestMap = externalContext.getRequestMap();
   requestMap.put(FOCUSED_COMPONENT_ID_KEY, focusedComponentId);
 }
Example #7
0
  @PostConstruct
  public void init() {
    ExternalContext externalContext = getContext().getExternalContext();
    originalURL =
        (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);
    if (originalURL == null) {
      originalURL =
          getCurrentUri(); // externalContext.getRequestContextPath() + "/pages/home.xhtml";
    } else {
      String originalQuery =
          (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);

      if (originalQuery != null) {
        originalURL += "?" + originalQuery;
      }
    }
  }
Example #8
0
 private static Script encodeScrollPosTracking(FacesContext facesContext) {
   ExternalContext externalContext = facesContext.getExternalContext();
   Map requestMap = externalContext.getRequestMap();
   String scrollPos = (String) requestMap.get(SCROLL_POS_KEY);
   return new ScriptBuilder()
       .functionCall(
           "O$.initDefaultScrollPosition",
           SCROLL_POS_TRACKER_FIELD_ID,
           scrollPos != null ? scrollPos : null)
       .semicolon();
 }
Example #9
0
 private static Script encodeFocusTracking(FacesContext facesContext) {
   ExternalContext externalContext = facesContext.getExternalContext();
   Map requestMap = externalContext.getRequestMap();
   String focusedComponentId = (String) requestMap.get(FOCUSED_COMPONENT_ID_KEY);
   return new ScriptBuilder()
       .functionCall(
           "O$.initDefaultFocus",
           FOCUS_TRACKER_FIELD_ID,
           focusedComponentId != null ? focusedComponentId : null)
       .semicolon();
 }
Example #10
0
 private void addSessionExpirationFlagUnderPortlets(FacesContext context, UIViewRoot root) {
   ExternalContext externalContext = context.getExternalContext();
   Map<String, Object> requestMap = externalContext.getRequestMap();
   if (!requestMap.containsKey(SESSION_EXPIRATION_PROCESSING)) {
     requestMap.put(SESSION_EXPIRATION_PROCESSING, Boolean.TRUE);
   }
   if (!requestMap.containsKey(LOCATION_HEADER)) {
     String actionURL = getActionURL(context, root.getViewId());
     actionURL = externalContext.encodeActionURL(actionURL);
     requestMap.put(LOCATION_HEADER, actionURL);
   }
 }
Example #11
0
  @Override
  public UIViewRoot createView(FacesContext context, String viewId) {
    UIViewRoot root = null;

    try {
      root = super.createView(context, viewId);
    } catch (RuntimeException e) {
      if (AjaxUtil.isAjaxRequest(context)) {
        // If exception was caught during our ajax request then we need to process it
        // and send ajax response with details about exception.
        CommonAjaxViewRoot.processExceptionDuringAjax(context, e);
        Log.log(context, e.getMessage(), e);
      } else {
        // We need to rethrow exception.
        throw new RuntimeException(e);
      }
    } catch (Error e) {
      if (AjaxUtil.isAjaxRequest(context)) {
        // If exception was caught during our ajax request then we need to process it
        // and send ajax response with details about exception.
        CommonAjaxViewRoot.processExceptionDuringAjax(context, e);
        Log.log(context, e.getMessage(), e);
      } else {
        // We need to rethrow exception.
        throw new Error(e);
      }
    }

    // If created instance of UIViewRoot does not implement our interface WrappedAjaxRoot
    // then we need to wrap it with our AjaxViewRoot
    UIViewRoot riRoot;
    if (null == root || root instanceof WrappedAjaxRoot) {
      riRoot = root;
    } else {
      riRoot = getAjaxViewRoot(root, context);
    }

    ExternalContext externalContext = context.getExternalContext();
    Map<String, String> requestParameterMap = externalContext.getRequestParameterMap();
    Map<String, Object> requestMap = externalContext.getRequestMap();
    if (requestParameterMap.containsKey("of_sessionExpiration")
        && requestParameterMap.containsKey(AjaxUtil.AJAX_REQUEST_MARKER)) {
      if (!requestMap.containsKey(SESSION_EXPIRATION_PROCESSING)) {
        requestMap.put(SESSION_EXPIRATION_PROCESSING, Boolean.TRUE);

        String actionURL = getActionURL(context, viewId);
        actionURL = externalContext.encodeActionURL(actionURL);
        requestMap.put(LOCATION_HEADER, actionURL);
      }
    }

    return riRoot;
  }
Example #12
0
  /**
   * @param context the {@link FacesContext} for the current request
   * @return a {@link ResponseWriter} for processing the request
   * @throws IOException if the writer cannot be created
   */
  protected ResponseWriter createResponseWriter(FacesContext context) throws IOException {

    ExternalContext extContext = context.getExternalContext();
    RenderKit renderKit = context.getRenderKit();
    // Avoid a cryptic NullPointerException when the renderkit ID
    // is incorrectly set
    if (renderKit == null) {
      String id = context.getViewRoot().getRenderKitId();
      throw new IllegalStateException("No render kit was available for id \"" + id + "\"");
    }

    if (responseBufferSizeSet) {
      // set the buffer for content
      extContext.setResponseBufferSize(responseBufferSize);
    }

    // get our content type
    String contentType = (String) extContext.getRequestMap().get("facelets.ContentType");

    // get the encoding
    String encoding = (String) extContext.getRequestMap().get("facelets.Encoding");

    // Create a dummy ResponseWriter with a bogus writer,
    // so we can figure out what content type the ReponseWriter
    // is really going to ask for
    ResponseWriter writer =
        renderKit.createResponseWriter(NullWriter.Instance, contentType, encoding);

    contentType = getResponseContentType(context, writer.getContentType());
    encoding = getResponseEncoding(context, writer.getCharacterEncoding());

    // apply them to the response
    extContext.setResponseContentType(contentType);
    extContext.setResponseCharacterEncoding(encoding);

    // Now, clone with the real writer
    writer = writer.cloneWithWriter(extContext.getResponseOutputWriter());

    return writer;
  }
Example #13
0
  /**
   * Perform actions that need to happen on the <code>beforePhase</code> event.
   *
   * <p>For all phases, store the current phaseId in request scope.
   *
   * <p>For before restore-view, create a sequenceId for this request and store it in request scope.
   *
   * <p>For before render-response, store the sequenceId for this request in the response.
   */
  public void beforePhase(PhaseEvent e) {
    FacesContext context = e.getFacesContext();
    ExternalContext extContext = context.getExternalContext();
    Object response = extContext.getResponse();
    Map<String, Object> requestMap = extContext.getRequestMap();
    String thisRequestSequenceString = null;
    String postbackSequenceString = null;
    ELFlash elFlash = (ELFlash) ELFlash.getFlash(context, true);

    // If we're on before-restore-view...
    if (e.getPhaseId().equals(PhaseId.RESTORE_VIEW)) {
      thisRequestSequenceString = Long.toString(getSequenceNumber());
      // Put the sequence number for the request/response pair
      // that is starting with *this particular request* in the request scope
      // so the ELFlash can access it.
      requestMap.put(Constants.FLASH_THIS_REQUEST_ATTRIBUTE_NAME, thisRequestSequenceString);

      // Make sure to restore all request scoped data
      if (null != elFlash && elFlash.isKeepMessages()) {
        elFlash.restoreAllMessages(context);
      }

      if (context.isPostback()) {
        // to a servlet JSF app...
        if (response instanceof HttpServletResponse) {
          // extract the sequence number from the cookie or portletSession
          // for the request/response pair for which this request is a postback.
          postbackSequenceString = getCookieValue(extContext);
        } else {
          /**
           * **** PortletRequest portletRequest = null; portletRequest = (PortletRequest) request;
           * // You can't retrieve a cookie in portlet. //
           * http://wiki.java.net/bin/view/Portlet/JSR168FAQ#How_can_I_set_retrieve_a_cookie
           * postbackSequenceString = (String) portletRequest.getPortletSession().
           * getAttribute(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME,
           * PortletSession.PORTLET_SCOPE); *****
           */
        }
        if (null != postbackSequenceString) {
          // Store the sequenceNumber in the request so the
          // after-render-response event can flush the flash
          // of entries from that sequence
          requestMap.put(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME, postbackSequenceString);
        }
      }
    }
    if (e.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
      // Set the REQUEST_ID cookie to be the sequence number
      addCookie(extContext, elFlash);
    }
  }
Example #14
0
 private void expireEntries(FacesContext context) {
   ExternalContext extContext = context.getExternalContext();
   String postbackSequenceString = null;
   // Clear out the flash for the postback.
   if (null
       != (postbackSequenceString =
           (String)
               extContext.getRequestMap().get(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME))) {
     ELFlash flash = (ELFlash) ELFlash.getFlash(context, false);
     if (null != flash) {
       flash.expireEntriesForSequence(postbackSequenceString);
     }
   }
 }
Example #15
0
  /*
   * This method checks is session new or not.
   * In servlet environment we use servlet-api for this checking.
   * In portlet environment we checks by our custom session scoped parameter.
   * If session is new - it shouldn't contain our custom parameter.
   *
   * @param httpSession - current session
   */
  @SuppressWarnings({"ChainOfInstanceofChecks"})
  public static boolean isNewSession(Object httpSession) {
    if (httpSession instanceof HttpSession) {
      return ((HttpSession) httpSession).isNew();
    } else if (httpSession instanceof PortletSession) {
      ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
      if (Environment.isLiferay(externalContext.getRequestMap())) {
        Map<String, Object> sessionMap = externalContext.getSessionMap();
        return sessionMap != null && !sessionMap.containsKey(SESSION_SCOPED_PARAMETER);
      }

      Map<String, Object> sessionMap = externalContext.getSessionMap();
      return sessionMap != null && !sessionMap.containsKey(SESSION_SCOPED_PARAMETER);
    }
    return false;
  }
Example #16
0
  public static boolean isPostBack() {
    ExternalContext ext = FacesUtils.extContext();
    boolean result = false;
    Map<String, Object> requestMap = ext.getRequestMap();
    Object value = requestMap.get(VIEW_STATE_KEY);
    if (!Strings.isEmpty(value)) {
      return true;
    }

    Map<String, String> params = ext.getRequestParameterMap();
    value = params.get(VIEW_STATE_KEY);
    if (!Strings.isEmpty(value)) {
      requestMap.put(VIEW_STATE_KEY, Boolean.TRUE);
      result = true;
    }
    return result;
  }
Example #17
0
  private static boolean symbolParam(String key) {
    ExternalContext ext = FacesUtils.extContext();
    boolean result = false;
    Map<String, Object> requestMap = ext.getRequestMap();
    Object value = requestMap.get(key);
    if (value != null && "true".equalsIgnoreCase(value.toString())) {
      return true;
    }

    Map<String, String> params = ext.getRequestParameterMap();
    value = params.get(key);
    if (value != null && "true".equalsIgnoreCase(value.toString())) {
      requestMap.put(key, Boolean.TRUE);
      result = true;
    }
    return result;
  }
Example #18
0
 protected Object addSearchDocumentToELContext(FacesContext facesContext) {
   ExternalContext econtext = null;
   if (facesContext != null) {
     econtext = facesContext.getExternalContext();
   }
   if (facesContext == null || econtext == null) {
     log.error(
         "JSF context is null: cannot expose variable '"
             + SEARCH_DOCUMENT_EL_VARIABLE
             + "' for content view '"
             + getName()
             + "'");
     return null;
   }
   Map<String, Object> requestMap = econtext.getRequestMap();
   Object previousValue = requestMap.get(SEARCH_DOCUMENT_EL_VARIABLE);
   requestMap.put(SEARCH_DOCUMENT_EL_VARIABLE, searchDocumentModel);
   return previousValue;
 }
Example #19
0
  public static void renderScript(
      FacesContext facesContext, UIComponent uiComponent, String script, String use) {

    // Render the script at the bottom of the page by setting the WebKeys.AUI_SCRIPT_DATA request
    // attribute.
    ExternalContext externalContext = facesContext.getExternalContext();
    ClientScriptFactory clientScriptFactory =
        (ClientScriptFactory) FactoryExtensionFinder.getFactory(ClientScriptFactory.class);
    ClientScript clientScript = clientScriptFactory.getClientScript(externalContext);

    String portletId = StringPool.BLANK;
    Object portlet = externalContext.getRequestMap().get(WebKeys.RENDER_PORTLET);

    if (portlet != null) {
      portletId = LiferayPortletUtil.getPortletId(portlet);
    }

    clientScript.append(portletId, script, use);
  }
Example #20
0
 protected void removeSearchDocumentFromELContext(
     FacesContext facesContext, Object previousValue) {
   if (facesContext == null) {
     // ignore
     return;
   }
   ExternalContext econtext = facesContext.getExternalContext();
   if (econtext != null) {
     Map<String, Object> requestMap = econtext.getRequestMap();
     requestMap.remove(SEARCH_DOCUMENT_EL_VARIABLE);
     if (previousValue != null) {
       requestMap.put(SEARCH_DOCUMENT_EL_VARIABLE, previousValue);
     }
   } else {
     log.error(
         "External context is null: cannot dispose variable '"
             + SEARCH_DOCUMENT_EL_VARIABLE
             + "' for content view '"
             + getName()
             + "'");
   }
 }
  @PostConstruct
  public void init() {
    serviceDAO = new ServiceDAO();
    ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
    // originalURL = (String)
    // externalContext.getRequestMap().get(RequestDispatcher.FORWARD_REQUEST_URI);

    originalURL = (String) externalContext.getRequestHeaderMap().get("referer");

    if (originalURL == null) {
      originalURL = externalContext.getRequestContextPath() + "/index.jsf";
    } else {
      String originalQuery =
          (String) externalContext.getRequestMap().get(RequestDispatcher.FORWARD_QUERY_STRING);

      if (originalQuery != null) {
        originalURL += "?" + originalQuery;
      }
    }

    // log.debug("originalURL==>" + originalURL);
  }
Example #22
0
 /**
  * Returns <code>true</code> if the {@link #disableConfiguratorServices(ServletRequest)} has been
  * executed on the current request and <code>false</code> if it has not.
  *
  * <p><strong>Note:</strong>it is important to understand that this method will not properly
  * reflect if the services have actually been disabled or not. It simply returns whether they
  * "should" have been disabled. If the disableConfiguratorServices was executed after the
  * beginRequest methods have been executed, then the services will continue to function so that
  * {{@link #getExternalContext(ExternalContext)} and {@link #endRequest(ExternalContext)} will
  * still be called.
  *
  * @param ec the ExternalContext object
  * @return a <code>boolean</code> containing <code>true</code> if the <code>
  *     disableConfiguratorServices()</code> method has been called and <code>false</code> if it
  *     has not.
  */
 protected static final boolean isConfiguratorServiceDisabled(ExternalContext ec) {
   return Boolean.TRUE.equals(ec.getRequestMap().get(_DISABLE_SERVICES));
 }
  /**
   * Return an <code>Iterator</code> over the attributes that this resolver knows how to deal with.
   *
   * @param context <code>ELContext</code> for evaluating this value
   * @param base Base object against which this evaluation occurs
   */
  public Iterator getFeatureDescriptors(ELContext context, Object base) {

    if (base != null) {
      return null;
    }

    // Create the variables we will need
    FacesContext fcontext = (FacesContext) context.getContext(FacesContext.class);
    ExternalContext econtext = fcontext.getExternalContext();
    List descriptors = new ArrayList();
    Map map = null;
    Set set = null;
    Iterator items = null;
    String key = null;
    Object value = null;

    // Add feature descriptors for request scoped attributes
    set = econtext.getRequestMap().entrySet();
    items = set.iterator();
    while (items.hasNext()) {
      Entry item = (Entry) items.next();
      key = (String) item.getKey();
      value = item.getValue();
      descriptors.add(
          descriptor(
              key,
              key,
              "Request Scope Attribute " + key,
              false,
              false,
              true,
              value.getClass(),
              true));
    }

    // Add feature descriptors for session scoped attributes
    set = econtext.getSessionMap().entrySet();
    items = set.iterator();
    while (items.hasNext()) {
      Entry item = (Entry) items.next();
      key = (String) item.getKey();
      value = item.getValue();
      descriptors.add(
          descriptor(
              key,
              key,
              "Session Scope Attribute " + key,
              false,
              false,
              true,
              value.getClass(),
              true));
    }

    // Add feature descriptors for application scoped attributes
    set = econtext.getApplicationMap().entrySet();
    items = set.iterator();
    while (items.hasNext()) {
      Entry item = (Entry) items.next();
      key = (String) item.getKey();
      value = item.getValue();
      descriptors.add(
          descriptor(
              key,
              key,
              "Application Scope Attribute " + key,
              false,
              false,
              true,
              value.getClass(),
              true));
    }

    // Return the accumulated descriptors
    return descriptors.iterator();
  }
  /**
   * 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);
    }
  }
Example #25
0
 @Produces
 @RequestMap
 public Map<String, Object> getRequestMap(ExternalContext externalContext) {
   return externalContext.getRequestMap();
 }
  protected void execute(String renderRedirectViewId) throws BridgeException, IOException {

    init(renderRequest, renderResponse, Bridge.PortletPhase.RENDER_PHASE);

    // If the portlet mode has not changed, then restore the faces view root and messages that would
    // have been saved during the ACTION_PHASE of the portlet lifecycle. Section 5.4.1 requires that
    // the
    // BridgeRequestScope must not be restored if there is a change in portlet modes detected.
    boolean facesLifecycleExecuted = bridgeRequestScope.isFacesLifecycleExecuted();
    bridgeRequestScope.restoreState(facesContext);

    if (bridgeRequestScope.isPortletModeChanged()) {
      bridgeRequestScopeCache.remove(bridgeRequestScope.getId());
    }

    // If a render-redirect URL was specified, then it is necessary to create a new view from the
    // URL and place it
    // in the FacesContext.
    if (renderRedirectViewId != null) {
      renderRequest.setAttribute(BridgeExt.RENDER_REDIRECT_AFTER_DISPATCH, Boolean.TRUE);

      ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
      UIViewRoot uiViewRoot = viewHandler.createView(facesContext, renderRedirectViewId);
      facesContext.setViewRoot(uiViewRoot);
      logger.debug("Performed render-redirect to viewId=[{0}]", renderRedirectViewId);
    }

    // NOTE: PROPOSE-FOR-BRIDGE3-API Actually, the proposal would be to REMOVE
    // Bridge.IS_POSTBACK_ATTRIBUTE from the Bridge API, because JSF 2.0 introduced the
    // FacesContext#isPostBack() method.
    // http://javaserverfaces.java.net/nonav/docs/2.0/javadocs/javax/faces/context/FacesContext.html#isPostback()
    if (bridgeRequestScope.getBeganInPhase() == Bridge.PortletPhase.ACTION_PHASE) {

      ExternalContext externalContext = facesContext.getExternalContext();
      externalContext.getRequestMap().put(Bridge.IS_POSTBACK_ATTRIBUTE, Boolean.TRUE);
    }

    logger.debug(
        "portletName=[{0}] facesLifecycleExecuted=[{1}]", portletName, facesLifecycleExecuted);

    // If the JSF lifecycle executed back in the ACTION_PHASE of the portlet lifecycle, then
    if (facesLifecycleExecuted) {

      // TCK TestPage054: prpUpdatedFromActionTest
      PhaseEvent restoreViewPhaseEvent =
          new PhaseEvent(facesContext, PhaseId.RESTORE_VIEW, facesLifecycle);
      PhaseListener[] phaseListeners = facesLifecycle.getPhaseListeners();

      for (PhaseListener phaseListener : phaseListeners) {

        if (phaseListener instanceof IPCPhaseListener) {
          phaseListener.afterPhase(restoreViewPhaseEvent);

          break;
        }
      }
    }

    // Otherwise, in accordance with Section 5.2.6 of the Spec, execute the JSF lifecycle so that
    // ONLY the
    // RESTORE_VIEW phase executes. Note that this is accomplished by the
    // RenderRequestPhaseListener.
    else {

      try {
        ExternalContext externalContext = facesContext.getExternalContext();
        String viewId = getFacesViewId(externalContext);
        logger.debug("Executing Faces lifecycle for viewId=[{0}]", viewId);
      } catch (BridgeException e) {
        logger.error("Unable to get viewId due to {0}", e.getClass().getSimpleName());
        throw e;
      }

      // Attach the JSF 2.2 client window to the JSF lifecycle so that Faces Flows can be utilized.
      attachClientWindowToLifecycle(facesContext, facesLifecycle);

      // Execute the JSF lifecycle.
      facesLifecycle.execute(facesContext);
    }

    // If there were any "handled" exceptions queued, then throw a BridgeException.
    Throwable handledException = getJSF2HandledException(facesContext);

    if (handledException != null) {
      throw new BridgeException(handledException);
    }

    // Otherwise, if there were any "unhandled" exceptions queued, then throw a BridgeException.
    Throwable unhandledException = getJSF2UnhandledException(facesContext);

    if (unhandledException != null) {
      throw new BridgeException(unhandledException);
    }

    // Otherwise, if the PortletMode has changed, and a navigation-rule hasn't yet fired (which
    // could have happened
    // in the EVENT_PHASE), then switch to the appropriate PortletMode and navigate to the current
    // viewId in the
    // UIViewRoot.
    if (bridgeRequestScope.isPortletModeChanged() && !bridgeRequestScope.isNavigationOccurred()) {
      BridgeNavigationHandler bridgeNavigationHandler = getBridgeNavigationHandler(facesContext);
      PortletMode fromPortletMode = bridgeRequestScope.getPortletMode();
      PortletMode toPortletMode = renderRequest.getPortletMode();
      bridgeNavigationHandler.handleNavigation(facesContext, fromPortletMode, toPortletMode);
    }

    // Determines whether or not lifecycle incongruities should be managed.
    boolean manageIncongruities =
        PortletConfigParam.ManageIncongruities.getBooleanValue(portletConfig);

    // Now that we're executing the RENDER_PHASE of the Portlet lifecycle, before the JSF
    // RENDER_RESPONSE phase is executed, we have to fix some incongruities between the Portlet
    // lifecycle and the JSF lifecycle that may have occurred during the ACTION_PHASE of the Portlet
    // lifecycle.
    if (manageIncongruities) {
      incongruityContext.makeCongruous(facesContext);
    }

    // Execute the RENDER_RESPONSE phase of the faces lifecycle.
    logger.debug("Executing Faces render");
    facesLifecycle.render(facesContext);

    // Set the view history according to Section 5.4.3 of the Bridge Spec.
    setViewHistory(facesContext.getViewRoot().getViewId());

    // Spec 6.6 (Namespacing)
    indicateNamespacingToConsumers(facesContext.getViewRoot(), renderResponse);

    // If a render-redirect occurred, then
    ExternalContext externalContext = facesContext.getExternalContext();
    Writer writer = getResponseOutputWriter(externalContext);

    Map<String, Object> requestMap = externalContext.getRequestMap();
    Boolean renderRedirect = (Boolean) requestMap.remove(BridgeExt.RENDER_REDIRECT);

    if ((renderRedirect != null) && renderRedirect) {

      // Cleanup the old FacesContext since a new one will be created in the recursive method call
      // below.
      facesContext.responseComplete();
      facesContext.release();

      // If the render-redirect standard feature is enabled in web.xml or portlet.xml, then the
      // ResponseOutputWriter has buffered up markup that must be discarded. This is because we
      // don't want the
      // markup from the original Faces view to be included with the markup of Faces view found in
      // the
      // redirect URL.
      if (writer instanceof RenderRedirectWriter) {
        RenderRedirectWriter responseOutputWriter = (RenderRedirectWriter) writer;
        responseOutputWriter.discard();
      }

      // Recursively call this method with the render-redirect URL so that the RENDER_RESPONSE phase
      // of the
      // JSF lifecycle will be re-executed according to the new Faces viewId found in the redirect
      // URL.
      renderRedirectViewId = (String) requestMap.remove(BridgeExt.RENDER_REDIRECT_VIEW_ID);

      execute(renderRedirectViewId);
    }

    // Otherwise,
    else {

      // In the case that a render-redirect took place, need to render the buffered markup to the
      // response.
      if (writer instanceof RenderRedirectWriter) {
        RenderRedirectWriter responseOutputWriter = (RenderRedirectWriter) writer;
        responseOutputWriter.render();
      }
    }
  }
  @Override
  public String getWindowId(FacesContext facesContext) {
    ExternalContext externalContext = facesContext.getExternalContext();
    Map<String, Object> requestMap = externalContext.getRequestMap();

    // try to lookup from cache
    String windowId = (String) requestMap.get(WINDOW_ID_REQUEST_MAP_KEY);
    if (windowId != null) {
      return windowId;
    }

    ClientWindowRenderMode clientWindowRenderMode =
        clientWindowConfig.getClientWindowRenderMode(facesContext);
    if (ClientWindowRenderMode.NONE.equals(clientWindowRenderMode)) {
      // if this request should not get any window detection then we are done
      windowId = DEFAULT_WINDOW_ID;
    } else if (ClientWindowRenderMode.DELEGATED.equals(clientWindowRenderMode)) {
      windowId = ClientWindowAdapter.getWindowIdFromJsf(facesContext);
    } else if (ClientWindowRenderMode.LAZY.equals(clientWindowRenderMode)) {
      windowId = ClientWindowHelper.getInitialRedirectWindowId(facesContext);

      if (StringUtils.isEmpty(windowId)) {
        windowId = externalContext.getRequestParameterMap().get(DELTASPIKE_WINDOW_ID_URL_PARAM);
      }

      if (StringUtils.isEmpty(windowId)) {
        if (this.jsfModuleConfig.isInitialRedirectEnabled()) {
          ClientWindowHelper.handleInitialRedirect(facesContext, generateNewWindowId());
          facesContext.responseComplete();
          windowId = null;
        } else {
          windowId = generateNewWindowId();
        }
      }
    } else if (ClientWindowRenderMode.CLIENTWINDOW.equals(clientWindowRenderMode)) {
      if (facesContext.isPostback()) {
        windowId = getPostBackWindowId(facesContext);
      } else if (isNoscriptRequest(externalContext)) {
        // the client has JavaScript disabled
        clientWindowConfig.setJavaScriptEnabled(false);

        windowId = DEFAULT_WINDOW_ID;
      } else {
        windowId = getVerifiedWindowIdFromCookie(externalContext);

        boolean newWindowIdRequested = false;
        if (AUTOMATED_ENTRY_POINT_PARAMETER_KEY.equals(windowId)) {
          // this is a marker for generating a new windowId
          windowId = generateNewWindowId();
          newWindowIdRequested = true;
        }

        if (windowId == null || newWindowIdRequested) {
          // GET request without windowId - send windowhandlerfilter.html to get the windowId
          sendWindowHandlerHtml(externalContext, windowId);
          facesContext.responseComplete();
        }
      }
    }

    // we have a valid windowId - set it and continue with the request
    if (windowId != null) {
      requestMap.put(WINDOW_ID_REQUEST_MAP_KEY, windowId);
    }

    return windowId;
  }
  @Override
  public void encodeBegin(FacesContext facesContext, UIComponent uiComponent) throws IOException {

    super.encodeBegin(facesContext, uiComponent);

    InputEditorInternal inputEditorInternal = (InputEditorInternal) uiComponent;
    ResponseWriter responseWriter = facesContext.getResponseWriter();
    ExternalContext externalContext = facesContext.getExternalContext();
    PortletRequest portletRequest = (PortletRequest) externalContext.getRequest();
    PortletResponse portletResponse = (PortletResponse) externalContext.getResponse();
    HttpServletRequest httpServletRequest = PortalUtil.getHttpServletRequest(portletRequest);
    httpServletRequest = new NonNamespacedHttpServletRequest(httpServletRequest);

    HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(portletResponse);
    PortletRequest liferayPortletRequest = getLiferayPortletRequest(portletRequest);
    boolean resourcePhase = (liferayPortletRequest instanceof ResourceRequest);
    Map<String, Object> attributes = inputEditorInternal.getAttributes();
    String onBlurMethod = (String) attributes.get("onBlurMethod");
    String editorImpl = (String) attributes.get("editorImpl");

    if (editorImpl == null) {
      editorImpl = CKEDITOR;
    }

    // Build up a URL that can be used to invoke the liferay-ui:input-editor JSP tag.
    String url = "/resources/liferay-ui/jsp/input-editor.jsp";
    StringBuilder queryString = new StringBuilder();
    queryString.append(StringPool.QUESTION);
    queryString.append("editorImpl");
    queryString.append(StringPool.EQUAL);
    queryString.append(editorImpl);
    queryString.append(StringPool.AMPERSAND);
    queryString.append("height");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("height"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("initMethod");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("initMethod"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("name");
    queryString.append(StringPool.EQUAL);

    String editorName = (String) attributes.get("name");
    queryString.append(editorName);
    queryString.append(StringPool.AMPERSAND);
    queryString.append("onChangeMethod");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("onChangeMethod"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("skipEditorLoading");
    queryString.append(StringPool.EQUAL);

    if (resourcePhase) {

      // FACES-1439: Ensure that the <script src=".../ckeditor.js" /> element is not included in the
      // response by
      // specifying skipEditorLoading="true" during Ajax requests.
      queryString.append(Boolean.TRUE.toString());
    } else {
      queryString.append(Boolean.FALSE.toString());
    }

    queryString.append(StringPool.AMPERSAND);
    queryString.append("toolbarSet");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("toolbarSet"));
    queryString.append(StringPool.AMPERSAND);
    queryString.append("width");
    queryString.append(StringPool.EQUAL);
    queryString.append(attributes.get("width"));
    url = url + queryString.toString();

    // Invoke the tag and capture it's output in a String, rather than having the output go directly
    // to the
    // response.
    RequestDispatcher requestDispatcher = httpServletRequest.getRequestDispatcher(url);
    JspIncludeResponse jspIncludeResponse = new JspIncludeResponse(httpServletResponse);

    try {
      requestDispatcher.include(httpServletRequest, jspIncludeResponse);
    } catch (ServletException e) {
      logger.error(e.getMessage());
      throw new IOException(e.getMessage());
    }

    String bufferedResponse = jspIncludeResponse.getBufferedResponse();

    if (bufferedResponse != null) {

      // Note: Trim the buffered response since there is typically over 100 newlines at the
      // beginning.
      bufferedResponse = bufferedResponse.trim();

      // If rendering an instance of the CKEditor, then
      String editorType = EditorUtil.getEditorValue(httpServletRequest, editorImpl);

      if (editorType.indexOf(CKEDITOR) >= 0) {

        String namespace = portletResponse.getNamespace();

        // FACES-1441: The liferay-ui:input-editor JSP tag (and associated ckeditor.jsp file) do not
        // provide a
        // way to hook-in to the "onblur" callback feature of the CKEditor. In order to overcome
        // this
        // limitation, it is necessary to append a <script>...</script> to the response that
        // provides this
        // ability.
        String onBlurScript = getOnBlurScript(editorName, onBlurMethod, namespace);

        // If running within an Ajax request, include the "onblur" callback script must be included
        // directly
        // to the response.
        if (resourcePhase) {

          StringBuilder scriptMarkup = new StringBuilder();
          scriptMarkup.append(StringPool.LESS_THAN);
          scriptMarkup.append(StringPool.SCRIPT);
          scriptMarkup.append(StringPool.GREATER_THAN);
          scriptMarkup.append(StringPool.CDATA_OPEN);
          scriptMarkup.append(onBlurScript);
          scriptMarkup.append(COMMENT_CDATA_CLOSE);
          scriptMarkup.append(StringPool.LESS_THAN);
          scriptMarkup.append(StringPool.FORWARD_SLASH);
          scriptMarkup.append(StringPool.SCRIPT);
          scriptMarkup.append(StringPool.GREATER_THAN);
          bufferedResponse = bufferedResponse.concat(scriptMarkup.toString());
        }

        // Otherwise, append the script to the "LIFERAY_SHARED_AUI_SCRIPT_DATA" request attribute,
        // which will
        // cause the script to be rendered at the bottom of the portal page.
        else {

          ScriptData scriptData =
              (ScriptData) externalContext.getRequestMap().get(WebKeys.AUI_SCRIPT_DATA);
          scriptData.append(getPortletId(portletRequest), onBlurScript, null);
        }

        // FACES-1439: If the component was rendered on the page on the previous JSF lifecycle, then
        // prevent it
        // from being re-initialized by removing all <script>...</script> elements.
        boolean scriptsRemoved = false;

        String clientId = inputEditorInternal.getClientId();

        if (resourcePhase && inputEditorInternal.isPreviouslyRendered()) {

          logger.debug("Preventing re-initialization of CKEditor for clientId=[{0}]", clientId);

          ParsedResponse parsedResponse = new ParsedResponse(bufferedResponse);
          bufferedResponse = parsedResponse.getNonScripts();
          scriptsRemoved = true;
        }

        // FACES-1422: Move the scripts to the <eval>...</eval> section of the partial-response so
        // that they
        // will execute properly. This has the added benefit of preempt a DOM-diff with ICEfaces.
        if (resourcePhase && !scriptsRemoved) {

          logger.debug(
              "Moving CKEditor scripts to <eval>...</eval> section of the partial-response for clientId=[{0}]",
              clientId);

          ParsedResponse parsedResponse = new ParsedResponse(bufferedResponse);
          bufferedResponse = parsedResponse.getNonScripts();

          String scripts = parsedResponse.getScripts();

          LiferayFacesContext liferayFacesContext = LiferayFacesContext.getInstance();
          liferayFacesContext.getJavaScriptMap().put(clientId, scripts);
          logger.trace(scripts);
        }
      }

      // Write the captured output from the JSP tag to the Faces responseWriter.
      logger.trace(bufferedResponse);
      responseWriter.write(bufferedResponse);
    }
  }
  /**
   * 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);
  }
Example #30
0
  @Override
  public void renderView(FacesContext context, UIViewRoot root) throws IOException, FacesException {
    Components.runScheduledActions();
    if (!context.getResponseComplete()) {

      ExternalContext externalContext = context.getExternalContext();
      Object session = externalContext.getSession(false);
      Map<String, Object> requestMap = externalContext.getRequestMap();

      if (externalContext.getSessionMap().containsKey(ERROR_OCCURRED_UNDER_PORTLETS)) {
        processExceptionUnderPortlets(context);
        return;
      }

      if (AjaxUtil.isPortletRequest(context)
          && Environment.isMyFaces()
          && isNewSession(externalContext.getSession(false))) {
        processSessionExpirationUnderPortletsMyFaces(context, root, externalContext, session);
      }

      if (AjaxUtil.isPortletRequest(context)
          && Environment.isRI()
          && isNewSession(externalContext.getSession(false))) {
        processSessionExpirationUnderPortletsRI(context, root, externalContext);
      }

      boolean ajaxRequest = AjaxUtil.isAjaxRequest(context);
      if (!ajaxRequest && !AjaxUtil.isAjax4jsfRequest())
        ValidationSupportResponseWriter.resetBubbleIndex(context);

      if (ajaxRequest) {
        updateSessionExpirationFlagUnderPortlets(context, root, externalContext, requestMap);
        try {
          // HACK for MyFaces ( <f:view> tag not call renderers )
          // ServletResponse response = (ServletResponse) context
          //		.getExternalContext().getResponse();
          Object response = externalContext.getResponse();

          if (!AjaxUtil.isPortletRequest(context)) {
            try {
              response.getClass().getDeclaredMethod("resetResponse").invoke(response);
              // response.reset();
            } catch (Exception e) {
              // Do nothing - we will use directly and reset
              // wrapper
            }
          }

          if (requestMap.containsKey(SESSION_EXPIRATION_PROCESSING)) {
            super.renderView(context, root);
            // This is done for MyFaces use-case, because MyFaces doesn't call rendering methods for
            // ViewRoot
            if (!Environment.isRI()) {
              root.encodeChildren(context);
            }
            Map<String, Object> sessionMap = context.getExternalContext().getSessionMap();
            if (sessionMap != null && !sessionMap.containsKey(SESSION_SCOPED_PARAMETER)) {
              sessionMap.put(SESSION_SCOPED_PARAMETER, Boolean.TRUE.toString());
            }
            return;
          }

          if (Environment.isFacelets(context)) {
            super.renderView(context, root);
          } else {
            root.encodeBegin(context);
            if (root.getRendersChildren()) {
              root.encodeChildren(context);
            }
            root.encodeEnd(context);
          }
        } catch (RuntimeException e) {
          CommonAjaxViewRoot.processExceptionDuringAjax(context, e);
          externalContext.log(e.getMessage(), e);
        } catch (Error e) {
          CommonAjaxViewRoot.processExceptionDuringAjax(context, e);
          externalContext.log(e.getMessage(), e);
        }

      } else {

        super.renderView(context, root);
        Map<String, Object> sessionMap = context.getExternalContext().getSessionMap();
        if (sessionMap != null && !sessionMap.containsKey(SESSION_SCOPED_PARAMETER)) {
          sessionMap.put(SESSION_SCOPED_PARAMETER, Boolean.TRUE.toString());
        }

        if (AjaxUtil.isAjax4jsfRequest()) {
          Resources.processHeadResources(context);
        }
      }
    }
  }