<application> <view-handler>com.icesoft.faces.application.D2DViewHandler</view-handler> </application> <factory> <faces-context-factory> com.icesoft.faces.context.FacesContextFactoryImpl </faces-context-factory> </factory> ....
In the D2DViewHandler, Icefaces uses its own JsfJspDigester to parse the JSF/JSP files. But the core of the whole program is still the LifecycleImpl class ( This class implements javax.faces.lifecycle.Lifecycle ) from SUN to carry out the JSF lifecycle.
Note that the ICEfaces facelet viewHandler is a subclass of the D2DViewHandler:
public class D2DFaceletViewHandler extends D2DViewHandlerD2DFaceletViewHandler inherits from D2DViewHandler all the public methods including the following
public void renderView(FacesContext context, UIViewRoot viewToRender) throws IOException, FacesExceptionThis method calls the renderResponse method:
protected void renderResponse(FacesContext facesContext) throws IOExceptionD2DFaceletViewHandler overrides this method.
We'll check the details of how it works. In this analysis, Icefaces 1.6.2 is used.
The major class of Icefaces is com.icesoft.faces.webapp.xmlhttp.PersistentFacesServlet.
The PersistentFacesServlet is actually a MainServlet. It has a PathDispather:
private PathDispatcher dispatcher = new PathDispatcher();In the init() method, it has the following:
PseudoServlet resourceServer = new BasicAdaptingServlet(new ResourceServer(configuration, mimeTypeMatcher, localFileLocator)); PseudoServlet sessionServer = new SessionDispatcher() { protected PseudoServlet newServlet(HttpSession session, Listener.Monitor sessionMonitor) { return new MainSessionBoundServlet(session, sessionMonitor, idGenerator, configuration); } }; dispatcher.dispatchOn(".*(\\.iface$|\\.jsf|\\.faces$|\\.jsp$|\\.jspx$|\\.html$|\\.xhtml$|\\.seam$|uploadHtml$|block\\/)", sessionServer); dispatcher.dispatchOn(".*", resourceServer);
The method dispathOn is the following:
public void dispatchOn(String pathExpression, PseudoServlet toServer) { matchers.add(new Matcher(pathExpression, toServer)); }
In short, when an Icefaces URL is sent to the server, this servlet PersistentFacesServlet is invoked. It creates many objects and then services the request. Eventually a PageServer object services the request. The class is the following:
public class PageServer implements Server { private final static LifecycleFactory LIFECYCLE_FACTORY = (LifecycleFactory) FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY); private Lifecycle lifecycle = LIFECYCLE_FACTORY.getLifecycle(LIFECYCLE_FACTORY.DEFAULT_LIFECYCLE); private ResponseHandler responseHandler = new ResponseHandler() { public void respond(Response response) throws Exception { FacesContext facesContext = FacesContext.getCurrentInstance(); response.setHeader("Cache-Control", new String[]{"no-cache", "no-store", "must-revalidate"});//HTTP 1.1 response.setHeader("Pragma", "no-cache");//HTTP 1.0 response.setHeader("Expires", 0);//prevents proxy caching response.setHeader("Content-Type", "text/html"); com.icesoft.util.SeamUtilities.removeSeamDebugPhaseListener(lifecycle); lifecycle.execute(facesContext); lifecycle.render(facesContext); } };Here the lifecycle object and its factory are of the following two classes:
com.sun.faces.lifecycle.LifecycleFactoryImpl com.sun.faces.lifecycle.LifecycleImplThe PersistentFacesServlet has created these objects already before using the PageServer.
The code of LifecycleImpl for the two methods is basically the following:
public void execute(FacesContext context) throws FacesException { if(context == null) throw new NullPointerException(Util.getExceptionMessageString("com.sun.faces.NULL_PARAMETERS_ERROR")); if(log.isDebugEnabled()) log.debug("execute(" + context + ")"); for(int i = 1; i < phases.length; i++) { if(context.getRenderResponse() || context.getResponseComplete()) break; phase((PhaseId)PhaseId.VALUES.get(i), phases[i], context); if(reload((PhaseId)PhaseId.VALUES.get(i), context)) { if(log.isDebugEnabled()) log.debug("Skipping rest of execute() because of a reload"); context.renderResponse(); } } } public void render(FacesContext context) throws FacesException { if(context == null) throw new NullPointerException(Util.getExceptionMessageString("com.sun.faces.NULL_PARAMETERS_ERROR")); if(log.isDebugEnabled()) log.debug("render(" + context + ")"); if(!context.getResponseComplete()) phase(PhaseId.RENDER_RESPONSE, response, context); } private void phase(PhaseId phaseId, Phase phase, FacesContext context) throws FacesException { List firedListeners; PhaseEvent event; if(log.isTraceEnabled()) log.trace("phase(" + phaseId.toString() + "," + context + ")"); List ourListeners = listeners; int numListeners = ourListeners.size(); firedListeners = new ArrayList(numListeners); if(numListeners <= 0) break MISSING_BLOCK_LABEL_573; event = new PhaseEvent(context, phaseId, this); int i = 0; try { while(i < numListeners) { PhaseListener listener = (PhaseListener)ourListeners.get(i); PhaseId listenerPhaseId = listener.getPhaseId(); if(phaseId.equals(listenerPhaseId) || PhaseId.ANY_PHASE.equals(listenerPhaseId)) { listener.beforePhase(event); firedListeners.add(listener); } i++; } } catch(Throwable e) { if(log.isTraceEnabled()) log.trace("beforePhase(" + phaseId.toString() + "," + context + ") threw exception: " + e + " " + e.getMessage() + "\n" + Util.getStackTraceString(e)); } if(!skipping(phaseId, context)) phase.execute(context); int i = firedListeners.size() - 1; try { while(i >= 0) { PhaseListener listener = (PhaseListener)firedListeners.get(i); listener.afterPhase(event); i--; } } catch(Throwable e) { if(log.isTraceEnabled()) log.trace("afterPhase(" + phaseId.toString() + "," + context + ") threw exception: " + e + " " + e.getMessage() + "\n" + Util.getStackTraceString(e)); } break MISSING_BLOCK_LABEL_587; Exception exception; exception; int i = firedListeners.size() - 1; try { while(i >= 0) { PhaseListener listener = (PhaseListener)firedListeners.get(i); listener.afterPhase(event); i--; } } catch(Throwable e) { if(log.isTraceEnabled()) log.trace("afterPhase(" + phaseId.toString() + "," + context + ") threw exception: " + e + " " + e.getMessage() + "\n" + Util.getStackTraceString(e)); } throw exception; if(!skipping(phaseId, context)) phase.execute(context); } private Phase phases[] = { null, new RestoreViewPhase(), new ApplyRequestValuesPhase(), new ProcessValidationsPhase(), new UpdateModelValuesPhase(), new InvokeApplicationPhase() };
Looking at the method execute() and phase(), we can see the following:
- The execute() method basically calls each phase except for the last phase "Render Response"
- In each phase, the phase listerners for that phase will be invoked for their beforePhase() methods. Then the phase will execute. And then the afterPhase() method will be called. Note that these phase listeners are kept in the LifecycleImpl instance. Each phase just loops through these listeners and invokes only those with the same phase id or the ANY phase id.
- During the executions, the methods call the methods renderResponse() and responseComplete() of the class FacesContext frequently to check if the lifecycle needs to be short curcuited.
- Each phase implements its own execute() method.
Now the next activity is the call lifecycle.render(facesContext). Recall that the lifecycle.execute() method does not invoke the Render phase.
Note: The methods renderResponse() and responseComplete() of the class FacesContext just signal the JavaServer faces what has been done. They do not actually do the rendering. See Javadoc of FacesContext.
RestoreView Phase
The execute() method has the following piece of code:public void execute(FacesContext facesContext) throws FacesException { if(log.isDebugEnabled()) log.debug("Entering RestoreViewPhase"); if(null == facesContext) throw new FacesException(Util.getExceptionMessageString("com.sun.faces.NULL_CONTEXT_ERROR")); UIViewRoot viewRoot = facesContext.getViewRoot(); java.util.Locale locale = null; if(viewRoot != null) { if(log.isDebugEnabled()) log.debug("Found a pre created view in FacesContext"); locale = facesContext.getExternalContext().getRequestLocale(); facesContext.getViewRoot().setLocale(locale); doPerComponentActions(facesContext, viewRoot); return; } Map requestMap = facesContext.getExternalContext().getRequestMap(); String viewId = (String)requestMap.get("javax.servlet.include.path_info"); if(viewId == null) viewId = facesContext.getExternalContext().getRequestPathInfo(); if(viewId == null) viewId = (String)requestMap.get("javax.servlet.include.servlet_path"); if(viewId == null) { Object request = facesContext.getExternalContext().getRequest(); if(request instanceof HttpServletRequest) viewId = ((HttpServletRequest)request).getServletPath(); } if(viewId == null) { if(log.isDebugEnabled()) log.debug("viewId is null"); throw new FacesException(Util.getExceptionMessageString("com.sun.faces.NULL_REQUEST_VIEW_ERROR")); } if(null == (viewRoot = Util.getViewHandler(facesContext).restoreView(facesContext, viewId))) { if(log.isDebugEnabled()) log.debug("New request: creating a view for " + viewId); viewRoot = Util.getViewHandler(facesContext).createView(facesContext, viewId); facesContext.renderResponse(); } else if(log.isDebugEnabled()) log.debug("Postback: Restored view for " + viewId); Util.doAssert(null != viewRoot); facesContext.setViewRoot(viewRoot); doPerComponentActions(facesContext, viewRoot); if(log.isDebugEnabled()) log.debug("Exiting RestoreViewPhase"); }
When Spring webflow is used, the FlowPhaseListener's beforePhase() is called in this phase. If it is the start of the flow, the beforePhase() method will call
restoreFlowExecution(event.getFacesContext());If the flowId is used in the URL, this method will call the following code:
String flowId = argumentHandler.extractFlowId(context); FlowDefinition flowDefinition = getLocator(context).getFlowDefinition(flowId); FlowExecution flowExecution = getFactory(context).createFlowExecution(flowDefinition); FlowExecutionHolder holder = new FlowExecutionHolder(flowExecution); FlowExecutionHolderUtils.setFlowExecutionHolder(holder, facesContext); ViewSelection selectedView = flowExecution.start(createInput(context), context); holder.setViewSelection(selectedView);We can see that the key objects are FlowDefinition and FlowExecution. At the end, it gets the ViewSelection and saves this in the holder. This ViewSelection will be used in the RenderResponsePhase to render the view.
After the beforePhase() method is called, the execute() method of the RestoreViewPhase will be called. For the first time flow entry, the execute() method will call the following:
if(null == (viewRoot = Util.getViewHandler(facesContext).restoreView(facesContext, viewId))) { if(log.isDebugEnabled()) log.debug("New request: creating a view for " + viewId); viewRoot = Util.getViewHandler(facesContext).createView(facesContext, viewId); facesContext.renderResponse(); }where the "if" condition is true. This is a place where the ViewHandler comes into play. When Icefaces is used, the ViewHandler is D2dViewHandler or D2DFaceletViewHandler. The createView() method is the following:
public UIViewRoot createView(FacesContext context, String viewId) { initializeParameters(context); if (delegateView(viewId)) { return delegate.createView(context, viewId); } // #2139 Remove this token here as well ExternalContext externalContext = context.getExternalContext(); externalContext.getRequestParameterMap().remove( PersistentFacesCommonlet.SEAM_LIFECYCLE_SHORTCUT); UIViewRoot root = new NamespacingViewRoot(context); // UIViewRoot root = new UIViewRoot(); root.setRenderKitId(RenderKitFactory.HTML_BASIC_RENDER_KIT); Map contextServletTable = getContextServletTable(context); if (null == viewId) { root.setViewId("default"); context.setViewRoot(root); contextServletTable .put(DOMResponseWriter.RESPONSE_VIEWROOT, root); Locale locale = calculateLocale(context); root.setLocale(locale); return root; } root.setViewId(viewId); context.setViewRoot(root); contextServletTable.put(DOMResponseWriter.RESPONSE_VIEWROOT, root); return root; }When Spring web flow is also used and the URL from web client is like
http://localhost:7001/foo/xyz.iface?_flowId=xyz-flow, the viewId is xyz.iface. The line
UIViewRoot root = new NamespacingViewRoot(context);is called and is set to the context.
However, in the RenderResponsePhase, the FlowPhaseListener will update the ViewRoot in its beforePhase() method and set it to the start view of the web flow. Recall from before that the FlowPhaseListener's beforePhase() has picked up the ViewSelection and stored it in the FlowExecutionHolder. So it seems that the execute() method of the RestoreViewPhase does something but is then ignored. For details of how the ViewRoot is updated in the RenderResponsePhase, see the prepareApplicationView() method and the updateViewRoot() method of the class FlowPhaseListener.
ApplyRequestValuesPhase
public void execute(FacesContext facesContext) throws FacesException { if(log.isDebugEnabled()) log.debug("Entering ApplyRequestValuesPhase"); UIComponent component = facesContext.getViewRoot(); Util.doAssert(null != component); try { component.processDecodes(facesContext); } catch(RuntimeException re) { String exceptionMessage = re.getMessage(); if(null != exceptionMessage && log.isErrorEnabled()) log.error(exceptionMessage, re); throw new FacesException(exceptionMessage, re); } if(log.isDebugEnabled()) log.debug("Exiting ApplyRequestValuesPhase"); }
ProcessValidationsPhase
public void execute(FacesContext facesContext) throws FacesException { if(log.isDebugEnabled()) log.debug("Entering ProcessValidationsPhase"); UIComponent component = facesContext.getViewRoot(); Util.doAssert(null != component); try { component.processValidators(facesContext); } catch(RuntimeException re) { String exceptionMessage = re.getMessage(); if(null != exceptionMessage && log.isErrorEnabled()) log.error(exceptionMessage, re); throw new FacesException(exceptionMessage, re); } if(log.isDebugEnabled()) log.debug("Exiting ProcessValidationsPhase"); }
UpdateModelValuesPhase
public void execute(FacesContext facesContext) { if(log.isDebugEnabled()) log.debug("Entering UpdateModelValuesPhase"); UIComponent component = facesContext.getViewRoot(); Util.doAssert(null != component); String exceptionMessage = null; try { component.processUpdates(facesContext); } catch(IllegalStateException e) { exceptionMessage = e.getMessage(); } catch(FacesException fe) { exceptionMessage = fe.getMessage(); } if(null != exceptionMessage) { Object params[] = new Object[3]; params[2] = exceptionMessage; facesContext.addMessage(component.getClientId(facesContext), MessageFactory.getMessage(facesContext, "com.sun.faces.MODELUPDATE_ERROR", params)); if(log.isErrorEnabled()) log.error(exceptionMessage); if(log.isDebugEnabled()) log.debug("Exiting UpdateModelValuesPhase"); } }
InvokeApplicationPhase
public void execute(FacesContext facesContext) throws FacesException { if(log.isDebugEnabled()) log.debug("Entering InvokeApplicationsPhase"); UIViewRoot root = facesContext.getViewRoot(); Util.doAssert(null != root); try { root.processApplication(facesContext); } catch(RuntimeException re) { String exceptionMessage = re.getMessage(); if(null != exceptionMessage && log.isErrorEnabled()) log.error(exceptionMessage, re); throw new FacesException(exceptionMessage, re); } if(log.isDebugEnabled()) log.debug("Exiting InvokeApplicationsPhase"); }
Notes on UIViewRoot:
- All the events are stored in this object. The instance variable events is a list of list. Each event has a PhaseId. The event is queued in the list for that phase.
- Each event is associated with the component which is the source of the event.
- The broadcastEvents() method delegate the handling to the same method of the event source component. It was done first for the ANY
PhaseId, and then the PhaseId of this phase.
package javax.faces.component; .... public class UIViewRoot extends UIComponentBase private int lastId; private String renderKitId; private String viewId; private transient List events[]; private Locale locale; public void queueEvent(FacesEvent event) { if(event == null) throw new NullPointerException(); int i = 0; int len = 0; if(events == null) { events = new List[len = PhaseId.VALUES.size()]; for(i = 0; i < len; i++) events[i] = new ArrayList(5); } events[event.getPhaseId().getOrdinal()].add(event); } public void processApplication(FacesContext context) { broadcastEvents(context, PhaseId.INVOKE_APPLICATION); } private void broadcastEvents(FacesContext context, PhaseId phaseId) { List eventsForPhaseId = null; if(null == events) return; boolean hasMoreAnyPhaseEvents = true; boolean hasMoreCurrentPhaseEvents = true; eventsForPhaseId = events[PhaseId.ANY_PHASE.getOrdinal()]; do { if(null != eventsForPhaseId) { for(int cursor = 0; cursor < eventsForPhaseId.size(); eventsForPhaseId.remove(cursor)) { FacesEvent event = (FacesEvent)eventsForPhaseId.get(cursor); UIComponent source = event.getComponent(); try { source.broadcast(event); } catch(AbortProcessingException e) { } } } if(null != (eventsForPhaseId = events[phaseId.getOrdinal()])) { for(int cursor = 0; cursor < eventsForPhaseId.size(); eventsForPhaseId.remove(cursor)) { FacesEvent event = (FacesEvent)eventsForPhaseId.get(cursor); UIComponent source = event.getComponent(); try { source.broadcast(event); } catch(AbortProcessingException e) { } } } hasMoreAnyPhaseEvents = null != (eventsForPhaseId = events[PhaseId.ANY_PHASE.getOrdinal()]) && eventsForPhaseId.size() > 0; hasMoreCurrentPhaseEvents = null != events[phaseId.getOrdinal()] && events[phaseId.getOrdinal()].size() > 0; } while(hasMoreAnyPhaseEvents || hasMoreCurrentPhaseEvents); }
UICommand is in the package javax.faces.component
public class UICommand extends UIComponentBase implements ActionSource { ....... public void broadcast(FacesEvent event) throws AbortProcessingException { super.broadcast(event); if(event instanceof ActionEvent) { FacesContext context = getFacesContext(); MethodBinding mb = getActionListener(); if(mb != null) mb.invoke(context, new Object[] { event }); ActionListener listener = context.getApplication().getActionListener(); if(listener != null) listener.processAction((ActionEvent)event); } } }The HtmlCommandLink and HtmlCommandButton are subclasses of UICommand. Icefaces has the class com.icesoft.faces.component.ext.HtmlCommandLink, which extends javax.faces.component.HtmlCommandLink.
package com.sun.faces.application public class ActionListenerImpl implements ActionListener { ..... public void processAction(ActionEvent event) { if(log.isDebugEnabled()) log.debug("processAction(" + event.getComponent().getId() + ")"); UIComponent source = event.getComponent(); ActionSource actionSource = (ActionSource)source; FacesContext context = FacesContext.getCurrentInstance(); Application application = context.getApplication(); String outcome = null; MethodBinding binding = null; binding = actionSource.getAction(); if(binding != null) try { outcome = (String)binding.invoke(context, null); } catch(MethodNotFoundException e) { throw new FacesException(binding.getExpressionString() + ": " + e, e); } catch(EvaluationException e) { throw new FacesException(binding.getExpressionString() + ": " + e, e); } NavigationHandler navHandler = application.getNavigationHandler(); navHandler.handleNavigation(context, null == binding ? null : binding.getExpressionString(), outcome); context.renderResponse(); } }Note that this is where the NavigationHandler comes into play . When Spring webflow is used, the NavigationHandler is FlowNavigationHandler. Its handleNavigation() method will calculate the
ViewSelection from the FlowExecution and save it in the FlowExecutionHolder:
holder.setViewSelection(selectedView);
RenderResponsePhase
The execute() method has the following main code:public void execute(FacesContext facesContext) throws FacesException { if(log.isDebugEnabled()) log.debug("Entering RenderResponsePhase"); if(log.isDebugEnabled()) log.debug("About to render view " + facesContext.getViewRoot().getViewId()); try { facesContext.getApplication().getViewHandler().renderView(facesContext, facesContext.getViewRoot()); } catch(IOException e) { throw new FacesException(e.getMessage(), e); } if(log.isDebugEnabled()) log.debug("Exiting RenderResponsePhase"); }Notice that this is another place where the ViewHandler comes into play. It renders the view which is the ViewRoot from the FacesContext. When Spring webflow is used, the FlowPhaseListener sets the ViewRoot in its beforePhase() method. In this method, it calls the prepareResponse() method. This method gets the ViewSelection in the FlowExecutionHolder:
ViewSelection selectedView = holder.getViewSelection();Recall that in the InvokeApplicationPhase, the Spring NavigationHandler has set the ViewSelection in the holder. Then the prepareResponse() method creates a ResponseInstructionHandler object and calls its handleQuietly() method.
The handleQuietly() method deals with several cases. For one of the cases, it calls
handleApplicationView((ApplicationView)responseInstruction.getViewSelection());The ResponseInstructionHandler object implements this method as follows:
protected void handleApplicationView(ApplicationView view) throws Exception { prepareApplicationView(context.getFacesContext(), holder); }The method prepareApplicationView() is a method in the FlowPhaseListener class as the ResponseInstructionHandler object is a created inside this class:
protected void prepareApplicationView(FacesContext facesContext, FlowExecutionHolder holder) { ApplicationView view = (ApplicationView) holder.getViewSelection(); if (view != null) { // expose the view's "model map" in the request map putInto(facesContext.getExternalContext().getRequestMap(), view.getModel()); // update the root component if necessary updateViewRoot(facesContext, viewIdMapper.mapViewId(view.getViewName())); } String flowExecutionKey = holder.getFlowExecution().isActive() ? holder.getFlowExecutionKey().toString() : null; if (flowExecutionKey != null) { saveInViewRoot(facesContext, flowExecutionKey); } Map requestMap = facesContext.getExternalContext().getRequestMap(); argumentHandler.exposeFlowExecutionContext(flowExecutionKey, holder.getFlowExecution(), requestMap); }We can see that this method updates the ViewRoot in the FacesContext. And this completes the preparation because a ViewHandler will get the ViewRoot from FacesContext and render it.
Some key Classes
PhaseIdpackage javax.faces.event; import java.util.*; public class PhaseId implements Comparable { ...... public static final List VALUES; static { ANY_PHASE = new PhaseId("ANY"); RESTORE_VIEW = new PhaseId("RESTORE_VIEW"); APPLY_REQUEST_VALUES = new PhaseId("APPLY_REQUEST_VALUES"); PROCESS_VALIDATIONS = new PhaseId("PROCESS_VALIDATIONS"); UPDATE_MODEL_VALUES = new PhaseId("UPDATE_MODEL_VALUES"); INVOKE_APPLICATION = new PhaseId("INVOKE_APPLICATION"); RENDER_RESPONSE = new PhaseId("RENDER_RESPONSE"); values = (new PhaseId[] { ANY_PHASE, RESTORE_VIEW, APPLY_REQUEST_VALUES, PROCESS_VALIDATIONS, UPDATE_MODEL_VALUES, INVOKE_APPLICATION, RENDER_RESPONSE }); VALUES = Collections.unmodifiableList(Arrays.asList(values)); } }
FlowPhaseListener
The Spring class FlowPhaseListener is a key in integrating Spring web flow into JSF. The following are some important methods of the class.
public PhaseId getPhaseId() { return PhaseId.ANY_PHASE; } public void beforePhase(PhaseEvent event) { FacesContext context = event.getFacesContext(); if (event.getPhaseId() == PhaseId.RESTORE_VIEW) { ExternalContextHolder.setExternalContext(new JsfExternalContext(context)); restoreFlowExecution(event.getFacesContext()); // we do not need to worry about clean up here since other phases will continue to run even if an exception // occurs in restoreFlowExecution(FacesContext) } else if (event.getPhaseId() == PhaseId.RENDER_RESPONSE) { if (FlowExecutionHolderUtils.isFlowExecutionRestored(event.getFacesContext())) { try { prepareResponse(getCurrentContext(), FlowExecutionHolderUtils.getFlowExecutionHolder(context)); } catch (RuntimeException e) { // we must cleanup here since this is the render response phase and the after phase callback will // NOT run when an exception occurs (which typically does the cleanup--see below) cleanupResources(context); throw e; } catch (Error e) { cleanupResources(context); throw e; } } } } public void afterPhase(PhaseEvent event) { FacesContext context = event.getFacesContext(); if (event.getPhaseId() == PhaseId.RENDER_RESPONSE) { if (FlowExecutionHolderUtils.isFlowExecutionRestored(context)) { try { saveFlowExecution(getCurrentContext(), FlowExecutionHolderUtils.getFlowExecutionHolder(context)); } finally { // always cleanup after save - we are done with flow execution request processing cleanupResources(context); } } } else { // cleanup if some other JSF artifact marked 'response complete' to short-circuit the lifecycle early if (context.getResponseComplete()) { cleanupResources(context); } } } protected void restoreFlowExecution(FacesContext facesContext) { JsfExternalContext context = new JsfExternalContext(facesContext); if (argumentHandler.isFlowExecutionKeyPresent(context)) { // restore flow execution from repository so it will be available to JSF artifacts // (this could happen as part of a flow execution redirect or browser refresh) FlowExecutionRepository repository = getRepository(context); FlowExecutionKey flowExecutionKey = repository.parseFlowExecutionKey(argumentHandler .extractFlowExecutionKey(context)); try { FlowExecutionLock lock = repository.getLock(flowExecutionKey); lock.lock(); try { FlowExecution flowExecution = repository.getFlowExecution(flowExecutionKey); if (logger.isDebugEnabled()) { logger.debug("Loaded existing flow execution with key '" + flowExecutionKey + "' due to browser access " + "[either via a flow execution redirect or direct browser refresh]"); } FlowExecutionHolderUtils.setFlowExecutionHolder(new FlowExecutionHolder(flowExecutionKey, flowExecution, lock), facesContext); } catch (RuntimeException e) { lock.unlock(); throw e; } catch (Error e) { lock.unlock(); throw e; } } catch (FlowExecutionAccessException e) { // thrown if access to the execution could not be granted handleFlowExecutionAccessException(e, facesContext); } } else if (argumentHandler.isFlowIdPresent(context)) { // launch a new flow execution // (this could happen as part of direct browser access or a flow definition redirect) String flowId = argumentHandler.extractFlowId(context); FlowDefinition flowDefinition = getLocator(context).getFlowDefinition(flowId); FlowExecution flowExecution = getFactory(context).createFlowExecution(flowDefinition); FlowExecutionHolder holder = new FlowExecutionHolder(flowExecution); FlowExecutionHolderUtils.setFlowExecutionHolder(holder, facesContext); ViewSelection selectedView = flowExecution.start(createInput(context), context); holder.setViewSelection(selectedView); if (logger.isDebugEnabled()) { logger.debug("Launched a new flow execution due to browser access " + "[either via a flow redirect or direct browser URL access]"); } } } /** * Prepare the JSF view for rendering. * @param facesContext the faces context * @param holder the holder of the current flow execution */ protected void prepareApplicationView(FacesContext facesContext, FlowExecutionHolder holder) { ApplicationView view = (ApplicationView) holder.getViewSelection(); if (view != null) { // expose the view's "model map" in the request map putInto(facesContext.getExternalContext().getRequestMap(), view.getModel()); // update the root component if necessary updateViewRoot(facesContext, viewIdMapper.mapViewId(view.getViewName())); } String flowExecutionKey = holder.getFlowExecution().isActive() ? holder.getFlowExecutionKey().toString() : null; if (flowExecutionKey != null) { saveInViewRoot(facesContext, flowExecutionKey); } Map requestMap = facesContext.getExternalContext().getRequestMap(); argumentHandler.exposeFlowExecutionContext(flowExecutionKey, holder.getFlowExecution(), requestMap); } private void updateViewRoot(FacesContext facesContext, String viewId) { UIViewRoot viewRoot = facesContext.getViewRoot(); if (viewRoot == null || hasViewChanged(viewRoot, viewId)) { // create the specified view so that it can be rendered ViewHandler handler = facesContext.getApplication().getViewHandler(); UIViewRoot view = handler.createView(facesContext, viewId); facesContext.setViewRoot(view); } }
So the beforePhase only reacts to the RESTORE_VIEW and RENDER_RESPONSE phases.
FlowNavigationHandler
The class FlowNavigationHandler is another key in integration of JSF and Spring web flow:
public class FlowNavigationHandler extends DecoratingNavigationHandler { ...... public void handleNavigation(FacesContext facesContext, String fromAction, String outcome, NavigationHandler originalNavigationHandler) { try { JsfExternalContext context = getCurrentContext(); // record the navigation handler context context.handleNavigationCalled(fromAction, outcome); // first see if we need to launch a new flow execution if the flow id is present if (argumentExtractor.isFlowIdPresent(context)) { // a flow execution launch has been requested - create the new execution String flowId = argumentExtractor.extractFlowId(context); FlowDefinition flowDefinition = getLocator(context).getFlowDefinition(flowId); FlowExecution flowExecution = getFactory(context).createFlowExecution(flowDefinition); // check to see if this execution was created while another was running if (FlowExecutionHolderUtils.isFlowExecutionRestored(facesContext)) { // replace the current flow execution with the new one FlowExecutionHolderUtils.getFlowExecutionHolder(facesContext).replaceWith(flowExecution); } else { // bind the new execution as the 'current execution' FlowExecutionHolderUtils.setFlowExecutionHolder(new FlowExecutionHolder(flowExecution), facesContext); } // start the new execution ViewSelection selectedView = flowExecution.start(createInput(context), context); // set the starting view to render FlowExecutionHolderUtils.getFlowExecutionHolder(facesContext).setViewSelection(selectedView); } else { // not a launch request - see if this is a resume request to continue an existing execution if (FlowExecutionHolderUtils.isFlowExecutionRestored(facesContext)) { // a flow execution has been restored - see if we need to signal an event against it if (argumentExtractor.isEventIdPresent(context)) { // signal the event against the current flow execution String eventId = argumentExtractor.extractEventId(context); try { FlowExecutionHolder holder = FlowExecutionHolderUtils.getFlowExecutionHolder(facesContext); ViewSelection selectedView = holder.getFlowExecution().signalEvent(eventId, context); // set the next view to render holder.setViewSelection(selectedView); } catch (NoMatchingTransitionException e) { if (logger.isDebugEnabled()) { logger.debug("No flow state transition found for event '" + eventId + "'; falling back to standard navigation handler."); } // not a valid event in the current state: proceed with standard navigation originalNavigationHandler.handleNavigation(facesContext, fromAction, outcome); } } } else { // neither a flow launch or resume request: proceed with standard navigation originalNavigationHandler.handleNavigation(facesContext, fromAction, outcome); } } } catch (RuntimeException e) { cleanupResources(facesContext); throw e; } catch (Error e) { cleanupResources(facesContext); throw e; } }
D2dViewHandler
package com.icesoft.faces.application; ... public class D2DViewHandler extends ViewHandler { ...... /** * Create a new ViewRoot * * @param context FacesContext * @param viewId ViewId identifying the root * @return A new viewRoot */ public UIViewRoot createView(FacesContext context, String viewId) { initializeParameters(context); if (delegateView(viewId)) { return delegate.createView(context, viewId); } // #2139 Remove this token here as well ExternalContext externalContext = context.getExternalContext(); externalContext.getRequestParameterMap().remove( PersistentFacesCommonlet.SEAM_LIFECYCLE_SHORTCUT); UIViewRoot root = new NamespacingViewRoot(context); // UIViewRoot root = new UIViewRoot(); root.setRenderKitId(RenderKitFactory.HTML_BASIC_RENDER_KIT); Map contextServletTable = getContextServletTable(context); if (null == viewId) { root.setViewId("default"); context.setViewRoot(root); contextServletTable .put(DOMResponseWriter.RESPONSE_VIEWROOT, root); Locale locale = calculateLocale(context); root.setLocale(locale); return root; } root.setViewId(viewId); context.setViewRoot(root); contextServletTable.put(DOMResponseWriter.RESPONSE_VIEWROOT, root); return root; } }
No comments:
Post a Comment