Exemplo n.º 1
0
  /**
   * Build the view.
   *
   * @param ctx the {@link FacesContext} for the current request
   * @param view the {@link UIViewRoot} to populate based of the Facelet template
   * @throws IOException if an error occurs building the view.
   */
  @Override
  public void buildView(FacesContext ctx, UIViewRoot view) throws IOException {

    if (Util.isViewPopulated(ctx, view)) {
      return;
    }
    updateStateSavingType(ctx, view.getViewId());
    view.setViewId(view.getViewId());

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Building View: " + view.getViewId());
    }
    if (faceletFactory == null) {
      ApplicationAssociate associate = ApplicationAssociate.getInstance(ctx.getExternalContext());
      faceletFactory = associate.getFaceletFactory();
      assert (faceletFactory != null);
    }
    RequestStateManager.set(ctx, RequestStateManager.FACELET_FACTORY, faceletFactory);
    Facelet f = faceletFactory.getFacelet(view.getViewId());

    // populate UIViewRoot
    f.apply(ctx, view);
    doPostBuildActions(view);
    Util.setViewPopulated(ctx, view);
  }
Exemplo n.º 2
0
  /**
   * @see javax.faces.view.ViewDeclarationLanguage#renderView(javax.faces.context.FacesContext,
   *     javax.faces.component.UIViewRoot)
   */
  public void renderView(FacesContext ctx, UIViewRoot viewToRender) throws IOException {

    // suppress rendering if "rendered" property on the component is
    // false
    if (!viewToRender.isRendered()) {
      return;
    }

    // log request
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Rendering View: " + viewToRender.getViewId());
    }

    WriteBehindStateWriter stateWriter = null;
    try {
      // Only build the view if this view has not yet been built.
      if (!Util.isViewPopulated(ctx, viewToRender)) {
        this.buildView(ctx, viewToRender);
      }

      // setup writer and assign it to the ctx
      ResponseWriter origWriter = ctx.getResponseWriter();
      if (origWriter == null) {
        origWriter = createResponseWriter(ctx);
      }

      stateWriter = new WriteBehindStateWriter(origWriter, ctx, responseBufferSize);

      ResponseWriter writer = origWriter.cloneWithWriter(stateWriter);
      ctx.setResponseWriter(writer);

      // render the view to the response
      writer.startDocument();
      viewToRender.encodeAll(ctx);
      writer.endDocument();

      // finish writing
      writer.close();

      boolean writtenState = stateWriter.stateWritten();
      // flush to origWriter
      if (writtenState) {
        stateWriter.flushToWriter();
      }

    } catch (FileNotFoundException fnfe) {
      this.handleFaceletNotFound(ctx, viewToRender.getViewId(), fnfe.getMessage());
    } catch (Exception e) {
      this.handleRenderException(ctx, e);
    } finally {
      if (stateWriter != null) stateWriter.release();
    }
  }
Exemplo n.º 3
0
  /**
   * @see javax.faces.view.ViewDeclarationLanguage#buildView(javax.faces.context.FacesContext,
   *     javax.faces.component.UIViewRoot)
   * @param context
   * @param view
   * @throws IOException
   */
  public void buildView(FacesContext context, UIViewRoot view) throws IOException {

    if (Util.isViewPopulated(context, view)) {
      return;
    }
    try {
      if (executePageToBuildView(context, view)) {
        context.getExternalContext().responseFlushBuffer();
        if (associate != null) {
          associate.responseRendered();
        }
        context.responseComplete();
        return;
      }
    } catch (IOException e) {
      throw new FacesException(e);
    }

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.log(Level.FINE, "Completed building view for : \n" + view.getViewId());
    }
    context
        .getApplication()
        .publishEvent(context, PostAddToViewEvent.class, UIViewRoot.class, view);
    Util.setViewPopulated(context, view);
  }
Exemplo n.º 4
0
  /**
   * @param ctx FacesContext.
   * @param viewId the view ID to check or null if viewId is unknown.
   * @return <code>true</code> if partial state saving should be used for the specified view ID,
   *     otherwise <code>false</code>
   */
  public boolean isPartialStateSaving(FacesContext ctx, String viewId) {
    // track UIViewRoot changes
    UIViewRoot root = ctx.getViewRoot();
    UIViewRoot refRoot = viewRootRef.get();
    if (root != refRoot) {
      // set weak reference to current viewRoot
      this.viewRootRef = new WeakReference<UIViewRoot>(root);

      // On first call in restore phase, viewRoot is null, so we treat the first
      // change to not null not as a changing viewRoot.
      if (refRoot != null) {
        // view root changed in request processing - force usage of a
        // new AddRemoveListener instance for the new viewId ...
        modListener = null;
        // ... and also force check for partial state saving for the new viewId
        partialLocked = false;
      }
    }

    if (!partialLocked) {
      if (viewId == null) {
        if (root != null) {
          viewId = root.getViewId();
        } else {
          // View root has not yet been initialized.  Check to see whether
          // the target view id has been stashed away for us.
          viewId = (String) ctx.getAttributes().get(RIConstants.VIEWID_KEY_NAME);
        }
      }

      partial = stateInfo.usePartialStateSaving(viewId);
      partialLocked = true;
    }
    return partial;
  }
Exemplo n.º 5
0
  /*
   * This method provides custom logic of wrapping viewRoot instances.
   * This is done, because different environments casts current viewRoot
   * instance to their own implementation of UIViewRoot class.
   * So, we need to comply with inheritance hierarchy.
   */
  private UIViewRoot getAjaxViewRoot(UIViewRoot root, FacesContext context) {
    UIViewRoot riRoot;
    Class ajax4jsfViewRootClass = null;
    try {
      ajax4jsfViewRootClass = Class.forName("org.ajax4jsf.framework.ajax.AjaxViewRoot");
    } catch (ClassNotFoundException e) {
      // absence of the Ajax4jsf library is a valid case
    }
    boolean isAjax4jsf = (ajax4jsfViewRootClass != null);
    if (isAjax4jsf)
      throw new IllegalArgumentException(
          "OpenFaces warning: The old Ajax4jsf framework is not supported. Use RichFaces that now incorporates this framework instead.");

    Class richFacesAjaxViewRootClass = null;
    try {
      richFacesAjaxViewRootClass = Class.forName("org.ajax4jsf.component.AjaxViewRoot");
    } catch (ClassNotFoundException e) {
      // absence of the RichFaces library is a valid case
    }

    if (Environment.isExoPortal()) riRoot = createExoAjaxViewRoot(root);
    else if (richFacesAjaxViewRootClass == null) riRoot = new AjaxViewRoot();
    else if (Environment.isGateInPortal(context)) riRoot = createGateInAjaxViewRoot(root);
    else riRoot = createA4jAjaxViewRoot(root);
    // fill properties from default.
    riRoot.setViewId(root.getViewId());
    riRoot.setLocale(root.getLocale());
    String renderKitId = root.getRenderKitId();
    // Fix facelets bug - for debug requests renderKitId is null !
    if (null == renderKitId) {
      renderKitId = calculateRenderKitId(context);
    }
    riRoot.setRenderKitId(renderKitId);
    return riRoot;
  }
Exemplo n.º 6
0
 /**
  * Inspect the annotations in the ViewConfigStore, enforcing any restrictions applicable to this
  * phase
  *
  * @param event
  * @param phaseIdType
  */
 private void performObservation(PhaseEvent event, PhaseIdType phaseIdType) {
   UIViewRoot viewRoot = (UIViewRoot) event.getFacesContext().getViewRoot();
   List<? extends Annotation> restrictionsForPhase =
       getRestrictionsForPhase(phaseIdType, viewRoot.getViewId());
   if (restrictionsForPhase != null) {
     log.debugf("Enforcing on phase %s", phaseIdType);
     enforce(event.getFacesContext(), viewRoot, restrictionsForPhase);
   }
 }
Exemplo n.º 7
0
  /**
   * Call {@link PageDeclarationLanguage#renderView(javax.faces.context.FacesContext,
   * javax.faces.component.UIViewRoot)} if the view can be rendered.
   *
   * @see ViewHandler#renderView(javax.faces.context.FacesContext, javax.faces.component.UIViewRoot)
   */
  public void renderView(FacesContext context, UIViewRoot viewToRender)
      throws IOException, FacesException {

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

    pdlFactory
        .getPageDeclarationLanguage(viewToRender.getViewId())
        .renderView(context, viewToRender);
  }
Exemplo n.º 8
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);
   }
 }
Exemplo n.º 9
0
  /**
   * This is a separate method to account for handling the content after the view tag.
   *
   * <p>Create a new ResponseWriter around this response's Writer. Set it into the FacesContext,
   * saving the old one aside.
   *
   * <p>call encodeBegin(), encodeChildren(), encodeEnd() on the argument <code>UIViewRoot</code>.
   *
   * <p>Restore the old ResponseWriter into the FacesContext.
   *
   * <p>Write out the after view content to the response's writer.
   *
   * <p>Flush the response buffer, and remove the after view content from the request scope.
   *
   * @param context the <code>FacesContext</code> for the current request
   * @param viewToRender the view to render
   * @throws java.io.IOException if an error occurs rendering the view to the client
   * @throws javax.faces.FacesException if some error occurs within the framework processing
   */
  private void doRenderView(FacesContext context, UIViewRoot viewToRender) throws IOException {

    if (null != associate) {
      associate.responseRendered();
    }

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.log(Level.FINE, "About to render view " + viewToRender.getViewId());
    }

    viewToRender.encodeAll(context);
  }
Exemplo n.º 10
0
  protected void addViewParameters(
      FacesContext ctx, String viewId, Map<String, List<String>> existingParameters) {

    UIViewRoot currentRoot = ctx.getViewRoot();
    String currentViewId = currentRoot.getViewId();
    Collection<UIViewParameter> toViewParams;
    Collection<UIViewParameter> currentViewParams;
    boolean currentIsSameAsNew = false;
    currentViewParams = ViewMetadata.getViewParameters(currentRoot);

    if (currentViewId.equals(viewId)) {
      currentIsSameAsNew = true;
      toViewParams = currentViewParams;
    } else {
      ViewDeclarationLanguage pdl = getViewDeclarationLanguage(ctx, viewId);
      ViewMetadata viewMetadata = pdl.getViewMetadata(ctx, viewId);
      UIViewRoot root = viewMetadata.createMetadataView(ctx);
      toViewParams = ViewMetadata.getViewParameters(root);
    }

    if (toViewParams.isEmpty()) {
      return;
    }

    for (UIViewParameter viewParam : toViewParams) {
      String value;
      // don't bother looking at view parameter if it's been overridden
      if (existingParameters.containsKey(viewParam.getName())) {
        continue;
      } else if (paramHasValueExpression(viewParam)) {
        value = viewParam.getStringValueFromModel(ctx);
      } else {
        // Anonymous view parameter:
        // Get string value from UIViewParameter instance stored in current view
        if (currentIsSameAsNew) {
          value = viewParam.getStringValue(ctx);
        }
        // ...or transfer string value from matching UIViewParameter instance stored in current view
        else {
          value = getStringValueToTransfer(ctx, viewParam, currentViewParams);
        }
      }
      if (value != null) {
        List<String> existing = existingParameters.get(viewParam.getName());
        if (existing == null) {
          existing = new ArrayList<String>(4);
          existingParameters.put(viewParam.getName(), existing);
        }
        existing.add(value);
      }
    }
  }
Exemplo n.º 11
0
 /**
  * Perform the navigation to the @LoginView. If not @LoginView is defined, return a 401 response.
  * The original view id requested by the user is stored in the session map, for use after a
  * successful login.
  *
  * @param context
  * @param viewRoot
  */
 private void redirectToLoginPage(FacesContext context, UIViewRoot viewRoot) {
   Map<String, Object> sessionMap = context.getExternalContext().getSessionMap();
   preLoginEvent.fire(new PreLoginEvent(context, sessionMap));
   LoginView loginView = viewConfigStore.getAnnotationData(viewRoot.getViewId(), LoginView.class);
   if (loginView == null || loginView.value() == null || loginView.value().isEmpty()) {
     log.debug("Returning 401 response (login required)");
     context.getExternalContext().setResponseStatus(401);
     context.responseComplete();
     return;
   }
   String loginViewId = loginView.value();
   log.debugf("Redirecting to configured LoginView %s", loginViewId);
   NavigationHandler navHandler = context.getApplication().getNavigationHandler();
   navHandler.handleNavigation(context, "", loginViewId);
   context.renderResponse();
 }
Exemplo n.º 12
0
 /**
  * Perform the navigation to the @AccessDeniedView. If not @AccessDeniedView is defined, return a
  * 401 response
  *
  * @param context
  * @param viewRoot
  */
 private void redirectToAccessDeniedView(FacesContext context, UIViewRoot viewRoot) {
   AccessDeniedView accessDeniedView =
       viewConfigStore.getAnnotationData(viewRoot.getViewId(), AccessDeniedView.class);
   if (accessDeniedView == null
       || accessDeniedView.value() == null
       || accessDeniedView.value().isEmpty()) {
     log.debug("Returning 401 response (access denied)");
     context.getExternalContext().setResponseStatus(401);
     context.responseComplete();
     return;
   }
   String accessDeniedViewId = accessDeniedView.value();
   log.debugf("Redirecting to configured AccessDenied %s", accessDeniedViewId);
   NavigationHandler navHandler = context.getApplication().getNavigationHandler();
   navHandler.handleNavigation(context, "", accessDeniedViewId);
   context.renderResponse();
 }
Exemplo n.º 13
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());
      }
    }
  }
Exemplo n.º 14
0
 public void renderView(FacesContext context, UIViewRoot viewRoot)
     throws IOException, FacesException {
   String viewId = viewRoot.getViewId();
   if (!context.getResponseComplete() && isMapped(viewId)) {
     NavigationHandler nh = context.getApplication().getNavigationHandler();
     ViewHandler vh = context.getApplication().getViewHandler();
     String action = (String) context.getExternalContext().getRequestParameterMap().get("action");
     String outcome =
         (String) context.getExternalContext().getRequestParameterMap().get("outcome");
     if (action != null) {
       String method = extractMethodName(action);
       MethodBinding mb =
           context.getApplication().createMethodBinding("#{" + action + "}", new Class[0]);
       outcome = mb.invoke(context, new Object[0]).toString();
       nh.handleNavigation(context, method, outcome);
       if (!context.getResponseComplete() && context.getViewRoot().equals(viewRoot)) {
         throw new FacesException(
             "No navigation rules from viewId="
                 + viewId
                 + ", action="
                 + action
                 + ", outcome="
                 + outcome
                 + " found.");
       }
     } else {
       nh.handleNavigation(context, null, outcome);
       if (!context.getResponseComplete() && context.getViewRoot().equals(viewRoot)) {
         throw new FacesException(
             "No navigation rules from viewId=" + viewId + ", outcome=" + outcome + " found.");
       }
     }
     if (!context.getResponseComplete()) {
       vh.renderView(context, context.getViewRoot());
     }
     ;
   } else {
     viewHandler.renderView(context, viewRoot);
   }
 }
Exemplo n.º 15
0
  /**
   * Handles the case where rendering throws an Exception.
   *
   * @param context the {@link FacesContext} for the current request
   * @param e the caught Exception
   * @throws IOException if the custom debug content cannot be written
   */
  protected void handleRenderException(FacesContext context, Exception e) throws IOException {

    // always log
    if (LOGGER.isLoggable(Level.SEVERE)) {
      UIViewRoot root = context.getViewRoot();
      StringBuffer sb = new StringBuffer(64);
      sb.append("Error Rendering View");
      if (root != null) {
        sb.append('[');
        sb.append(root.getViewId());
        sb.append(']');
      }
      LOGGER.log(Level.SEVERE, sb.toString(), e);
    }

    if (e instanceof RuntimeException) {
      throw (RuntimeException) e;
    } else if (e instanceof IOException) {
      throw (IOException) e;
    } else {
      throw new FacesException(e.getMessage(), e);
    }
  }
Exemplo n.º 16
0
  /**
   * This method uses helper methods to determine the new <code>view</code> identifier. Refer to
   * section 7.4.2 of the specification for more details.
   *
   * @param context The Faces Context
   * @param fromAction The action reference string
   * @param outcome The outcome string
   * @return The <code>view</code> identifier.
   */
  private CaseStruct getViewId(FacesContext context, String fromAction, String outcome) {

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

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

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

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

    if (caseStruct == null && development) {
      String key;
      Object[] params;
      if (fromAction == null) {
        key = MessageUtils.NAVIGATION_NO_MATCHING_OUTCOME_ID;
        params = new Object[] {viewId, outcome};
      } else {
        key = MessageUtils.NAVIGATION_NO_MATCHING_OUTCOME_ACTION_ID;
        params = new Object[] {viewId, fromAction, outcome};
      }
      FacesMessage m = MessageUtils.getExceptionMessage(key, params);
      m.setSeverity(FacesMessage.SEVERITY_WARN);
      context.addMessage(null, m);
    }
    return caseStruct;
  }
  @Override
  public void buildView(FacesContext facesContext, UIViewRoot uiViewRoot) throws IOException {
    super.buildView(facesContext, uiViewRoot);

    UIComponent coreForm = findCoreFormRecurse(uiViewRoot);

    if (coreForm != null) {

      // Since the JSF-1.2-based TCK does not have h:head tags in any of the JSPs, need to add one
      // dynamically so
      // that the jsf.js script resource can be rendered. This is necessary so that Trinidad Partial
      // Page
      // Rendering (PPR) will work properly.
      HtmlHead htmlHead = new HtmlHead();
      uiViewRoot.getChildren().add(htmlHead);

      // Add the "jsf.js" script resource to the h:head component.
      UIOutput uiOutput = new UIOutput();
      uiOutput.setRendererType("javax.faces.resource.Script");
      uiOutput.getAttributes().put("name", "jsf.js");
      uiOutput.getAttributes().put("library", "javax.faces");
      uiViewRoot.addComponentResource(facesContext, uiOutput, "head");

      // Due to a bug in the Trinidad tr:form renderer, need to add the javax.faces.encodedURL
      // hidden field
      // dynamically. See: https://issues.apache.org/jira/browse/TRINIDAD-2284
      String viewId = uiViewRoot.getViewId();
      String actionURL =
          facesContext.getApplication().getViewHandler().getActionURL(facesContext, viewId);
      ExternalContext externalContext = facesContext.getExternalContext();
      String encodedPartialActionURL = externalContext.encodePartialActionURL(actionURL);
      EncodedURLHiddenField encodedURLHiddenField = new EncodedURLHiddenField();
      encodedURLHiddenField.setValue(encodedPartialActionURL);
      coreForm.getChildren().add(encodedURLHiddenField);
    }
  }
Exemplo n.º 18
0
 private String getViewId(PhaseEvent event) {
   UIViewRoot viewRoot = event.getFacesContext().getViewRoot();
   return viewRoot == null ? null : viewRoot.getViewId();
 }
Exemplo n.º 19
0
  private boolean sendError(FacesContext context, String lifecycle, Exception e) {
    for (Throwable cause = e; cause != null; cause = cause.getCause()) {
      if (cause instanceof DisplayableException) {
        if (e instanceof RuntimeException) throw (RuntimeException) e;
        else throw new FacesException(e);
      } else if (cause instanceof ServletException) throw new FacesException(e);
      else if (cause instanceof JspException) throw new FacesException(e);
    }

    ExternalContext extContext = context.getExternalContext();
    Object response = extContext.getResponse();

    if (!(response instanceof HttpServletResponse)) {
      context.renderResponse();

      if (e instanceof RuntimeException) throw (RuntimeException) e;
      else throw new RuntimeException(e);
    }

    log.log(Level.WARNING, e.toString(), e);

    HttpServletResponse res = (HttpServletResponse) response;

    try {
      context.renderResponse();
      context.responseComplete();

      res.setStatus(500, "JSF Exception");
      res.setContentType("text/html");

      PrintWriter out = res.getWriter();

      out.println("<body>");

      out.println("<h3>JSF exception detected in " + lifecycle + " phase</h3>");

      String msg = e.getMessage();
      out.println("<span style='color:red;font:bold'>" + Html.escapeHtml(msg) + "</span><br/>");

      out.println("<h3>Context: " + context.getViewRoot() + "</h3>");
      out.println("<code><pre>");

      String errorId = null;

      if (e instanceof FacesException && msg.startsWith("id=")) {
        int p = msg.indexOf(' ');
        errorId = msg.substring(3, p);
      }

      printComponentTree(out, errorId, context, context.getViewRoot(), 0);

      out.println("</pre></code>");

      if (!Alarm.isTest()) {
        out.println("<h3>Stack Trace</h3>");
        out.println("<pre>");
        if (e.getCause() != null) e.getCause().printStackTrace(out);
        else e.printStackTrace(out);
        out.println("</pre>");
      }

      out.println("</body>");

      // clear, so we don't just loop
      Application app = context.getApplication();

      ViewHandler view = app.getViewHandler();

      UIViewRoot viewRoot = context.getViewRoot();

      viewRoot = view.createView(context, viewRoot.getViewId());

      context.setViewRoot(viewRoot);

      // view.writeState(context); // XXX: no need to output state, but review.

      return true;
    } catch (IOException e1) {
      throw new RuntimeException(e);
    }
  }
  @SuppressWarnings("unchecked")
  public void restoreState(FacesContext facesContext) {

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

    boolean restoreNonExcludedRequestAttributes =
        ((beganInPhase == Bridge.PortletPhase.ACTION_PHASE)
            || (beganInPhase == Bridge.PortletPhase.EVENT_PHASE)
            || (beganInPhase == Bridge.PortletPhase.RESOURCE_PHASE));

    BridgeContext bridgeContext = BridgeContext.getCurrentInstance();

    PortletPhase portletRequestPhase = bridgeContext.getPortletRequestPhase();

    if (portletRequestPhase == Bridge.PortletPhase.RENDER_PHASE) {

      if (!portletMode.equals(bridgeContext.getPortletRequest().getPortletMode())) {
        setPortletModeChanged(true);
        restoreNonExcludedRequestAttributes = false;
      }
    }

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

      // Restore the view root that may have been saved during the ACTION_PHASE of the portlet
      // lifecycle.
      UIViewRoot uiViewRoot = (UIViewRoot) getAttribute(BRIDGE_REQ_SCOPE_ATTR_FACES_VIEW_ROOT);

      if (uiViewRoot != null) {
        facesContext.setViewRoot(uiViewRoot);
        logger.debug("Restored viewId=[{0}] uiViewRoot=[{1}]", uiViewRoot.getViewId(), uiViewRoot);
      } else {
        logger.debug("Did not restore uiViewRoot");
      }

      // Restore the faces messages that may have been saved during the ACTION_PHASE of the portlet
      // lifecycle.
      List<FacesMessageWrapper> facesMessages =
          (List<FacesMessageWrapper>) getAttribute(BRIDGE_REQ_SCOPE_ATTR_FACES_MESSAGES);

      boolean restoredFacesMessages = false;

      if (facesMessages != null) {

        for (FacesMessageWrapper facesMessageWrapper : facesMessages) {
          String clientId = facesMessageWrapper.getClientId();
          FacesMessage facesMessage = facesMessageWrapper.getFacesMessage();
          facesContext.addMessage(clientId, facesMessage);
          logger.trace("Restored facesMessage=[{0}]", facesMessage.getSummary());
          restoredFacesMessages = true;
        }
      }

      if (restoredFacesMessages) {
        logger.debug("Restored facesMessages");
      } else {
        logger.debug("Did not restore any facesMessages");
      }

      // NOTE: PROPOSE-FOR-BRIDGE3-API: https://issues.apache.org/jira/browse/PORTLETBRIDGE-203
      // Restore the
      // FacesContext attributes that may have been saved during the ACTION_PHASE of the portlet
      // lifecycle.
      restoreJSF2FacesContextAttributes(facesContext);
    }

    if (restoreNonExcludedRequestAttributes) {

      // Restore the non-excluded request attributes.
      List<RequestAttribute> savedRequestAttributes =
          (List<RequestAttribute>) getAttribute(BRIDGE_REQ_SCOPE_ATTR_REQUEST_ATTRIBUTES);

      boolean restoredNonExcludedRequestAttributes = false;

      if (savedRequestAttributes != null) {
        Map<String, Object> currentRequestAttributes =
            facesContext.getExternalContext().getRequestMap();

        // If a redirect did not occur, then restore the non-excluded request attributes.
        if (!isRedirectOccurred()) {

          for (RequestAttribute requestAttribute : savedRequestAttributes) {
            String name = requestAttribute.getName();
            Object value = requestAttribute.getValue();
            logger.trace(
                "Restoring non-excluded request attribute name=[{0}] value=[{1}]", name, value);
            currentRequestAttributes.put(name, value);
            restoredNonExcludedRequestAttributes = true;
          }
        }
      }

      if (restoredNonExcludedRequestAttributes) {
        logger.debug("Restored non-excluded request attributes");
      } else {
        logger.debug("Did not restore any non-excluded request attributes");
      }
    }

    // If running in the RENDER_PHASE, then the Flash scope must be restored.
    if (portletRequestPhase == Bridge.PortletPhase.RENDER_PHASE) {

      // NOTE: PROPOSED-FOR-BRIDGE3-API: https://issues.apache.org/jira/browse/PORTLETBRIDGE-201
      // Restore the flash scope.
      restoreFlashState(facesContext);
    }

    // If running in the RENDER_PHASE, then the incongruity context must be restored.
    if (((beganInPhase == Bridge.PortletPhase.ACTION_PHASE)
            || (beganInPhase == Bridge.PortletPhase.EVENT_PHASE))
        && (portletRequestPhase == Bridge.PortletPhase.RENDER_PHASE)) {

      List<IncongruityAttribute> savedIncongruityAttributes =
          (List<IncongruityAttribute>)
              getAttribute(BRIDGE_REQ_SCOPE_ATTR_INCONGRUITY_CONTEXT_ATTRIBUTES);

      if (savedIncongruityAttributes != null) {

        IncongruityContext incongruityContext = bridgeContext.getIncongruityContext();
        Map<String, Object> incongruityContextAttributes = incongruityContext.getAttributes();

        for (IncongruityAttribute incongruityAttribute : savedIncongruityAttributes) {
          String key = incongruityAttribute.getName();
          Object value = incongruityAttribute.getValue();
          incongruityContextAttributes.put(key, value);
        }
      }
    }
  }
Exemplo n.º 21
0
  @Override
  public void encodeJavaScriptCustom(FacesContext facesContext, UIComponent uiComponent)
      throws IOException {

    ResponseWriter responseWriter = facesContext.getResponseWriter();
    InputFile inputFile = (InputFile) uiComponent;
    JavaScriptFragment alloyNamespace = new JavaScriptFragment("A");

    // Determine the valid content-types and maximum file size from the validator (if specified).
    JavaScriptFragment contentTypes = new JavaScriptFragment("[]");
    String validContentTypes = inputFile.getContentTypes();

    if (validContentTypes != null) {
      contentTypes = toJavaScriptArray(validContentTypes.split(","));
    }

    String clientId = inputFile.getClientId(facesContext);
    Long maxFileSize = inputFile.getMaxFileSize();

    if (maxFileSize == null) {
      maxFileSize = Long.MAX_VALUE;
    }

    // If the component should render the upload progress table, then initialize the YUI progress
    // uploader widget.
    if (inputFile.isShowProgress()) {

      String clientVarName = getClientVarName(facesContext, inputFile);
      String clientKey = inputFile.getClientKey();

      if (clientKey == null) {
        clientKey = clientVarName;
      }

      UIViewRoot viewRoot = facesContext.getViewRoot();
      Locale locale = viewRoot.getLocale();
      String formClientId = getParentFormClientId(inputFile);
      Application application = facesContext.getApplication();
      ViewHandler viewHandler = application.getViewHandler();
      String actionURL = viewHandler.getActionURL(facesContext, viewRoot.getViewId());
      String partialActionURL = facesContext.getExternalContext().encodePartialActionURL(actionURL);
      String namingContainerId = "";

      if (viewRoot instanceof NamingContainer) {
        namingContainerId = viewRoot.getContainerClientId(facesContext);
      }

      AjaxParameters ajaxParameters = new AjaxParameters(inputFile, clientId, formClientId);
      String execute = ajaxParameters.getExecute();
      String render = ajaxParameters.getRender();

      String notStartedMessage = getMessageContext().getMessage(locale, "not-started");
      JavaScriptFragment clientComponent =
          new JavaScriptFragment("Liferay.component('" + clientKey + "')");
      encodeFunctionCall(
          responseWriter,
          "LFAI.initProgressUploader",
          alloyNamespace,
          clientComponent,
          contentTypes,
          clientId,
          formClientId,
          namingContainerId,
          inputFile.isAuto(),
          execute,
          render,
          partialActionURL,
          maxFileSize,
          notStartedMessage);
    }

    // Otherwise, if the component should render the upload preview table, then format the
    // preview-uploader.js
    // template and write it to the response.
    else if (inputFile.isShowPreview()) {

      encodeFunctionCall(
          responseWriter,
          "LFAI.initPreviewUploader",
          alloyNamespace,
          contentTypes,
          clientId,
          maxFileSize);
    }
  }
Exemplo n.º 22
0
  /**
   * Execute the target view. If the HTTP status code range is not 2xx, then return true to indicate
   * the response should be immediately flushed by the caller so that conditions such as 404 are
   * properly handled.
   *
   * @param context the <code>FacesContext</code> for the current request
   * @param viewToExecute the view to build
   * @return <code>true</code> if the response should be immediately flushed to the client,
   *     otherwise <code>false</code>
   * @throws java.io.IOException if an error occurs executing the page
   */
  private boolean executePageToBuildView(FacesContext context, UIViewRoot viewToExecute)
      throws IOException {

    if (null == context) {
      String message =
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "context");
      throw new NullPointerException(message);
    }
    if (null == viewToExecute) {
      String message =
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "viewToExecute");
      throw new NullPointerException(message);
    }

    ExternalContext extContext = context.getExternalContext();

    if ("/*".equals(RequestStateManager.get(context, RequestStateManager.INVOCATION_PATH))) {
      throw new FacesException(
          MessageUtils.getExceptionMessageString(MessageUtils.FACES_SERVLET_MAPPING_INCORRECT_ID));
    }

    String requestURI = viewToExecute.getViewId();

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("About to execute view " + requestURI);
    }

    // update the JSTL locale attribute in request scope so that JSTL
    // picks up the locale from viewRoot. This attribute must be updated
    // before the JSTL setBundle tag is called because that is when the
    // new LocalizationContext object is created based on the locale.
    if (extContext.getRequest() instanceof ServletRequest) {
      Config.set(
          (ServletRequest) extContext.getRequest(),
          Config.FMT_LOCALE,
          context.getViewRoot().getLocale());
    }
    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Before dispacthMessage to viewId " + requestURI);
    }

    // save the original response
    Object originalResponse = extContext.getResponse();

    // replace the response with our wrapper
    ViewHandlerResponseWrapper wrapped = getWrapper(extContext);
    extContext.setResponse(wrapped);

    try {

      // build the view by executing the page
      extContext.dispatch(requestURI);

      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("After dispacthMessage to viewId " + requestURI);
      }
    } finally {
      // replace the original response
      extContext.setResponse(originalResponse);
    }

    // Follow the JSTL 1.2 spec, section 7.4,
    // on handling status codes on a forward
    if (wrapped.getStatus() < 200 || wrapped.getStatus() > 299) {
      // flush the contents of the wrapper to the response
      // this is necessary as the user may be using a custom
      // error page - this content should be propagated
      wrapped.flushContentToWrappedResponse();
      return true;
    }

    // Put the AFTER_VIEW_CONTENT into request scope
    // temporarily
    RequestStateManager.set(context, RequestStateManager.AFTER_VIEW_CONTENT, wrapped);

    return false;
  }
  /**
   * Restores 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 RENDER_PHASE of the portlet lifecycle.
   *
   * @param facesContext The current faces context.
   * @return Flag indicating whether or not a restoration took place.
   */
  @SuppressWarnings("unchecked")
  public boolean restoreScopedData(FacesContext facesContext) {

    if (beganInActionOrEventRequest) {

      // Restore the view root that may have been saved during the ACTION_PHASE of the portlet
      // lifecycle.
      UIViewRoot uiViewRoot = (UIViewRoot) getAttribute(BRIDGE_REQ_SCOPE_ATTR_FACES_VIEW_ROOT);

      if (uiViewRoot != null) {
        facesContext.setViewRoot(uiViewRoot);
        logger.debug("Restored viewId=[{0}] uiViewRoot=[{1}]", uiViewRoot.getViewId(), uiViewRoot);
      } else {
        logger.debug("Did not restore uiViewRoot");
      }

      // Restore the faces messages that may have been saved during the ACTION_PHASE of the portlet
      // lifecycle.
      List<FacesMessageWrapper> facesMessages =
          (List<FacesMessageWrapper>) getAttribute(BRIDGE_REQ_SCOPE_ATTR_FACES_MESSAGES);

      boolean restoredFacesMessages = false;

      if (facesMessages != null) {

        for (FacesMessageWrapper facesMessageWrapper : facesMessages) {
          String clientId = facesMessageWrapper.getClientId();
          FacesMessage facesMessage = facesMessageWrapper.getFacesMessage();
          facesContext.addMessage(clientId, facesMessage);
          logger.trace("Restored facesMessage=[{0}]", facesMessage.getSummary());
          restoredFacesMessages = true;
        }
      }

      if (restoredFacesMessages) {
        logger.debug("Restored facesMessages");
      } else {
        logger.debug("Did not restore any facesMessages");
      }

      // Restore the non-excluded request attributes.
      List<RequestAttribute> savedRequestAttributes =
          (List<RequestAttribute>) getAttribute(BRIDGE_REQ_SCOPE_ATTR_REQUEST_ATTRIBUTES);

      boolean restoredNonExcludedRequestAttributes = false;

      if (savedRequestAttributes != null) {
        Map<String, Object> currentRequestAttributes =
            facesContext.getExternalContext().getRequestMap();

        for (RequestAttribute requestAttribute : savedRequestAttributes) {
          String name = requestAttribute.getName();
          Object value = requestAttribute.getValue();
          logger.trace(
              "Restoring non-excluded request attribute name=[{0}] value=[{1}]", name, value);
          currentRequestAttributes.put(name, value);
          restoredNonExcludedRequestAttributes = true;
        }
      }

      if (restoredNonExcludedRequestAttributes) {
        logger.debug("Restored non-excluded request attributes");
      } else {
        logger.debug("Did not restore any non-excluded request attributes");
      }

      // NOTE: PROPOSE-FOR-BRIDGE3-API: https://issues.apache.org/jira/browse/PORTLETBRIDGE-203
      // Restore the
      // FacesContext attributes that may have been saved during the ACTION_PHASE of the portlet
      // lifecycle.
      List<FacesContextAttribute> savedFacesContextAttributes =
          (List<FacesContextAttribute>)
              getAttribute(BRIDGE_REQ_SCOPE_ATTR_FACES_CONTEXT_ATTRIBUTES);

      boolean restoredFacesContextAttibutes = false;

      if (savedFacesContextAttributes != null) {
        Map<Object, Object> currentFacesContextAttributes = facesContext.getAttributes();

        for (FacesContextAttribute facesContextAttribute : savedFacesContextAttributes) {
          Object name = facesContextAttribute.getName();

          // Note: Don't want to restore the BridgeContext because that would be invalid data -- it
          // would
          // contain the ActionRequest/ActionResponse or EventRequest/EventResponse and would
          // overwrite the
          // current RenderRequest/RenderResponse.
          if (!BridgeExt.BRIDGE_CONTEXT_ATTRIBUTE.equals(name)) {
            Object value = facesContextAttribute.getValue();
            logger.trace("Restoring FacesContext attribute name=[{0}] value=[{1}]", name, value);
            currentFacesContextAttributes.put(name, value);
            restoredFacesContextAttibutes = true;
          }
        }
      }

      if (restoredFacesContextAttibutes) {
        logger.debug("Restored FacesContext attributes");
      } else {
        logger.debug("Did not restore any FacesContext attributes");
      }

      return true;
    } else {
      return false;
    }
  }
Exemplo n.º 24
0
 private void doPostBuildActions(UIViewRoot root) {
   if (usePartialSaving(root.getViewId())) {
     stateManagementStrategy.notifyTrackChanges(root);
   }
 }