Search in sources :

Example 1 with StateManager

use of jakarta.faces.application.StateManager in project myfaces by apache.

the class ViewHandlerImpl method writeState.

@Override
public void writeState(FacesContext context) throws IOException {
    Assert.notNull(context, "context");
    if (context.getPartialViewContext().isAjaxRequest()) {
        return;
    }
    ResponseStateManager responseStateManager = context.getRenderKit().getResponseStateManager();
    setWritingState(context, responseStateManager);
    StateManager stateManager = context.getApplication().getStateManager();
    // that so, check if the current one support the trick.
    if (StateCacheUtils.isMyFacesResponseStateManager(responseStateManager)) {
        if (StateCacheUtils.getMyFacesResponseStateManager(responseStateManager).isWriteStateAfterRenderViewRequired(context)) {
            // Only write state marker if javascript view state is disabled
            context.getResponseWriter().write(FORM_STATE_MARKER);
        } else {
            stateManager.writeState(context, new Object[2]);
        }
    } else {
        // Only write state marker if javascript view state is disabled
        context.getResponseWriter().write(FORM_STATE_MARKER);
    }
}
Also used : StateManager(jakarta.faces.application.StateManager) ResponseStateManager(jakarta.faces.render.ResponseStateManager) ResponseStateManager(jakarta.faces.render.ResponseStateManager)

Example 2 with StateManager

use of jakarta.faces.application.StateManager 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 3 with StateManager

use of jakarta.faces.application.StateManager in project mojarra by eclipse-ee4j.

the class WriteBehindStateWriter method flushToWriter.

/**
 * <p>
 * Write directly from our FastStringWriter to the provided writer.
 * </p>
 *
 * @throws IOException if an error occurs
 */
public void flushToWriter() throws IOException {
    // Save the state to a new instance of StringWriter to
    // avoid multiple serialization steps if the view contains
    // multiple forms.
    StateManager stateManager = Util.getStateManager(context);
    ResponseWriter origWriter = context.getResponseWriter();
    StringBuilder stateBuilder = getState(stateManager, origWriter);
    StringBuilder builder = fWriter.getBuffer();
    // Begin writing...
    int totalLen = builder.length();
    int stateLen = stateBuilder.length();
    int pos = 0;
    int tildeIdx = getNextDelimiterIndex(builder, pos);
    while (pos < totalLen) {
        if (tildeIdx != -1) {
            if (tildeIdx > pos && tildeIdx - pos > bufSize) {
                // There's enough content before the first ~
                // to fill the entire buffer
                builder.getChars(pos, pos + bufSize, buf, 0);
                orig.write(buf);
                pos += bufSize;
            } else {
                // Write all content up to the first '~'
                builder.getChars(pos, tildeIdx, buf, 0);
                int len = tildeIdx - pos;
                orig.write(buf, 0, len);
                // state out.
                if (builder.indexOf(RIConstants.SAVESTATE_FIELD_MARKER, pos) == tildeIdx) {
                    // buf is effectively zero'd out at this point
                    int statePos = 0;
                    while (statePos < stateLen) {
                        if (stateLen - statePos > bufSize) {
                            // enough state to fill the buffer
                            stateBuilder.getChars(statePos, statePos + bufSize, buf, 0);
                            orig.write(buf);
                            statePos += bufSize;
                        } else {
                            int slen = stateLen - statePos;
                            stateBuilder.getChars(statePos, stateLen, buf, 0);
                            orig.write(buf, 0, slen);
                            statePos += slen;
                        }
                    }
                    // Push us past the last '~' at the end of the marker
                    pos += len + STATE_MARKER_LEN;
                    tildeIdx = getNextDelimiterIndex(builder, pos);
                    stateBuilder = getState(stateManager, origWriter);
                    stateLen = stateBuilder.length();
                } else {
                    pos = tildeIdx;
                    tildeIdx = getNextDelimiterIndex(builder, tildeIdx + 1);
                }
            }
        } else {
            // finish writing content
            if (totalLen - pos > bufSize) {
                // There's enough content to fill the buffer
                builder.getChars(pos, pos + bufSize, buf, 0);
                orig.write(buf);
                pos += bufSize;
            } else {
                // We're near the end of the response
                builder.getChars(pos, totalLen, buf, 0);
                int len = totalLen - pos;
                orig.write(buf, 0, len);
                pos += len + 1;
            }
        }
    }
    // all state has been written. Have 'out' point to the
    // response so that all subsequent writes will make it to the
    // browser.
    out = orig;
}
Also used : StateManager(jakarta.faces.application.StateManager) ResponseWriter(jakarta.faces.context.ResponseWriter)

Example 4 with StateManager

use of jakarta.faces.application.StateManager in project faces by jakartaee.

the class TestServlet method stateManagerIsSavingStateInClientTest.

// ---------------------------------------------------------------- Test
// Methods
// Validation of return value will be performed on the client side.
public void stateManagerIsSavingStateInClientTest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    StateManager manager = new SimpleStateManagerWrapper(getApplication().getStateManager());
    out.println(manager.isSavingStateInClient(getFacesContext()));
}
Also used : StateManager(jakarta.faces.application.StateManager) PrintWriter(java.io.PrintWriter)

Example 5 with StateManager

use of jakarta.faces.application.StateManager in project myfaces by apache.

the class FacesConfigurator method configureApplication.

private void configureApplication() {
    Application application = ((ApplicationFactory) FactoryFinder.getFactory(FactoryFinder.APPLICATION_FACTORY)).getApplication();
    FacesConfigData dispenser = getDispenser();
    ActionListener actionListener = ClassUtils.buildApplicationObject(ActionListener.class, dispenser.getActionListenerIterator(), null);
    _callInjectAndPostConstruct(actionListener);
    application.setActionListener(actionListener);
    if (dispenser.getDefaultLocale() != null) {
        application.setDefaultLocale(LocaleUtils.toLocale(dispenser.getDefaultLocale()));
    }
    if (dispenser.getDefaultRenderKitId() != null) {
        application.setDefaultRenderKitId(dispenser.getDefaultRenderKitId());
    }
    if (dispenser.getMessageBundle() != null) {
        application.setMessageBundle(dispenser.getMessageBundle());
    }
    // First build the object
    NavigationHandler navigationHandler = ClassUtils.buildApplicationObject(NavigationHandler.class, ConfigurableNavigationHandler.class, null, dispenser.getNavigationHandlerIterator(), application.getNavigationHandler());
    // Invoke inject and post construct
    _callInjectAndPostConstruct(navigationHandler);
    // Finally wrap the object with the BackwardsCompatibleNavigationHandlerWrapper if it is not assignable
    // from ConfigurableNavigationHandler
    navigationHandler = ClassUtils.wrapBackwardCompatible(NavigationHandler.class, ConfigurableNavigationHandler.class, BackwardsCompatibleNavigationHandlerWrapper.class, application.getNavigationHandler(), navigationHandler);
    application.setNavigationHandler(navigationHandler);
    StateManager stateManager = ClassUtils.buildApplicationObject(StateManager.class, dispenser.getStateManagerIterator(), application.getStateManager());
    _callInjectAndPostConstruct(stateManager);
    application.setStateManager(stateManager);
    ResourceHandler resourceHandler = ClassUtils.buildApplicationObject(ResourceHandler.class, dispenser.getResourceHandlerIterator(), application.getResourceHandler());
    _callInjectAndPostConstruct(resourceHandler);
    application.setResourceHandler(resourceHandler);
    List<Locale> locales = new ArrayList<>();
    for (String locale : dispenser.getSupportedLocalesIterator()) {
        locales.add(LocaleUtils.toLocale(locale));
    }
    application.setSupportedLocales(locales);
    application.setViewHandler(ClassUtils.buildApplicationObject(ViewHandler.class, dispenser.getViewHandlerIterator(), application.getViewHandler()));
    application.setSearchExpressionHandler(ClassUtils.buildApplicationObject(SearchExpressionHandler.class, dispenser.getSearchExpressionHandlerIterator(), application.getSearchExpressionHandler()));
    for (SystemEventListener systemEventListener : dispenser.getSystemEventListeners()) {
        try {
            // note here used to be an instantiation to deal with the explicit source type in the registration,
            // that cannot work because all system events need to have the source being passed in the constructor
            // instead we now  rely on the standard system event types and map them to their appropriate
            // constructor types
            Class eventClass = ClassUtils.classForName((systemEventListener.getSystemEventClass() != null) ? systemEventListener.getSystemEventClass() : SystemEvent.class.getName());
            jakarta.faces.event.SystemEventListener listener = (jakarta.faces.event.SystemEventListener) ClassUtils.newInstance(systemEventListener.getSystemEventListenerClass());
            _callInjectAndPostConstruct(listener);
            if (systemEventListener.getSourceClass() != null && systemEventListener.getSourceClass().length() > 0) {
                application.subscribeToEvent((Class<? extends SystemEvent>) eventClass, ClassUtils.classForName(systemEventListener.getSourceClass()), listener);
            } else {
                application.subscribeToEvent((Class<? extends SystemEvent>) eventClass, listener);
            }
        } catch (ClassNotFoundException e) {
            log.log(Level.SEVERE, "System event listener could not be initialized, reason:", e);
        }
    }
    for (Map.Entry<String, Component> entry : dispenser.getComponentsByType().entrySet()) {
        application.addComponent(entry.getKey(), entry.getValue().getComponentClass());
    }
    for (Map.Entry<String, String> entry : dispenser.getConverterClassesById().entrySet()) {
        application.addConverter(entry.getKey(), entry.getValue());
    }
    for (Map.Entry<String, String> entry : dispenser.getConverterClassesByClass().entrySet()) {
        try {
            application.addConverter(ClassUtils.classForName(entry.getKey()), entry.getValue());
        } catch (Exception ex) {
            log.log(Level.SEVERE, "Converter could not be added. Reason:", ex);
        }
    }
    for (Map.Entry<String, String> entry : dispenser.getValidatorClassesById().entrySet()) {
        application.addValidator(entry.getKey(), entry.getValue());
    }
    // programmatically add the BeanValidator if the following requirements are met:
    // - bean validation has not been disabled
    // - bean validation is available in the classpath
    String beanValidatorDisabled = _externalContext.getInitParameter(BeanValidator.DISABLE_DEFAULT_BEAN_VALIDATOR_PARAM_NAME);
    final boolean defaultBeanValidatorDisabled = (beanValidatorDisabled != null && beanValidatorDisabled.toLowerCase().equals("true"));
    boolean beanValidatorInstalledProgrammatically = false;
    if (!defaultBeanValidatorDisabled && ExternalSpecifications.isBeanValidationAvailable()) {
        // add the BeanValidator as default validator
        application.addDefaultValidatorId(BeanValidator.VALIDATOR_ID);
        beanValidatorInstalledProgrammatically = true;
    }
    // add the default-validators from the config files
    for (String validatorId : dispenser.getDefaultValidatorIds()) {
        application.addDefaultValidatorId(validatorId);
    }
    // default-validator programmatically, but via a config file.
    if (!beanValidatorInstalledProgrammatically && application.getDefaultValidatorInfo().containsKey(BeanValidator.VALIDATOR_ID)) {
        if (!ExternalSpecifications.isBeanValidationAvailable()) {
            // the BeanValidator was installed via a config file,
            // but bean validation is not available
            log.log(Level.WARNING, "The BeanValidator was installed as a " + "default-validator from a faces-config file, but bean " + "validation is not available on the classpath, " + "thus it will not work!");
        } else if (defaultBeanValidatorDisabled) {
            // the user disabled the default bean validator in web.xml,
            // but a config file added it, which is ok with the spec
            // (section 11.1.3: "though manual installation is still possible")
            // --> inform the user about this scenario
            log.log(Level.INFO, "The BeanValidator was disabled as a " + "default-validator via the config parameter " + BeanValidator.DISABLE_DEFAULT_BEAN_VALIDATOR_PARAM_NAME + " in web.xml, but a faces-config file added it, " + "thus it actually was installed as a default-validator.");
        }
    }
    for (Behavior behavior : dispenser.getBehaviors()) {
        application.addBehavior(behavior.getBehaviorId(), behavior.getBehaviorClass());
    }
    // JSF 2.2 set FlowHandler from factory.
    FlowHandlerFactory flowHandlerFactory = (FlowHandlerFactory) FactoryFinder.getFactory(FactoryFinder.FLOW_HANDLER_FACTORY);
    FlowHandler flowHandler = flowHandlerFactory.createFlowHandler(getFacesContext());
    application.setFlowHandler(flowHandler);
    for (ContractMapping mapping : dispenser.getResourceLibraryContractMappings()) {
        List<String> urlMappingsList = mapping.getUrlPatternList();
        for (String urlPattern : urlMappingsList) {
            for (String contract : mapping.getContractList()) {
                String[] contracts = StringUtils.trim(StringUtils.splitShortString(contract, ' '));
                _runtimeConfig.addContractMapping(urlPattern, contracts);
            }
        }
    }
    this.setApplication(application);
}
Also used : Locale(java.util.Locale) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) ResourceHandler(jakarta.faces.application.ResourceHandler) ContractMapping(org.apache.myfaces.config.element.ContractMapping) StateManager(jakarta.faces.application.StateManager) SearchExpressionHandler(jakarta.faces.component.search.SearchExpressionHandler) Behavior(org.apache.myfaces.config.element.Behavior) Component(org.apache.myfaces.config.element.Component) FacesConfigData(org.apache.myfaces.config.element.FacesConfigData) ViewHandler(jakarta.faces.application.ViewHandler) ConfigurableNavigationHandler(jakarta.faces.application.ConfigurableNavigationHandler) NavigationHandler(jakarta.faces.application.NavigationHandler) InvocationTargetException(java.lang.reflect.InvocationTargetException) InjectionProviderException(org.apache.myfaces.spi.InjectionProviderException) IOException(java.io.IOException) FacesException(jakarta.faces.FacesException) ConfigurableNavigationHandler(jakarta.faces.application.ConfigurableNavigationHandler) FlowHandlerFactory(jakarta.faces.flow.FlowHandlerFactory) SystemEventListener(org.apache.myfaces.config.element.SystemEventListener) ActionListener(jakarta.faces.event.ActionListener) ApplicationFactory(jakarta.faces.application.ApplicationFactory) FlowHandler(jakarta.faces.flow.FlowHandler) Application(jakarta.faces.application.Application) BackwardsCompatibleNavigationHandlerWrapper(org.apache.myfaces.application.BackwardsCompatibleNavigationHandlerWrapper) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

StateManager (jakarta.faces.application.StateManager)8 IOException (java.io.IOException)4 ELException (jakarta.el.ELException)3 FacesException (jakarta.faces.FacesException)3 PrintWriter (java.io.PrintWriter)3 TCKStateManager (com.sun.ts.tests.jsf.common.statemanager.TCKStateManager)2 Application (jakarta.faces.application.Application)2 ResponseWriter (jakarta.faces.context.ResponseWriter)2 ResponseStateManager (jakarta.faces.render.ResponseStateManager)2 ServletException (jakarta.servlet.ServletException)2 Util.getLocaleFromString (com.sun.faces.util.Util.getLocaleFromString)1 ApplicationFactory (jakarta.faces.application.ApplicationFactory)1 ApplicationWrapper (jakarta.faces.application.ApplicationWrapper)1 ConfigurableNavigationHandler (jakarta.faces.application.ConfigurableNavigationHandler)1 NavigationHandler (jakarta.faces.application.NavigationHandler)1 ResourceHandler (jakarta.faces.application.ResourceHandler)1 ViewHandler (jakarta.faces.application.ViewHandler)1 SearchExpressionHandler (jakarta.faces.component.search.SearchExpressionHandler)1 ExternalContext (jakarta.faces.context.ExternalContext)1 ActionListener (jakarta.faces.event.ActionListener)1