Search in sources :

Example 1 with StateManagementStrategy

use of jakarta.faces.view.StateManagementStrategy in project myfaces by apache.

the class FaceletViewDeclarationLanguage method renderView.

/**
 * {@inheritDoc}
 */
@Override
public void renderView(FacesContext context, UIViewRoot view) throws IOException {
    if (!view.isRendered()) {
        return;
    }
    // log request
    if (log.isLoggable(Level.FINE)) {
        log.fine("Rendering View: " + view.getViewId());
    }
    try {
        // build view - but not if we're in "buildBeforeRestore"
        // land and we've already got a populated view. Note
        // that this optimizations breaks if there's a "c:if" in
        // the page that toggles as a result of request processing -
        // should that be handled? Or
        // is this optimization simply so minor that it should just
        // be trimmed altogether?
        // See JSF 2.0 spec section 2.2.6, buildView is called before
        // Render Response
        // if (!isFilledView(context, view))
        // {
        // buildView(context, view);
        // }
        // setup writer and assign it to the context
        ResponseWriter origWriter = createResponseWriter(context);
        ExternalContext extContext = context.getExternalContext();
        Writer outputWriter = extContext.getResponseOutputWriter();
        StateWriter stateWriter = new StateWriter(outputWriter, 1024, context);
        try {
            ResponseWriter writer = origWriter.cloneWithWriter(stateWriter);
            try {
                context.setResponseWriter(writer);
                StateManager stateMgr = context.getApplication().getStateManager();
                StateManagementStrategy sms = getStateManagementStrategy(context, view.getId());
                // force creation of session if saving state there
                // -= Leonardo Uribe =- Do this does not have any sense!. The only reference
                // about these lines are on http://java.net/projects/facelets/sources/svn/revision/376
                // and it says: "fixed lazy session instantiation with eager response commit"
                // This code is obviously to prevent this exception:
                // java.lang.IllegalStateException: Cannot create a session after the response has been committed
                // But in theory if that so, StateManager.saveState must happen before writer.close() is called,
                // which can be done very easily.
                // if (!stateMgr.isSavingStateInClient(context))
                // {
                // extContext.getSession(true);
                // }
                // render the view to the response
                writer.startDocument();
                view.encodeAll(context);
                writer.endDocument();
                // flush to origWriter
                if (stateWriter.isStateWritten()) {
                    // Call this method to force close the tag if necessary.
                    // The spec javadoc says this:
                    // "... Flush any ouput buffered by the output method to the underlying
                    // Writer or OutputStream. This method will not flush the underlying
                    // Writer or OutputStream; it simply clears any values buffered by this
                    // ResponseWriter. ..."
                    writer.flush();
                    // =-= markoc: STATE_KEY is in output ONLY if
                    // stateManager.isSavingStateInClient(context)is true - see
                    // org.apache.myfaces.application.ViewHandlerImpl.writeState(FacesContext)
                    // TODO this class and ViewHandlerImpl contain same constant <!--@@JSF_FORM_STATE_MARKER@@-->
                    Object stateObj = sms.saveView(context);
                    String content = stateWriter.getAndResetBuffer();
                    int end = content.indexOf(STATE_KEY);
                    // If so, we need to perform token replacement
                    if (end >= 0) {
                        // save state
                        int start = 0;
                        while (end != -1) {
                            origWriter.write(content, start, end - start);
                            String stateStr;
                            if (view.isTransient()) {
                                // Force state saving
                                stateMgr.writeState(context, stateObj);
                                stateStr = stateWriter.getAndResetBuffer();
                            } else if (stateObj == null) {
                                stateStr = null;
                            } else {
                                stateMgr.writeState(context, stateObj);
                                stateStr = stateWriter.getAndResetBuffer();
                            }
                            if (stateStr != null) {
                                origWriter.write(stateStr);
                            }
                            start = end + STATE_KEY_LEN;
                            end = content.indexOf(STATE_KEY, start);
                        }
                        origWriter.write(content, start, content.length() - start);
                    // No trace of any saved state, so we just need to flush the buffer
                    } else {
                        origWriter.write(content);
                    }
                } else if (stateWriter.isStateWrittenWithoutWrapper()) {
                    // The state token has been written but the state has not been saved yet.
                    sms.saveView(context);
                } else {
                    // Try to store it into cache.
                    if (viewPoolProcessor != null && viewPoolProcessor.isViewPoolEnabledForThisView(context, view)) {
                        ViewDeclarationLanguage vdl = context.getApplication().getViewHandler().getViewDeclarationLanguage(context, view.getViewId());
                        if (ViewDeclarationLanguage.FACELETS_VIEW_DECLARATION_LANGUAGE_ID.equals(vdl.getId())) {
                            if (sms != null) {
                                context.getAttributes().put(ViewPoolProcessor.FORCE_HARD_RESET, Boolean.TRUE);
                                // Force indirectly to store the map in the cache
                                try {
                                    Object state = sms.saveView(context);
                                } finally {
                                    context.getAttributes().remove(ViewPoolProcessor.FORCE_HARD_RESET);
                                }
                                // Clear the calculated value from the application map
                                context.getAttributes().remove(SERIALIZED_VIEW_REQUEST_ATTR);
                            }
                        }
                    }
                }
            } finally {
                // The Facelets implementation must close the writer used to write the response
                writer.close();
            }
        } finally {
            stateWriter.release(context);
        }
    } catch (FileNotFoundException e) {
        handleFaceletNotFound(context, view.getViewId());
    } catch (Exception e) {
        handleRenderException(context, e);
    }
}
Also used : StateManagementStrategy(jakarta.faces.view.StateManagementStrategy) PartialStateManagementStrategy(org.apache.myfaces.view.facelets.PartialStateManagementStrategy) StateManager(jakarta.faces.application.StateManager) ResponseStateManager(jakarta.faces.render.ResponseStateManager) ResponseWriter(jakarta.faces.context.ResponseWriter) ExternalContext(jakarta.faces.context.ExternalContext) FileNotFoundException(java.io.FileNotFoundException) ViewDeclarationLanguage(jakarta.faces.view.ViewDeclarationLanguage) ResponseWriter(jakarta.faces.context.ResponseWriter) Writer(java.io.Writer) IOException(java.io.IOException) ELException(jakarta.el.ELException) FacesException(jakarta.faces.FacesException) FileNotFoundException(java.io.FileNotFoundException)

Example 2 with StateManagementStrategy

use of jakarta.faces.view.StateManagementStrategy in project myfaces by apache.

the class ViewPoolProcessor method disposeView.

public void disposeView(FacesContext facesContext, UIViewRoot root) {
    if (root == null) {
        return;
    }
    String viewId = root.getViewId();
    if (viewId == null) {
        return;
    }
    Application app = facesContext.getApplication();
    if (app == null) {
        return;
    }
    ViewHandler viewHandler = app.getViewHandler();
    if (viewHandler == null) {
        return;
    }
    if (Boolean.TRUE.equals(facesContext.getAttributes().get(ViewPoolProcessor.DISPOSE_VIEW_NAVIGATION))) {
        ViewDeclarationLanguage vdl = facesContext.getApplication().getViewHandler().getViewDeclarationLanguage(facesContext, root.getViewId());
        if (vdl != null && ViewDeclarationLanguage.FACELETS_VIEW_DECLARATION_LANGUAGE_ID.equals(vdl.getId())) {
            StateManagementStrategy sms = vdl.getStateManagementStrategy(facesContext, root.getId());
            if (sms != null) {
                // Force indirectly to store the map in the pool
                facesContext.getAttributes().put(ViewPoolProcessor.FORCE_HARD_RESET, Boolean.TRUE);
                try {
                    Object state = sms.saveView(facesContext);
                } finally {
                    facesContext.getAttributes().remove(ViewPoolProcessor.FORCE_HARD_RESET);
                }
                // Clear the calculated value from the application map
                facesContext.getAttributes().remove(StateManagerImpl.SERIALIZED_VIEW_REQUEST_ATTR);
            }
        }
    }
}
Also used : StateManagementStrategy(jakarta.faces.view.StateManagementStrategy) ViewHandler(jakarta.faces.application.ViewHandler) ViewDeclarationLanguage(jakarta.faces.view.ViewDeclarationLanguage) Application(jakarta.faces.application.Application)

Example 3 with StateManagementStrategy

use of jakarta.faces.view.StateManagementStrategy in project myfaces by apache.

the class ViewDeclarationLanguageBase method restoreView.

@Override
public UIViewRoot restoreView(FacesContext context, String viewId) {
    Assert.notNull(context, "context");
    Application application = context.getApplication();
    ViewHandler applicationViewHandler = application.getViewHandler();
    String renderKitId = applicationViewHandler.calculateRenderKitId(context);
    if (log.isLoggable(Level.FINEST)) {
        log.finest("Entering restoreView - viewId: " + viewId + " ; renderKitId: " + renderKitId);
    }
    UIViewRoot viewRoot = null;
    StateManagementStrategy sms = getStateManagementStrategy(context, viewId);
    if (sms != null) {
        if (log.isLoggable(Level.FINEST)) {
            log.finest("Redirect to StateManagementStrategy: " + sms.getClass().getName());
        }
        viewRoot = sms.restoreView(context, viewId, renderKitId);
    } else {
        RenderKit renderKit = getRenderKitFactory().getRenderKit(context, renderKitId);
        ResponseStateManager responseStateManager = renderKit.getResponseStateManager();
        Object state = responseStateManager.getState(context, viewId);
        if (state != null) {
            Object[] stateArray = (Object[]) state;
            viewRoot = TreeStructureManager.restoreTreeStructure(((Object[]) stateArray[0])[0]);
            if (viewRoot != null) {
                context.setViewRoot(viewRoot);
                viewRoot.processRestoreState(context, stateArray[1]);
                RequestViewContext.getCurrentInstance(context).refreshRequestViewContext(context, viewRoot);
                // If state is saved fully, there outer f:view tag handler will not be executed,
                // so "contracts" attribute will not be set properly. We need to save it and
                // restore it from here. With PSS, the view will always be built so it is not
                // necessary to save it on the state.
                Object rlc = ((Object[]) stateArray[0])[1];
                if (rlc != null) {
                    context.setResourceLibraryContracts((List<String>) UIComponentBase.restoreAttachedState(context, rlc));
                }
            }
        }
    }
    if (log.isLoggable(Level.FINEST)) {
        log.finest("Exiting restoreView - " + viewId);
    }
    return viewRoot;
}
Also used : StateManagementStrategy(jakarta.faces.view.StateManagementStrategy) ViewHandler(jakarta.faces.application.ViewHandler) ResponseStateManager(jakarta.faces.render.ResponseStateManager) RenderKit(jakarta.faces.render.RenderKit) Application(jakarta.faces.application.Application) UIViewRoot(jakarta.faces.component.UIViewRoot)

Example 4 with StateManagementStrategy

use of jakarta.faces.view.StateManagementStrategy in project myfaces by apache.

the class StateManagerWithFaceletsTest method testWriteAndRestoreState.

@Test
public void testWriteAndRestoreState() throws Exception {
    String viewId = "/simpleTree.xhtml";
    String viewStateParam = null;
    try {
        setupRequest();
        UIViewRoot root = facesContext.getViewRoot();
        root.setViewId(viewId);
        vdl.buildView(facesContext, root, viewId);
        ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
        ViewDeclarationLanguage vdl = viewHandler.getViewDeclarationLanguage(facesContext, viewId);
        StateManagementStrategy sms = vdl.getStateManagementStrategy(facesContext, viewId);
        application.getStateManager().writeState(facesContext, sms.saveView(facesContext));
        viewStateParam = application.getStateManager().getViewState(facesContext);
    } finally {
        tearDownRequest();
    }
    try {
        setupRequest();
        request.addParameter(ResponseStateManager.VIEW_STATE_PARAM, viewStateParam);
        ((MockFacesContext20) facesContext).setPostback(true);
        ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
        ViewDeclarationLanguage vdl = viewHandler.getViewDeclarationLanguage(facesContext, viewId);
        StateManagementStrategy sms = vdl.getStateManagementStrategy(facesContext, viewId);
        UIViewRoot restoredViewRoot = sms.restoreView(facesContext, viewId, RenderKitFactory.HTML_BASIC_RENDER_KIT);
        Assert.assertNotNull(restoredViewRoot);
    } finally {
        tearDownRequest();
    }
}
Also used : StateManagementStrategy(jakarta.faces.view.StateManagementStrategy) ViewHandler(jakarta.faces.application.ViewHandler) ViewDeclarationLanguage(jakarta.faces.view.ViewDeclarationLanguage) UIViewRoot(jakarta.faces.component.UIViewRoot) MockFacesContext20(org.apache.myfaces.test.mock.MockFacesContext20) Test(org.junit.Test)

Example 5 with StateManagementStrategy

use of jakarta.faces.view.StateManagementStrategy in project faces by jakartaee.

the class TestServlet method stateMgmtStrategyNonNullTest.

// ------------------------------------------- Test Methods
public void stateMgmtStrategyNonNullTest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    PrintWriter out = response.getWriter();
    FacesContext context = getFacesContext();
    StateManagementStrategy statestrategy = this.getStateMgtmStrat(context, FACELETS_VIEWID);
    if (statestrategy == null) {
        out.println(JSFTestUtil.FAIL + JSFTestUtil.NL + "StateManagementStrategy Must be non-null for Facelet Views!");
    } else {
        out.println(JSFTestUtil.PASS);
    }
}
Also used : FacesContext(jakarta.faces.context.FacesContext) StateManagementStrategy(jakarta.faces.view.StateManagementStrategy) PrintWriter(java.io.PrintWriter)

Aggregations

StateManagementStrategy (jakarta.faces.view.StateManagementStrategy)6 ViewHandler (jakarta.faces.application.ViewHandler)4 ViewDeclarationLanguage (jakarta.faces.view.ViewDeclarationLanguage)4 UIViewRoot (jakarta.faces.component.UIViewRoot)3 Application (jakarta.faces.application.Application)2 ResponseStateManager (jakarta.faces.render.ResponseStateManager)2 MockFacesContext20 (org.apache.myfaces.test.mock.MockFacesContext20)2 Test (org.junit.Test)2 ELException (jakarta.el.ELException)1 FacesException (jakarta.faces.FacesException)1 StateManager (jakarta.faces.application.StateManager)1 ExternalContext (jakarta.faces.context.ExternalContext)1 FacesContext (jakarta.faces.context.FacesContext)1 ResponseWriter (jakarta.faces.context.ResponseWriter)1 RenderKit (jakarta.faces.render.RenderKit)1 FileNotFoundException (java.io.FileNotFoundException)1 IOException (java.io.IOException)1 PrintWriter (java.io.PrintWriter)1 Writer (java.io.Writer)1 HtmlResponseStateManager (org.apache.myfaces.renderkit.html.HtmlResponseStateManager)1