/* * (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); } }
/** * 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()); } }
/** * 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); } }
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); } } } }
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(); } } }
/** * 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); } } }
/** * 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); } } } } }
/** 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 + "."); } } } }
@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#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><f:ajax execute="@form" render=" @form" /></code> * * <p>When this happens, we need to somehow remember the list of JavaScript and/or CSS resources * that are currently in the <head> 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()); } } }
/** 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()); } }
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); } }
@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()); }
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); } } } }
// 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); } } }
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); } }
/** @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); } } }
@Override public void afterPhase(PhaseEvent event) { FacesContext facesContext = event.getFacesContext(); String currentPage = facesContext.getViewRoot().getViewId(); boolean isLoginPage = (currentPage.lastIndexOf("/login.xhtml") > -1) ? true : false; HttpSession sesion = (HttpSession) facesContext.getExternalContext().getSession(true); Object usuario = sesion.getAttribute("usuario"); if (!isLoginPage && usuario == null) { NavigationHandler nh = facesContext.getApplication().getNavigationHandler(); nh.handleNavigation(facesContext, null, "/login.xhtml"); } }
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); } }
@Override public void beforePhase(PhaseEvent event) { FacesContext facesContext = event.getFacesContext(); HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse(); response.addHeader("Pragma", "no-cache"); response.addHeader("Cache-Control", "no-cache"); // Stronger according to blog comment below that references HTTP spec response.addHeader("Cache-Control", "no-store"); response.addHeader("Cache-Control", "must-revalidate"); // some date in the past response.addHeader("Expires", "Mon, 8 Aug 2006 10:00:00 GMT"); }
@Override public void afterPhase(PhaseEvent event) { FacesContext facesContext = event.getFacesContext(); if (facesContext.getViewRoot() == null) { try { ExternalContext econtext = facesContext.getExternalContext(); String contextPath = ((ServletContext) econtext.getContext()).getContextPath(); econtext.redirect(contextPath + "/"); } catch (IOException ex) { Logger.getLogger(DefaultPhaseListener.class.getName()).log(Level.SEVERE, null, ex); } } }
/** * 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); } }
@Override public void afterPhase(PhaseEvent event) { FacesContext fc = event.getFacesContext(); if (permite(fc)) { } else { // Verifica se esta na página principal boolean paginaLogin = fc.getViewRoot().getViewId().lastIndexOf("index") > -1 ? true : false; if (!paginaLogin) { NavigationHandler nh = fc.getApplication().getNavigationHandler(); nh.handleNavigation(fc, null, "naologado"); } } }
/** @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!"); } } } }
@Override public void beforePhase(PhaseEvent event) { log.info("intercepted " + event); HttpSession httpSession = (HttpSession) event.getFacesContext().getExternalContext().getSession(false); Object entityViewerInitializer = httpSession.getAttribute("entityViewerInitializer"); if (entityViewerInitializer != null) { // viewers rely upon having an authenticated user in place, which is not the case if Tomcat // has sent us to the login page if (((EntityViewerInitializer) entityViewerInitializer).isReadyForInitialization()) { httpSession.removeAttribute("entityViewerInitializer"); ((EntityViewerInitializer) entityViewerInitializer).apply(); } } }
@Override public void afterPhase(PhaseEvent event) { FacesContext facesContext = event.getFacesContext(); ExternalContext externalContext = facesContext.getExternalContext(); HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); if (!request.getMethod().equals("POST")) { Map<?, ?> flashScope = (Map<?, ?>) facesContext .getApplication() .createValueBinding("#{flashScope}") .getValue(facesContext); flashScope.clear(); } }
/** * Determines if the user is authenticated. If not, direct the user to the login view, otherwise * all the user to continue to the requested view. * * <p>Implementation Note: We do this in the <code>afterPhase</code> to make use of the <code> * NavigationHandler</code>. */ public void afterPhase(PhaseEvent event) { FacesContext context = event.getFacesContext(); if (userExists(context)) { // allow processing of the requested view return; } else { // send the user to the login view if (requestingSecureView(context)) { context.responseComplete(); context .getApplication() .getNavigationHandler() .handleNavigation(context, null, USER_LOGIN_OUTCOME); } } }
@SuppressWarnings("unchecked") public void beforePhase(PhaseEvent event) { FacesContext facesContext = event.getFacesContext(); UIViewRoot root = facesContext.getViewRoot(); AddResource addResource = AddResourceFactory.getInstance(facesContext); addReferences(facesContext, addResource); visitComponent(facesContext, root); // String jsTxt = genJavaScriptCodeForMessages(facesContext); // if (jsTxt != null) { // addResource.addInlineScriptAtPosition(facesContext, // AddResource.HEADER_BEGIN, jsTxt); // } String styleSheetCode = genStyleCode(facesContext); if (styleSheetCode != null) { addResource.addInlineStyleAtPosition(facesContext, AddResource.HEADER_BEGIN, styleSheetCode); } }
@Override public void afterPhase(PhaseEvent event) { ExceptionHandler exceptionHandler = event.getFacesContext().getExceptionHandler(); if (Iterables.isEmpty(exceptionHandler.getUnhandledExceptionQueuedEvents())) { return; } try { new OptimisticLockExceptionHandler(exceptionHandler).handle(); FacesContext faces = FacesContext.getCurrentInstance(); String nextUrl = ConversationManager.getInstance().getCurrentConversation().nextUrl(); ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); String url = externalContext.getRequestContextPath() + nextUrl; faces.getExternalContext().redirect(url); faces.responseComplete(); } catch (IOException e) { log.error("Failed to redirect to context page in render response phase", e); } }