Esempio n. 1
0
  private void restoreView(FacesContext context) throws FacesException {
    Application app = context.getApplication();

    if (app instanceof ApplicationImpl) ((ApplicationImpl) app).initRequest();

    ViewHandler view = app.getViewHandler();

    view.initView(context);

    UIViewRoot viewRoot = context.getViewRoot();

    if (viewRoot != null) {
      ExternalContext extContext = context.getExternalContext();

      viewRoot.setLocale(extContext.getRequestLocale());

      doSetBindings(context.getELContext(), viewRoot);

      return;
    }

    String viewId = calculateViewId(context);

    String renderKitId = view.calculateRenderKitId(context);

    RenderKitFactory renderKitFactory =
        (RenderKitFactory) FactoryFinder.getFactory(FactoryFinder.RENDER_KIT_FACTORY);

    RenderKit renderKit = renderKitFactory.getRenderKit(context, renderKitId);

    ResponseStateManager stateManager = renderKit.getResponseStateManager();

    if (stateManager.isPostback(context)) {
      viewRoot = view.restoreView(context, viewId);

      if (viewRoot != null) {
        doSetBindings(context.getELContext(), viewRoot);
      } else {
        // XXX: backward compat issues with ViewHandler and StateManager

        // throw new ViewExpiredException(L.l("{0} is an expired view", viewId));

        context.renderResponse();

        viewRoot = view.createView(context, viewId);

        context.setViewRoot(viewRoot);
      }

      context.setViewRoot(viewRoot);
    } else {
      context.renderResponse();

      viewRoot = view.createView(context, viewId);

      context.setViewRoot(viewRoot);
    }
  }
Esempio n. 2
0
 public static void refresh() {
   FacesContext context = FacesContext.getCurrentInstance();
   Application application = context.getApplication();
   ViewHandler viewHandler = application.getViewHandler();
   UIViewRoot viewRoot = viewHandler.createView(context, context.getViewRoot().getViewId());
   context.setViewRoot(viewRoot);
 }
  public UIViewRoot createView(FacesContext arg0, String arg1) {
    UIViewRoot root = m_wrapped.createView(arg0, arg1);

    if (root != null) {
      // restore messages
      MessageSaver.restoreMessages(arg0);
    }

    return root;
  }
Esempio n. 4
0
  /** Reload the current active page. */
  public static void reloadPage() {
    FacesContext context = FacesContext.getCurrentInstance();

    String viewId = context.getViewRoot().getViewId();

    ViewHandler handler = context.getApplication().getViewHandler();

    UIViewRoot root = handler.createView(context, viewId);
    root.setViewId(viewId);
    context.setViewRoot(root);
  }
Esempio n. 5
0
  /**
   * Determine the next view based on the current view (<code>from-view-id</code> stored in <code>
   * FacesContext</code>), <code>fromAction</code> and <code>outcome</code>.
   *
   * @param context The <code>FacesContext</code>
   * @param fromAction the action reference string
   * @param outcome the outcome string
   */
  public void handleNavigation(FacesContext context, String fromAction, String outcome) {
    if (context == null) {
      String message =
          MessageUtils.getExceptionMessageString(
              MessageUtils.NULL_PARAMETERS_ERROR_MESSAGE_ID, "context");
      throw new NullPointerException(message);
    }
    if (outcome == null) {
      return; // Explicitly remain on the current view
    }
    CaseStruct caseStruct = getViewId(context, fromAction, outcome);
    ExternalContext extContext = context.getExternalContext();
    if (caseStruct != null) {
      ViewHandler viewHandler = Util.getViewHandler(context);
      assert (null != viewHandler);

      if (caseStruct.navCase.isRedirect()) {
        // perform a 302 redirect.
        String newPath = viewHandler.getActionURL(context, caseStruct.viewId);
        try {
          if (logger.isLoggable(Level.FINE)) {
            logger.fine(
                "Redirecting to path "
                    + newPath
                    + " for outcome "
                    + outcome
                    + "and viewId "
                    + caseStruct.viewId);
          }
          // encode the redirect to ensure session state
          // is maintained
          extContext.redirect(extContext.encodeActionURL(newPath));
        } catch (java.io.IOException ioe) {
          if (logger.isLoggable(Level.SEVERE)) {
            logger.log(Level.SEVERE, "jsf.redirect_failed_error", newPath);
          }
          throw new FacesException(ioe.getMessage(), ioe);
        }
        context.responseComplete();
        if (logger.isLoggable(Level.FINE)) {
          logger.fine("Response complete for " + caseStruct.viewId);
        }
      } else {
        UIViewRoot newRoot = viewHandler.createView(context, caseStruct.viewId);
        context.setViewRoot(newRoot);
        if (logger.isLoggable(Level.FINE)) {
          logger.fine("Set new view in FacesContext for " + caseStruct.viewId);
        }
      }
    }
  }
  /**
   * Jsf dispatch page.
   *
   * @param fctx the faces context
   * @param page the pge
   */
  private void jsfDispatchPage(FacesContext fctx, String page) {
    LifecycleFactory lf =
        (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
    Lifecycle lifecycle = lf.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
    ViewHandler vh = fctx.getApplication().getViewHandler();
    fctx.getViewRoot().setRenderKitId(vh.calculateRenderKitId(fctx));
    fctx.setViewRoot(vh.createView(fctx, page));

    // view rendering
    try {
      lifecycle.render(fctx);
    } catch (Exception e) {
      LOG.log(Level.INFO, "Error while rendering page. Attempting again" + page, e);
      lifecycle.render(fctx);
    } finally {
      fctx.release();
    }
  }
 @Override
 public void beforePhase(PhaseEvent event) {
   FacesContext facesContext = event.getFacesContext();
   ExternalContext externalContext = facesContext.getExternalContext();
   HttpSession httpSession = (HttpSession) externalContext.getSession(false);
   boolean newSession = (httpSession == null) || (httpSession.isNew());
   boolean postBack = !externalContext.getRequestParameterMap().isEmpty();
   boolean timedOut = postBack && newSession;
   if (timedOut) {
     Application application = facesContext.getApplication();
     ViewHandler viewHandler = application.getViewHandler();
     UIViewRoot view = viewHandler.createView(facesContext, "/main.xhtml");
     facesContext.setViewRoot(view);
     facesContext.renderResponse();
     try {
       viewHandler.renderView(facesContext, view);
       facesContext.responseComplete();
     } catch (Exception e) {
       throw new FacesException("Session timed out", e);
     }
   }
 }
  // executa antes de qualquer renderizar ao usuário
  public void beforePhase(PhaseEvent event) {
    FacesContext context = FacesContext.getCurrentInstance();
    String viewId = context.getViewRoot().getViewId();
    System.out.println("View ID:" + viewId);

    // verifica as páginas que não possuem acesso externo
    if (viewId.equals("/admin/formCategoria.xhtml")
        || viewId.equals("/admin/formProduto.xhtml")
        || viewId.equals("/admin/home.xhtml")
        || viewId.equals("/admin/mostrarCategorias.xhtml")
        || viewId.equals("/admin/mostrarProdutos.xhtml")
        || viewId.equals("/admin/mostrarCompras.xhtml")) {

      // recupera os dados que estão em
      // sessão em adminController
      Application app = context.getApplication();
      AdminController adminEmSessao =
          (AdminController)
              app.evaluateExpressionGet(context, "#{adminController}", AdminController.class);

      // se não houver administrador logado
      if (adminEmSessao.getAdmin().getId() == null) {

        // armazena a página ao qual o usuário está
        // tentando entrar em sessão
        // através da classe AdminController
        adminEmSessao.setOriginalViewId(viewId);
        // em seguida, cria a árvore de componentes
        // para a página admin.jsf
        // que exigirá o login e senha
        ViewHandler viewHandler = app.getViewHandler();
        UIViewRoot viewRoot = viewHandler.createView(context, "/admin/admin.xhtml");
        context.setViewRoot(viewRoot);
      }
    }
  }
 public UIViewRoot createView(FacesContext context, String strUID) {
   UIViewRoot ret = viewHandler.createView(context, strUID);
   return ret;
 }
  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();
      }
    }
  }
Esempio n. 11
0
  /**
   * PRECONDITION: the necessary factories have been installed in the ServletContext attr set.
   *
   * <p>
   *
   * <p>POSTCONDITION: The facesContext has been initialized with a tree.
   */
  public void execute(FacesContext facesContext) throws FacesException {

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Entering RestoreViewPhase");
    }
    if (null == facesContext) {
      throw new FacesException(
          MessageUtils.getExceptionMessageString(MessageUtils.NULL_CONTEXT_ERROR_MESSAGE_ID));
    }

    // If an app had explicitely set the tree in the context, use that;
    //
    UIViewRoot viewRoot = facesContext.getViewRoot();
    if (viewRoot != null) {
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Found a pre created view in FacesContext");
      }
      facesContext.getViewRoot().setLocale(facesContext.getExternalContext().getRequestLocale());

      // do per-component actions
      UIViewRoot root = facesContext.getViewRoot();
      final PostRestoreStateEvent event = new PostRestoreStateEvent(root);
      try {
        root.visitTree(
            VisitContext.createVisitContext(facesContext),
            new VisitCallback() {

              public VisitResult visit(VisitContext context, UIComponent target) {
                event.setComponent(target);
                target.processEvent(event);
                return VisitResult.ACCEPT;
              }
            });
      } catch (AbortProcessingException e) {
        facesContext
            .getApplication()
            .publishEvent(
                ExceptionQueuedEvent.class, new ExceptionQueuedEventContext(facesContext, e));
      }

      if (!facesContext.isPostback()) {
        facesContext.renderResponse();
      }
      return;
    }

    // Reconstitute or create the request tree
    Map requestMap = facesContext.getExternalContext().getRequestMap();
    String viewId = (String) requestMap.get("javax.servlet.include.path_info");
    if (viewId == null) {
      viewId = facesContext.getExternalContext().getRequestPathInfo();
    }

    // It could be that this request was mapped using
    // a prefix mapping in which case there would be no
    // path_info.  Query the servlet path.
    if (viewId == null) {
      viewId = (String) requestMap.get("javax.servlet.include.servlet_path");
    }

    if (viewId == null) {
      viewId = facesContext.getExternalContext().getRequestServletPath();
    }

    if (viewId == null) {
      if (LOGGER.isLoggable(Level.WARNING)) {
        LOGGER.warning("viewId is null");
      }
      throw new FacesException(
          MessageUtils.getExceptionMessageString(MessageUtils.NULL_REQUEST_VIEW_ERROR_MESSAGE_ID));
    }

    ViewHandler viewHandler = Util.getViewHandler(facesContext);

    boolean isPostBack = (facesContext.isPostback() && !isErrorPage(facesContext));
    if (isPostBack) {
      // try to restore the view
      viewRoot = viewHandler.restoreView(facesContext, viewId);
      if (viewRoot == null) {
        if (is11CompatEnabled(facesContext)) {
          // 1.1 -> create a new view and flag that the response should
          //        be immediately rendered
          if (LOGGER.isLoggable(Level.FINE)) {
            LOGGER.fine("Postback: recreating a view for " + viewId);
          }
          viewRoot = viewHandler.createView(facesContext, viewId);
          facesContext.renderResponse();

        } else {
          Object[] params = {viewId};
          throw new ViewExpiredException(
              MessageUtils.getExceptionMessageString(
                  MessageUtils.RESTORE_VIEW_ERROR_MESSAGE_ID, params),
              viewId);
        }
      }

      facesContext.setViewRoot(viewRoot);

      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Postback: restored view for " + viewId);
      }
    } else {
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("New request: creating a view for " + viewId);
      }

      ViewDeclarationLanguage vdl =
          facesContext
              .getApplication()
              .getViewHandler()
              .getViewDeclarationLanguage(facesContext, viewId);

      if (vdl != null) {
        // If we have one, get the ViewMetadata...
        ViewMetadata metadata = vdl.getViewMetadata(facesContext, viewId);

        if (metadata != null) { // perhaps it's not supported
          // and use it to create the ViewRoot.  This will have, at most
          // the UIViewRoot and its metadata facet.
          viewRoot = metadata.createMetadataView(facesContext);

          // Only skip to render response if there are no view parameters
          Collection<UIViewParameter> params = ViewMetadata.getViewParameters(viewRoot);
          if (params.isEmpty()) {
            facesContext.renderResponse();
          }
        }
      } else {
        facesContext.renderResponse();
      }

      if (null == viewRoot) {
        viewRoot = (Util.getViewHandler(facesContext)).createView(facesContext, viewId);
      }
      facesContext.setViewRoot(viewRoot);
      assert (null != viewRoot);
      facesContext.getApplication().publishEvent(PostAddToViewEvent.class, viewRoot);
    }

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Exiting RestoreViewPhase");
    }
  }
  private String processException(Exception exp, int flag) {

    String message = "";
    String type = "";
    Date requestDate = null;
    Date reviewDate = null;

    switch (flag) {
      case 0:
        LoanProfile loanProfile = ((DuplicateLoanProfileException) exp).getLoanProfile();
        type = loanProfile.getProfileState().getCode();
        requestDate = loanProfile.getRequestDate();
        reviewDate = loanProfile.getReviewDate();
        break;

      case 1:
        ExchangeProfile exchangeProfile =
            ((DuplicateExchangeProfileException) exp).getExchangeProfile();
        type = exchangeProfile.getProfileState().getCode();
        requestDate = exchangeProfile.getRequestDate();
        reviewDate = exchangeProfile.getReviewDate();
        break;

      case 2:
        ProberProfile proberProfile = ((DuplicateProberProfileException) exp).getProberProfile();
        type = proberProfile.getProfileState().getCode();
        requestDate = proberProfile.getRequestDate();
        reviewDate = proberProfile.getReviewDate();
        break;
    }

    if (type.equalsIgnoreCase(ProfileState.NEW_REQUEST_STATE)) {

      message =
          JsfUtils.getStringFromBundle("yourRequestForUnit")
              + " "
              + JsfUtils.getStringFromBundle(this.selectedUnitOrLib.getName())
              + JsfUtils.getStringFromBundle("andMembershipAt")
              + " "
              + JsfUtils.getStringFromBundle(
                  UserManagementDataMap.convertRequestType(this.selectedRequestType))
              + JsfUtils.getStringFromBundle("inDate")
              + " "
              + String.valueOf(requestDate)
              + JsfUtils.getStringFromBundle("isRegisteredAndCurrentlyIsUnderProcessing");

    } else if (type.equalsIgnoreCase(ProfileState.CONFIRMED_REQUEST_STATE)) {

      message =
          JsfUtils.getStringFromBundle("yourRequestForUnit")
              + " "
              + JsfUtils.getStringFromBundle(this.selectedUnitOrLib.getName())
              + JsfUtils.getStringFromBundle("andMembershipAt")
              + " "
              + JsfUtils.getStringFromBundle(
                  UserManagementDataMap.convertRequestType(this.selectedRequestType))
              + JsfUtils.getStringFromBundle("inDate")
              + " "
              + String.valueOf(requestDate)
              + JsfUtils.getStringFromBundle("isRegisteredAndInDate")
              + " "
              + String.valueOf(reviewDate)
              + JsfUtils.getStringFromBundle("havebeenRejected")
              + JsfUtils.getStringFromBundle("wouldYouLikeToSubmitANewRequest");

    } else if (type.equalsIgnoreCase(ProfileState.REJECTED_REQUEST_STATE)) {

      message =
          JsfUtils.getStringFromBundle("yourRequestForUnit")
              + " "
              + JsfUtils.getStringFromBundle(this.selectedUnitOrLib.getName())
              + JsfUtils.getStringFromBundle("andMembershipAt")
              + " "
              + JsfUtils.getStringFromBundle(
                  UserManagementDataMap.convertRequestType(this.selectedRequestType))
              + JsfUtils.getStringFromBundle("inDate")
              + " "
              + String.valueOf(requestDate)
              + JsfUtils.getStringFromBundle("isConfirmed");

    } else assert true : "Invalid Profile State!!!";

    FacesContext context = FacesContext.getCurrentInstance();
    ViewHandler viewHandler = context.getApplication().getViewHandler();
    UIViewRoot dialog =
        viewHandler.createView(context, "/usermanagement/generalPages/showMessagePage.jspx");

    Map properties = new HashMap();
    properties.put("width", new Integer(300));
    properties.put("height", new Integer(400));

    Map params = new HashMap();
    params.put(UserManagementConstants.DIALOG_MESSAGE, message);
    RequestContext requestContext = RequestContext.getCurrentInstance();
    requestContext.launchDialog(dialog, params, null, true, properties);

    return "";
  }
Esempio n. 13
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);
    }
  }
Esempio n. 14
0
  /**
   * PRECONDITION: the necessary factories have been installed in the ServletContext attr set.
   *
   * <p>
   *
   * <p>POSTCONDITION: The facesContext has been initialized with a tree.
   */
  public void execute(FacesContext facesContext) throws FacesException {

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Entering RestoreViewPhase");
    }
    if (null == facesContext) {
      throw new FacesException(
          MessageUtils.getExceptionMessageString(MessageUtils.NULL_CONTEXT_ERROR_MESSAGE_ID));
    }

    // If an app had explicitely set the tree in the context, use that;
    //
    UIViewRoot viewRoot = facesContext.getViewRoot();
    if (viewRoot != null) {
      if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.fine("Found a pre created view in FacesContext");
      }
      facesContext.getViewRoot().setLocale(facesContext.getExternalContext().getRequestLocale());

      // do per-component actions
      deliverPostRestoreStateEvent(facesContext);

      if (!facesContext.isPostback()) {
        facesContext.renderResponse();
      }
      return;
    }
    FacesException thrownException = null;

    try {

      // Reconstitute or create the request tree
      Map requestMap = facesContext.getExternalContext().getRequestMap();
      String viewId = (String) requestMap.get("javax.servlet.include.path_info");
      if (viewId == null) {
        viewId = facesContext.getExternalContext().getRequestPathInfo();
      }

      // It could be that this request was mapped using
      // a prefix mapping in which case there would be no
      // path_info.  Query the servlet path.
      if (viewId == null) {
        viewId = (String) requestMap.get("javax.servlet.include.servlet_path");
      }

      if (viewId == null) {
        viewId = facesContext.getExternalContext().getRequestServletPath();
      }

      if (viewId == null) {
        throw new FacesException(
            MessageUtils.getExceptionMessageString(
                MessageUtils.NULL_REQUEST_VIEW_ERROR_MESSAGE_ID));
      }

      ViewHandler viewHandler = Util.getViewHandler(facesContext);

      boolean isPostBack = (facesContext.isPostback() && !isErrorPage(facesContext));
      if (isPostBack) {
        if (isCSRFOptionEnabled(facesContext)) {
          String convertedViewId = viewHandler.deriveViewId(facesContext, viewId);
          if (!TokenHelper.verifyToken(facesContext, convertedViewId)) {
            throw new FacesException("Token verification failed.");
          }
        }
        facesContext.setProcessingEvents(false);
        // try to restore the view
        viewRoot = viewHandler.restoreView(facesContext, viewId);
        if (viewRoot == null) {
          if (is11CompatEnabled(facesContext)) {
            // 1.1 -> create a new view and flag that the response should
            //        be immediately rendered
            if (LOGGER.isLoggable(Level.FINE)) {
              LOGGER.fine("Postback: recreating a view for " + viewId);
            }
            viewRoot = viewHandler.createView(facesContext, viewId);
            facesContext.renderResponse();

          } else {
            Object[] params = {viewId};
            throw new ViewExpiredException(
                MessageUtils.getExceptionMessageString(
                    MessageUtils.RESTORE_VIEW_ERROR_MESSAGE_ID, params),
                viewId);
          }
        }

        facesContext.setViewRoot(viewRoot);
        facesContext.setProcessingEvents(true);
        if (LOGGER.isLoggable(Level.FINE)) {
          LOGGER.fine("Postback: restored view for " + viewId);
        }
      } else {
        if (LOGGER.isLoggable(Level.FINE)) {
          LOGGER.fine("New request: creating a view for " + viewId);
        }

        ViewDeclarationLanguage vdl =
            facesContext
                .getApplication()
                .getViewHandler()
                .getViewDeclarationLanguage(facesContext, viewId);

        if (vdl != null) {
          // If we have one, get the ViewMetadata...
          ViewMetadata metadata = vdl.getViewMetadata(facesContext, viewId);

          if (metadata != null) { // perhaps it's not supported
            // and use it to create the ViewRoot.  This will have, at most
            // the UIViewRoot and its metadata facet.
            viewRoot = metadata.createMetadataView(facesContext);

            // Only skip to render response if there are no view parameters
            Collection<UIViewParameter> params = ViewMetadata.getViewParameters(viewRoot);
            if (params.isEmpty()) {
              facesContext.renderResponse();
            }
          }
        } else {
          facesContext.renderResponse();
        }

        if (null == viewRoot) {
          viewRoot = (Util.getViewHandler(facesContext)).createView(facesContext, viewId);
        }
        facesContext.setViewRoot(viewRoot);
        assert (null != viewRoot);
      }
    } catch (FacesException fe) {
      thrownException = fe;
    } finally {
      if (null == thrownException) {
        deliverPostRestoreStateEvent(facesContext);
      } else {
        throw thrownException;
      }
    }

    if (LOGGER.isLoggable(Level.FINE)) {
      LOGGER.fine("Exiting RestoreViewPhase");
    }
  }