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

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

    // If this requset is ending normally...
    if (e.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
      // and the user requested we save all request scoped data...
      if (null != elFlash && elFlash.isKeepMessages()) {
        // save it all.
        elFlash.saveAllMessages(context);
      }
    }
    // Otherwise, if this request is ending early...
    else if ((context.getResponseComplete() || context.getRenderResponse())
        && elFlash.isRedirect()) {
      // and the user requested we save all request scoped data...
      if (null != elFlash && elFlash.isKeepMessages()) {
        // save it all.
        addCookie(extContext, elFlash);
        elFlash.saveAllMessages(context);
      }
    }
  }
 /** Restores the messages from the cache before the Restore View phase. */
 @Override
 public synchronized void beforePhase(PhaseEvent event) {
   LOGGER.trace(event.getPhaseId().toString() + " - Before Phase");
   if (event.getPhaseId() == PhaseId.RESTORE_VIEW) {
     restoreMessages(event.getFacesContext());
   }
 }
  /*
   * (non-Javadoc)
   *
   * @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent)
   */
  public void afterPhase(PhaseEvent event) {
    try {
      FacesContext context = event.getFacesContext();

      // can't use this here. only valid at render response phase?
      String viewId = context.getViewRoot().getViewId();
      AccessLevel required = requiredLevel(viewId);
      log.debug("Required level={} for viewId={}", required, viewId);

      // check if page require access:
      switch (required) {
        case NONE:
          break;
        case ADMIN:
          redirectAdmin(event.getFacesContext());
          break;
        case CLIENT:
          redirectClient(event.getFacesContext());
          break;
        default:
          // error
          log.error("huh?");
          throw new IllegalArgumentException("Not a valid access level");
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      log.error("beforePhase caught exception", e);
    }
  }
예제 #4
0
 public void afterPhase(PhaseEvent event) {
   phaseCalled[event.getPhaseId().getOrdinal()] =
       phaseCalled[event.getPhaseId().getOrdinal()] + 1;
   if (throwExceptionOnAfter) {
     throw new IllegalStateException(
         "throwing exception on after " + event.getPhaseId().toString());
   }
 }
 @Override
 public void beforePhase(PhaseEvent arg0) {
   // TODO Auto-generated method stub
   System.out.println("Before Phase:" + arg0.getSource());
   System.out.println("Before Phase:" + arg0.getFacesContext());
   System.out.println("Before Phase:" + arg0.getClass());
   System.out.println("Before Phase:" + arg0.getPhaseId());
 }
 /**
  * Caches Faces Messages after the Invoke Application phase and clears the cache after the Render
  * Response phase.
  */
 @Override
 public synchronized void afterPhase(PhaseEvent event) {
   LOGGER.trace(event.getPhaseId().toString() + " - After Phase");
   if (event.getPhaseId() == PhaseId.INVOKE_APPLICATION) {
     cacheMessages(event.getFacesContext());
   } else if (event.getPhaseId() == PhaseId.RENDER_RESPONSE) {
     removeFromCache(event.getFacesContext());
   }
 }
예제 #7
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);
   }
 }
 // Antes da Fase
 @Override
 public void beforePhase(PhaseEvent fase) {
   System.out.println("Antes da fase: " + fase.getPhaseId());
   if (fase.getPhaseId().equals(PhaseId.RESTORE_VIEW)) {
     Session session = HibernateUtil.getSessionFactory().openSession();
     session.beginTransaction();
     FacesContextUtil.setRequestSession(session);
   }
 }
  // TODO: Blog this (MultiPageMessagesSupport)
  public void beforePhase(final PhaseEvent event) {
    FacesContext facesContext = event.getFacesContext();
    this.saveMessages(facesContext);

    if (PhaseId.RENDER_RESPONSE.equals(event.getPhaseId())) {
      if (!facesContext.getResponseComplete()) {
        this.restoreMessages(facesContext);
      }
    }
  }
예제 #10
0
 public void beforePhase(PhaseEvent event) {
   phaseCalled[event.getPhaseId().getOrdinal()] =
       phaseCalled[event.getPhaseId().getOrdinal()] + 1;
   if (callRenderResponseBeforeThisPhase == event.getPhaseId()) {
     FacesContext.getCurrentInstance().renderResponse();
   }
   if (throwExceptionOnBefore) {
     throw new IllegalStateException(
         "throwing exception on before " + event.getPhaseId().toString());
   }
 }
예제 #11
0
 /** @see javax.faces.event.PhaseListener#beforePhase(javax.faces.event.PhaseEvent) */
 public void beforePhase(PhaseEvent event) {
   LOGGER.debug("Before phase {0}", event.getPhaseId());
   if (event.getPhaseId() == PhaseId.RENDER_RESPONSE) {
     UIViewRoot viewRoot = event.getFacesContext().getViewRoot();
     if (viewRoot != null) {
       LOGGER.debug(
           "Subscribing to event {0} with listener {1}", PRERENDER_EVENT_CLASS, HOOKING_EVENT);
       viewRoot.subscribeToEvent(PRERENDER_EVENT_CLASS, HOOKING_EVENT);
     }
   }
 }
  public void afterPhase(PhaseEvent phaseEvent) {

    // This method just does some logging. It's useful to the developer to determine if a
    // navigation-rule
    // fired, causing new JSF view to be restored after the INVOKE_APPLICATION phase finished.
    if (logger.isDebugEnabled() && (phaseEvent.getPhaseId() == PhaseId.INVOKE_APPLICATION)) {
      FacesContext facesContext = phaseEvent.getFacesContext();
      String viewId = facesContext.getViewRoot().getViewId();
      logger.debug("After INVOKE_APPLICATION: viewId=[{0}]", viewId);
    }
  }
예제 #13
0
  public void afterPhase(PhaseEvent event) {
    if (checkPortletMultipleNotifications(event, false)) return;

    FacesContext context = event.getFacesContext();
    PhaseId phaseId = event.getPhaseId();
    if (phaseId.equals(PhaseId.RENDER_RESPONSE)) {
      //            appendHeaderContent(context);
    } else if (phaseId.equals(PhaseId.APPLY_REQUEST_VALUES)) {
      decodeFocusTracking(context);
      decodeScrollPosTracking(context);
    }
  }
  private static void onEvent(PhaseEvent event, String prefix) {
    PhaseId phase = event.getPhaseId();
    Object source = event.getSource();

    DebugMessage message = new DebugMessage();
    message.event = prefix + " " + phase;
    message.source = getObjectString(source);
    message.component = null;
    message.details = null;
    message.type = TYPE_LIFECYCLE;

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

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

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

      if (context.isPostback()) {
        // to a servlet JSF app...
        if (response instanceof HttpServletResponse) {
          // extract the sequence number from the cookie or portletSession
          // for the request/response pair for which this request is a postback.
          postbackSequenceString = getCookieValue(extContext);
        } else {
          /**
           * **** PortletRequest portletRequest = null; portletRequest = (PortletRequest) request;
           * // You can't retrieve a cookie in portlet. //
           * http://wiki.java.net/bin/view/Portlet/JSR168FAQ#How_can_I_set_retrieve_a_cookie
           * postbackSequenceString = (String) portletRequest.getPortletSession().
           * getAttribute(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME,
           * PortletSession.PORTLET_SCOPE); *****
           */
        }
        if (null != postbackSequenceString) {
          // Store the sequenceNumber in the request so the
          // after-render-response event can flush the flash
          // of entries from that sequence
          requestMap.put(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME, postbackSequenceString);
        }
      }
    }
    if (e.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
      // Set the REQUEST_ID cookie to be the sequence number
      addCookie(extContext, elFlash);
    }
  }
예제 #16
0
 /** @see javax.faces.event.PhaseListener#afterPhase(javax.faces.event.PhaseEvent) */
 public void afterPhase(PhaseEvent event) {
   LOGGER.debug("After phase {0}", event.getPhaseId());
   if (event.getPhaseId() == PhaseId.RENDER_RESPONSE) {
     UIViewRoot viewRoot = event.getFacesContext().getViewRoot();
     if (viewRoot != null) {
       ServiceRegisterJSComponent serviceRegister =
           InternalEventListener.findServiceRegister(FacesContext.getCurrentInstance());
       if (serviceRegister != null) {
         LOGGER.debug("Found service register with clientId {0}", serviceRegister.getClientId());
       } else {
         LOGGER.debug("Service register not found!");
       }
     }
   }
 }
  public void beforePhase(PhaseEvent phaseEvent) {

    Bridge.PortletPhase portletRequestPhase = BridgeUtil.getPortletRequestPhase();

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

      // If about to execute the INVOKE_APPLICATION phase of the JSF lifecycle, then
      if (phaseEvent.getPhaseId() == PhaseId.INVOKE_APPLICATION) {
        beforeInvokeApplicationPhase(phaseEvent);
      } else if (phaseEvent.getPhaseId() == PhaseId.RENDER_RESPONSE) {
        beforeRenderResponsePhase(phaseEvent);
      }
    }
  }
예제 #18
0
 public void afterPhase(PhaseEvent event) {
   if (PhaseId.RESTORE_VIEW.equals(event.getPhaseId())) {
     if ("/conversations.xhtml".equals(getViewId(event))) {
       try {
         HttpServletRequest request =
             (HttpServletRequest) event.getFacesContext().getExternalContext().getRequest();
         HttpServletResponse response =
             (HttpServletResponse) event.getFacesContext().getExternalContext().getResponse();
         request.getRequestDispatcher("/result.jsf").forward(request, response);
         event.getFacesContext().responseComplete();
       } catch (Exception e) {
         throw new RuntimeException("blah", e);
       }
     }
   }
 }
 // Depois da Fase
 @Override
 public void afterPhase(PhaseEvent fase) {
   System.out.println("Depois da fase: " + fase.getPhaseId());
   if (fase.getPhaseId().equals(PhaseId.RENDER_RESPONSE)) {
     Session session = FacesContextUtil.getRequestSession();
     try {
       session.getTransaction().commit();
     } catch (Exception e) {
       if (session.getTransaction().isActive()) {
         session.getTransaction().rollback();
       }
     } finally {
       session.close();
     }
   }
 }
  protected void verify(PhaseEvent phaseEvent) {
    FacesContext facesContext = phaseEvent.getFacesContext();
    String viewId = facesContext.getViewRoot().getViewId();
    SecurityBean securityBean = SecurityBean.getInstance();

    /*
     * Primero se valida que la sesión no haya caducado
     * */
    if (SecurityBean.isSessionExpired(facesContext)) {
      try {
        doRedirect(facesContext, "/resources/errorpages/errorSessionExpired.jsp");
        facesContext.responseComplete();

      } catch (Exception e) {
        e.printStackTrace();
      }

    } else if (!securityBean.verifyPageAccess(viewId)) {
      /*
       * Luego se valida que no se esté accediendo a un recurso sin autenticación
       * */
      HttpServletResponse response =
          (HttpServletResponse) facesContext.getExternalContext().getResponse();
      try {
        response.sendError(403); // 403: Forbidden error
        facesContext.responseComplete();

      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
 @Override
 public void beforePhase(PhaseEvent phaseEvent) {
   PhaseId currPhaseId = phaseEvent.getPhaseId();
   if (currPhaseId.equals(PhaseId.RENDER_RESPONSE)) {
     verify(phaseEvent);
   }
 }
 @Override
 public void afterPhase(PhaseEvent phaseEvent) {
   PhaseId currPhaseId = phaseEvent.getPhaseId();
   if (currPhaseId.equals(PhaseId.RESTORE_VIEW)) {
     verify(phaseEvent);
   }
 }
예제 #23
0
 @Override
 public void beforePhase(PhaseEvent event) {
   FacesContext context = event.getFacesContext();
   HttpServletRequest httpRequest = (HttpServletRequest) context.getExternalContext().getRequest();
   try {
     URLPolicyService service = getURLPolicyService();
     if (service.isCandidateForDecoding(httpRequest)) {
       // Make sure we're in a transaction, and that Seam knows it.
       // Sometimes, when there is a page action, SeamPhaseListener
       // commits the transaction in RENDER_RESPONSE before this
       // phase listener executes, but does not start a new one.
       // (SeamPhaseListener.handleTransactionsAfterPageActions)
       if (!Transaction.instance().isActiveOrMarkedRollback()) {
         Transaction.instance().begin();
       }
       // hot reload hook, maybe to move up so that it's handled on
       // all requests, not only the ones using the URLservice
       // framework (?)
       resetHotReloadContext(context);
       // restore state
       service.navigate(context);
       // apply requests parameters after - they may need the state
       // to be restored first.
       service.applyRequestParameters(context);
     }
   } catch (RuntimeException | SystemException | NotSupportedException e) {
     handleException(context, e);
   }
 }
  /**
   * This method is called before the {@link PhaseId#RENDER_RESPONSE} phase of the JSF lifecycle is
   * executed. The purpose of this timing is to pick up where the {@link
   * #beforeInvokeApplicationPhase(PhaseEvent)} method left off. It might be the case that a
   * navigation-rule has fired and a NEW JSF view has been loaded up after the {@link
   * PhaseId#APPLY_REQUEST_VALUES} phase (in the case of immediate="true") or the {@link
   * PhaseId#INVOKE_APPLICATION} phase (in the case of immediate="false") has completed. If this is
   * the case, then the list of head resourceIds in the {@link HeadManagedBean} needs to be
   * repopulated from the list found in the Flash scope.
   */
  protected void beforeAjaxifiedRenderResponsePhase(PhaseEvent phaseEvent) {
    FacesContext facesContext = phaseEvent.getFacesContext();
    Flash flash = facesContext.getExternalContext().getFlash();
    String viewId = facesContext.getViewRoot().getViewId();

    @SuppressWarnings("unchecked")
    Set<String> headResourceIdsFromFlash = (Set<String>) flash.get(HEAD_RESOURCE_IDS);

    if (headResourceIdsFromFlash != null) {

      HeadManagedBean headManagedBean = HeadManagedBean.getInstance(facesContext);

      if (headManagedBean != null) {

        Set<String> managedBeanResourceIds = headManagedBean.getHeadResourceIds();

        for (String resourceIdFromFlash : headResourceIdsFromFlash) {

          if (!managedBeanResourceIds.contains(resourceIdFromFlash)) {
            managedBeanResourceIds.add(resourceIdFromFlash);
            logger.debug(
                "Added resourceId=[{0}] from the Flash scope to the list of resourceIds in the HeadManagedBean for viewId=[{1}]",
                resourceIdFromFlash, viewId);
          }
        }
      }
    }
  }
  /**
   * This method is called before the {@link PhaseId#INVOKE_APPLICATION} phase of the JSF lifecycle
   * is executed. The purpose of this timing is to handle the case when the user clicks on a {@link
   * UICommand} component (like h:commandButton or h:commandLink) that has been either
   * Auto-ajaxified by ICEfaces, or manually Ajaxified by the developer using code like the
   * following:
   *
   * <p><code>&lt;f:ajax execute="@form" render=" @form" /&gt;</code>
   *
   * <p>When this happens, we need to somehow remember the list of JavaScript and/or CSS resources
   * that are currently in the &lt;head&gt; section of the portal page. This is because a
   * navigation-rule might fire which could cause a new view to be rendered in the {@link
   * PhaseId#RENDER_RESPONSE} phase that is about to follow this {@link PhaseId#INVOKE_APPLICATION}
   * phase. The list of resources would be contained in the {@link HeadManagedBean} {@link
   * ViewScoped} instance that is managed by the JSF managed-bean facility. The list would have been
   * populated initially in the {@link HeadManagedBean} by the {@link HeadRender} during the initial
   * HTTP-GET of the portal page. The way we "remember" the list is by placing it into the JSF 2
   * {@link Flash} scope. This scope is used because it is very short-lived and survives any
   * navigation-rules that might fire, thereby causing the rendering of a new JSF view.
   *
   * <p>The story is continued in the {@link #beforeRenderResponsePhase(PhaseEvent)} method below...
   */
  protected void beforeInvokeApplicationPhase(PhaseEvent phaseEvent) {

    // Get the list of resourceIds that might be contained in the Flash scope. Note that they would
    // have been
    // placed into the Flash scope by this very same method, except during in the case below for the
    // RENDER_RESPONSE phase.
    FacesContext facesContext = phaseEvent.getFacesContext();
    Flash flash = facesContext.getExternalContext().getFlash();

    @SuppressWarnings("unchecked")
    Set<String> headResourceIdsFromFlash = (Set<String>) flash.get("HEAD_RESOURCE_IDS");

    // Log the viewId so that it can be visually compared with the value that is to be logged after
    // the
    // INVOKE_APPLICATION phase completes.
    logger.debug("Before INVOKE_APPLICATION: viewId=[{0}]", facesContext.getViewRoot().getViewId());

    // If the Flash scope does not yet contain a list of head resourceIds, then the scope needs to
    // be populated
    // with a list so that the {@link #beforeRenderResponsePhase(PhaseEvent)} method below can
    // retrieve it.
    if (headResourceIdsFromFlash == null) {

      HeadManagedBean headManagedBean = HeadManagedBean.getInstance(facesContext);

      // Note that in the case where a portlet RESOURCE_PHASE was invoked with a "portlet:resource"
      // type of URL,
      // there will be no HeadManagedBean available.
      if (headManagedBean != null) {
        flash.put("HEAD_RESOURCE_IDS", headManagedBean.getHeadResourceIds());
      }
    }
  }
  /** Metodo responsavel por interceptar os eventos e validar o acesso as paginas do sistema. */
  public void afterPhase(PhaseEvent event) {

    FacesContext context = event.getFacesContext();

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

    LoginBean loginBean =
        context.getApplication().evaluateExpressionGet(context, "#{loginBean}", LoginBean.class);

    if (!viewId.equals("/logout.xhtml") && !viewId.equals("/login.xhtml")) {

      loginBean.autenticar();

      if (loginBean.getUsuarioAutenticado() != null) {
        ExternalContext contextCurrent = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) contextCurrent.getRequest();
        this.remoteAddress = request.getRemoteAddr();
        logger.warning("Acesso permitido em " + viewId + " por " + this.remoteAddress);

      } else {
        ExternalContext externalContext = context.getExternalContext();
        HttpSession httpSession = (HttpSession) externalContext.getSession(false);
        httpSession.invalidate();

        ExternalContext contextCurrent = FacesContext.getCurrentInstance().getExternalContext();
        HttpServletRequest request = (HttpServletRequest) contextCurrent.getRequest();

        this.remoteAddress = request.getRemoteAddr();

        if (loginBean.getUsuarioAutenticado() == null) {
          logger.warning("Acesso indevido em " + viewId + " por " + this.remoteAddress + ".");
        }
      }
    }
  }
 public void afterPhase(PhaseEvent event) {
   FacesContext facesContext = event.getFacesContext();
   AddResource addResource = AddResourceFactory.getInstance(facesContext);
   String jsTxt = genJavaScriptCodeForMessages(facesContext);
   if (jsTxt != null) {
     addResource.addInlineScriptAtPosition(facesContext, AddResource.HEADER_BEGIN, jsTxt);
   }
 }
예제 #28
0
 public void beforePhase(PhaseEvent event) {
   if (PhaseId.RESTORE_VIEW.equals(event.getPhaseId())) {
     String uri =
         ((HttpServletRequest) event.getFacesContext().getExternalContext().getRequest())
             .getRequestURI();
     if (uri.contains("missing-page-error")) {
       try {
         HttpServletResponse response =
             (HttpServletResponse) event.getFacesContext().getExternalContext().getResponse();
         response.sendError(404);
         event.getFacesContext().responseComplete();
       } catch (Exception e) {
         throw new RuntimeException("blah", e);
       }
     }
   }
 }
  public void beforePhase(PhaseEvent phaseEvent) {

    Bridge.PortletPhase portletRequestPhase =
        BridgeUtil.getPortletRequestPhase(phaseEvent.getFacesContext());

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

      if (phaseEvent.getPhaseId() == PhaseId.APPLY_REQUEST_VALUES) {
        beforeApplyRequestValuesPhase(phaseEvent);
      } else if (phaseEvent.getPhaseId() == PhaseId.RENDER_RESPONSE) {
        FacesContext facesContext = phaseEvent.getFacesContext();

        if (facesContext.getPartialViewContext().isAjaxRequest()) {
          beforeAjaxifiedRenderResponsePhase(phaseEvent);
        }
      }
    }
  }
 /**
  * @param phaseListener
  * @param phaseEvent
  * @param beforePhase
  */
 private void invokePhaseListener(
     PhaseListener phaseListener, PhaseEvent phaseEvent, boolean beforePhase) {
   if (phaseEvent.getPhaseId().equals(phaseListener.getPhaseId())
       || PhaseId.ANY_PHASE.equals(phaseListener.getPhaseId())) {
     try {
       if (beforePhase) {
         phaseListener.beforePhase(phaseEvent);
       } else {
         phaseListener.afterPhase(phaseEvent);
       }
     } catch (Exception e) {
       _log.debug(
           "Exception in PhaseListener, phase :"
               + phaseEvent.getPhaseId().toString()
               + (beforePhase ? " : beforePhase" : " : afterPhase"),
           e);
     }
   }
 }