Пример #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);
    }
  }
  /**
   * @param context
   * @param resource
   * @throws IOException
   */
  public void send(ResourceContext resourceContext, InternetResource resource) throws IOException {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (null != facesContext) {
      Lifecycle facesLifecycle = getFacesLifecycle();
      PhaseListener[] phaseListeners = facesLifecycle.getPhaseListeners();
      PhaseEvent restoreViewEvent = new PhaseEvent(facesContext, PhaseId.RESTORE_VIEW, this);
      processPhaseListeners(phaseListeners, restoreViewEvent, true);
      // Fix for a http://jira.jboss.org/jira/browse/RF-1056
      if (facesContext.getResponseComplete()) {
        return;
      }
      // fix for a http://jira.jboss.com/jira/browse/RF-1064 .
      // viewRoot can be created outside.
      UIViewRoot savedViewRoot = facesContext.getViewRoot();
      try {
        // create "dummy" viewRoot, to avoid problems in phase listeners.
        UIViewRoot root = new UIViewRoot();
        String key = resource.getKey();
        if (null != key && !key.startsWith("/")) {
          key = "/" + key;
        }
        root.setViewId(key);
        root.setLocale(Locale.getDefault());
        root.setRenderKitId(RenderKitFactory.HTML_BASIC_RENDER_KIT);
        facesContext.setViewRoot(root);
        // We do not simulate other phases.
        facesContext.renderResponse();
        // Invoke after restore view phase listeners
        processPhaseListeners(phaseListeners, restoreViewEvent, false);
        // Fix for a http://jira.jboss.org/jira/browse/RF-1056
        if (!facesContext.getResponseComplete()) {
          // Invoke before render view phase listeners
          PhaseEvent renderViewEvent = new PhaseEvent(facesContext, PhaseId.RENDER_RESPONSE, this);

          try {
            processPhaseListeners(phaseListeners, renderViewEvent, true);
            sendResource(resourceContext, resource);
          } finally {
            processPhaseListeners(phaseListeners, renderViewEvent, false);
          }
        }

      } finally {
        if (null != savedViewRoot) {
          facesContext.setViewRoot(savedViewRoot);
        }
      }
    } else {
      sendResource(resourceContext, resource);
    }
  }
Пример #3
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);
 }
  @Override
  public void handle() throws FacesException {
    final Iterator<ExceptionQueuedEvent> i = getUnhandledExceptionQueuedEvents().iterator();

    while (i.hasNext()) {
      ExceptionQueuedEvent event = i.next();
      ExceptionQueuedEventContext context = (ExceptionQueuedEventContext) event.getSource();

      Throwable t = context.getException();

      final FacesContext fc = FacesContext.getCurrentInstance();
      final Map<String, Object> requestMap = fc.getExternalContext().getRequestMap();

      try {
        System.out.printf(">>> Exception caught: %s", t.getMessage());
        t.printStackTrace();

        requestMap.put("exceptionMessage", t.getMessage());

        ExternalContext extContext = fc.getExternalContext();
        String url = extContext.encodeActionURL(extContext.getRequestContextPath() + "/500.xhtml");
        extContext.redirect(url);
      } catch (Exception e) {
        String errorPageLocation = "/WEB-INF/500.xhtml";
        fc.setViewRoot(fc.getApplication().getViewHandler().createView(fc, errorPageLocation));
        fc.getPartialViewContext().setRenderAll(false);
        fc.renderResponse();
      } finally {
        i.remove();
      }
    }

    getWrapped().handle();
  }
Пример #5
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);
  }
Пример #6
0
  //
  // General Methods
  //
  private void buildTree() {
    FacesContext context = getFacesContext();
    UIViewRoot root = Util.getViewHandler(context).createView(context, null);
    root.setId("root");
    context.setViewRoot(root);

    HtmlForm form = new HtmlForm();
    form.setId("form");
    root.getChildren().add(form);

    buildPanel(form, "panel0");
    buildPanel(form, "panel1");
  }
Пример #7
0
  @Override
  public void execute(FacesContext context) throws FacesException {
    /*
     * 1. Find the bean + method that matches the correct @RequestMapping.
     */
    Set<Bean<?>> beans = getBeanManager().getBeans(Object.class, new AnnotationLiteral<Any>() {});
    Iterator<Bean<?>> beanIterator = beans.iterator();
    RequestMappingInfo current = null;

    while (beanIterator.hasNext()) {
      Bean<?> bean = beanIterator.next();
      RequestMappingInfo info = findMethodRequestMapping(context, bean);

      if (current == null) {
        current = info;
      } else if (info != null && info.getLength() > current.getLength()) {
        current = info;
      }
    }

    String viewId = null;

    if (current != null) {
      /*
       * 2. Get an instance of that bean.
       */
      Instance instance =
          CDI.current().select(current.getBean().getBeanClass(), new AnnotationLiteral<Any>() {});

      try {
        /*
         * 3. Call the required method and capture its result.
         *
         * Currently assuming String invoke() signature, but that obviously
         * needs to be expanded.
         */
        viewId = (String) current.getMethod().invoke(instance.get(), new Object[0]);
      } catch (Throwable throwable) {
        throw new FacesException(throwable);
      }
      if (context.getViewRoot() == null) {
        UIViewRoot viewRoot = new UIViewRoot();
        viewRoot.setRenderKitId("HTML_BASIC");
        /*
         * 4. Set the resulting view id on the viewroot.
         */
        viewRoot.setViewId(viewId);
        context.setViewRoot(viewRoot);
      }
    }
  }
Пример #8
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);
        }
      }
    }
  }
  public void testEncodeEnd_withJavaScript() throws Exception {
    TViewRoot root = new TViewRoot();
    htmlInputCommaText.setFraction("4");
    htmlInputCommaText.setOnblur("hoge();");
    root.setLocale(Locale.JAPAN);
    FacesContext context = getFacesContext();
    context.setViewRoot(root);

    // ## Act ##
    encodeByRenderer(renderer, context, htmlInputCommaText);

    // ## Assert ##
    System.out.println(getResponseText());
  }
  /**
   * 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();
    }
  }
  public void testEncodeEnd_withAnotherLocale() throws Exception {
    TViewRoot root = new TViewRoot();
    root.addScript(THtmlInputCommaText.class.getName(), new JavaScriptContext());
    htmlInputCommaText.setFraction("4");
    root.setLocale(Locale.GERMANY);
    FacesContext context = getFacesContext();
    context.setViewRoot(root);

    // ## Act ##
    encodeByRenderer(renderer, context, htmlInputCommaText);

    // ## Assert ##
    assertEquals(
        "<input type=\"text\" name=\"_id0\" value=\"\" onfocus=\"Teeda.THtmlInputCommaText.removeComma(this, '.');this.select();\" "
            + "onblur=\"Teeda.THtmlInputCommaText.convertByKey(this);Teeda.THtmlInputCommaText.addComma(this, 4, '.', ',');\" onkeydown=\"return Teeda.THtmlInputCommaText.keycheckForNumber(event, this, 4, ',');\" "
            + "onkeypress=\"return Teeda.THtmlInputCommaText.keycheckForNumber(event, this, 4, ',');\" onkeyup=\"Teeda.THtmlInputCommaText.convertByKey(this);\" style=\"ime-mode:disabled;\" />",
        getResponseText());
  }
  public void testEncodeEnd_withoutJavaScript() throws Exception {
    // # Arrange #
    TViewRoot root = new TViewRoot();
    htmlInputCommaText.setFraction("4");
    htmlInputCommaText.setOnblur("hoge();");
    root.setLocale(Locale.JAPAN);
    FacesContext context = getFacesContext();
    MockExternalContext extContext = (MockExternalContext) context.getExternalContext();
    extContext.setRequestPathInfo("/path1/hoge");
    FacesConfigOptions.setJavascriptNotPermittedPath(new String[] {"/not_path1"});
    context.setViewRoot(root);

    // ## Act ##
    encodeByRenderer(renderer, context, htmlInputCommaText);

    // ## Assert ##
    assertFalse(getResponseText().matches("Teeda.THtmlInputCommaText.removeComma(this);"));
  }
  public void testEncodeEnd_withErrorStyle() throws Exception {
    TViewRoot root = new TViewRoot();
    root.addScript(THtmlInputCommaText.class.getName(), new JavaScriptContext());
    root.setLocale(Locale.JAPAN);
    FacesContext context = getFacesContext();
    context.setViewRoot(root);
    htmlInputCommaText.setClientId("aaa");
    htmlInputCommaText.setErrorStyleClass("hoge");
    context.addMessage("aaa", new FacesMessage("bbb"));

    // ## Act ##
    encodeByRenderer(renderer, context, htmlInputCommaText);

    System.out.print(getResponseText());
    // ## Assert ##
    assertEquals(
        "<input type=\"text\" name=\"aaa\" value=\"\" onfocus=\"Teeda.THtmlInputCommaText.removeComma(this, ',');this.select();\" "
            + "onblur=\"Teeda.THtmlInputCommaText.convertByKey(this);Teeda.THtmlInputCommaText.addComma(this, 0, ',', '.');\" onkeydown=\"return Teeda.THtmlInputCommaText.keycheckForNumber(event, this, 0, '.');\" "
            + "onkeypress=\"return Teeda.THtmlInputCommaText.keycheckForNumber(event, this, 0, '.');\" onkeyup=\"Teeda.THtmlInputCommaText.convertByKey(this);\" style=\"ime-mode:disabled;\" class=\"hoge\" />",
        getResponseText());
  }
 @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);
      }
    }
  }
 private void thisMethodIsOnlyNecessaryBecauseOfTheWayWeForceTheViewExpiredException(
     FacesContext context) {
   UIViewRoot root = context.getApplication().getViewHandler().createView(context, "/main.xhtml");
   context.setViewRoot(root);
 }
Пример #17
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");
    }
  }
Пример #18
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);
    }
  }
Пример #19
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");
    }
  }
  /**
   * 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;
    }
  }
  @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);
        }
      }
    }
  }