Search in sources :

Example 1 with PartialViewContext

use of jakarta.faces.context.PartialViewContext in project myfaces by apache.

the class PartialViewContextImpl method processPartialRendering.

private void processPartialRendering(UIViewRoot viewRoot, PhaseId phaseId) {
    // note that we cannot use this.getPartialResponseWriter(), because
    // this could cause problems if PartialResponseWriter is wrapped
    PartialResponseWriter writer = context.getPartialViewContext().getPartialResponseWriter();
    PartialViewContext pvc = context.getPartialViewContext();
    ResponseWriter oldWriter = context.getResponseWriter();
    boolean inDocument = false;
    // response type = text/xml
    // no caching and no timeout if possible!
    ExternalContext externalContext = context.getExternalContext();
    externalContext.setResponseContentType("text/xml");
    externalContext.addResponseHeader("Pragma", "no-cache");
    externalContext.addResponseHeader("Cache-control", "no-cache");
    // under normal circumstances pragma should be enough, IE needs
    // a special treatment!
    // http://support.microsoft.com/kb/234067
    externalContext.addResponseHeader("Expires", "-1");
    try {
        String currentEncoding = writer.getCharacterEncoding();
        writer.writePreamble("<?xml version=\"1.0\" encoding=\"" + (currentEncoding == null ? "UTF-8" : currentEncoding) + "\"?>");
        writer.startDocument();
        writer.writeAttribute("id", viewRoot.getContainerClientId(context), "id");
        inDocument = true;
        context.setResponseWriter(writer);
        if (isResetValues()) {
            viewRoot.resetValues(context, getRenderIds());
        }
        if (pvc.isRenderAll()) {
            processRenderAll(viewRoot, writer);
        } else {
            Collection<String> renderIds = pvc.getRenderIds();
            // Only apply partial visit if we have ids to traverse
            if (renderIds != null && !renderIds.isEmpty()) {
                // render=@all, so output the body.
                if (renderIds.contains(PartialResponseWriter.RENDER_ALL_MARKER)) {
                    processRenderAll(viewRoot, writer);
                } else {
                    // In JSF 2.3 it was added jakarta.faces.Resource as an update target to add scripts or
                    // stylesheets inside <head> tag
                    List<UIComponent> updatedComponents = new ArrayList<>();
                    RequestViewContext rvc = RequestViewContext.getCurrentInstance(context);
                    processRenderResource(context, writer, rvc, updatedComponents, "head");
                    processRenderResource(context, writer, rvc, updatedComponents, "body");
                    processRenderResource(context, writer, rvc, updatedComponents, "form");
                    VisitContext visitCtx = getVisitContextFactory().getVisitContext(context, renderIds, MyFacesVisitHints.SET_SKIP_UNRENDERED);
                    viewRoot.visitTree(visitCtx, new PhaseAwareVisitCallback(context, phaseId, updatedComponents));
                }
            } else {
                List<UIComponent> updatedComponents = new ArrayList<>();
                RequestViewContext rvc = RequestViewContext.getCurrentInstance(context);
                processRenderResource(context, writer, rvc, updatedComponents, "head");
                processRenderResource(context, writer, rvc, updatedComponents, "body");
                processRenderResource(context, writer, rvc, updatedComponents, "form");
            }
            List<String> evalScripts = pvc.getEvalScripts();
            if (evalScripts != null && evalScripts.size() > 0) {
                for (String script : evalScripts) {
                    writer.startEval();
                    writer.write(script);
                    writer.endEval();
                }
            }
        }
        // invoke encodeAll() on every UIViewParameter in the view to
        // enable every UIViewParameter to save its value in the state
        // just like UIViewRoot.encodeEnd() does on a normal request
        // (see MYFACES-2645 for details)
        Collection<UIViewParameter> viewParams = ViewMetadata.getViewParameters(viewRoot);
        if (!viewParams.isEmpty()) {
            for (UIViewParameter param : viewParams) {
                param.encodeAll(context);
            }
        }
        // Retrieve the state and apply it if it is not null.
        String viewState = context.getApplication().getStateManager().getViewState(context);
        if (viewState != null) {
            writer.startUpdate(HtmlResponseStateManager.generateUpdateViewStateId(context));
            writer.write(viewState);
            writer.endUpdate();
        } else if (viewRoot.isTransient()) {
            writer.startUpdate(HtmlResponseStateManager.generateUpdateViewStateId(context));
            writer.write(StateTokenProcessor.STATELESS_TOKEN);
            writer.endUpdate();
        }
        ClientWindow cw = context.getExternalContext().getClientWindow();
        if (cw != null) {
            writer.startUpdate(HtmlResponseStateManager.generateUpdateClientWindowId(context));
            writer.writeText(cw.getId(), null);
            writer.endUpdate();
        }
    } catch (IOException ex) {
        if (log.isLoggable(Level.SEVERE)) {
            log.log(Level.SEVERE, "", ex);
        }
    } finally {
        try {
            if (inDocument) {
                writer.endDocument();
            }
            writer.flush();
        } catch (IOException ex) {
            if (log.isLoggable(Level.SEVERE)) {
                log.log(Level.SEVERE, "", ex);
            }
        }
        context.setResponseWriter(oldWriter);
    }
}
Also used : VisitContext(jakarta.faces.component.visit.VisitContext) ClientWindow(jakarta.faces.lifecycle.ClientWindow) UIComponent(jakarta.faces.component.UIComponent) ArrayList(java.util.ArrayList) RequestViewContext(org.apache.myfaces.context.RequestViewContext) PartialResponseWriter(jakarta.faces.context.PartialResponseWriter) IOException(java.io.IOException) ResponseWriter(jakarta.faces.context.ResponseWriter) PartialResponseWriter(jakarta.faces.context.PartialResponseWriter) ExternalContext(jakarta.faces.context.ExternalContext) UIViewParameter(jakarta.faces.component.UIViewParameter) PartialViewContext(jakarta.faces.context.PartialViewContext)

Example 2 with PartialViewContext

use of jakarta.faces.context.PartialViewContext in project myfaces by apache.

the class PartialViewContextImpl method processPartialExecute.

private void processPartialExecute(UIViewRoot viewRoot, PhaseId phaseId) {
    PartialViewContext pvc = context.getPartialViewContext();
    Collection<String> executeIds = pvc.getExecuteIds();
    if (executeIds == null || executeIds.isEmpty()) {
        return;
    }
    VisitContext visitCtx = getVisitContextFactory().getVisitContext(context, executeIds, PARTIAL_EXECUTE_HINTS);
    viewRoot.visitTree(visitCtx, new PhaseAwareVisitCallback(context, phaseId));
}
Also used : VisitContext(jakarta.faces.component.visit.VisitContext) PartialViewContext(jakarta.faces.context.PartialViewContext)

Example 3 with PartialViewContext

use of jakarta.faces.context.PartialViewContext in project myfaces by apache.

the class ServletExternalContextImpl method redirect.

@Override
public void redirect(final String url) throws IOException {
    FacesContext facesContext = getCurrentFacesContext();
    PartialViewContext partialViewContext = facesContext.getPartialViewContext();
    if (partialViewContext.isPartialRequest()) {
        PartialResponseWriter writer = partialViewContext.getPartialResponseWriter();
        this.setResponseContentType("text/xml");
        this.setResponseCharacterEncoding("UTF-8");
        this.addResponseHeader("Cache-control", "no-cache");
        writer.startDocument();
        writer.redirect(url);
        writer.endDocument();
        facesContext.responseComplete();
    } else if (_servletResponse instanceof HttpServletResponse) {
        ((HttpServletResponse) _servletResponse).sendRedirect(url);
        facesContext.responseComplete();
    } else {
        throw new IllegalArgumentException("Only HttpServletResponse supported");
    }
}
Also used : FacesContext(jakarta.faces.context.FacesContext) PartialResponseWriter(jakarta.faces.context.PartialResponseWriter) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) PartialViewContext(jakarta.faces.context.PartialViewContext)

Example 4 with PartialViewContext

use of jakarta.faces.context.PartialViewContext in project myfaces by apache.

the class NavigationHandlerImpl method handleNavigation.

@Override
public void handleNavigation(FacesContext facesContext, String fromAction, String outcome, String toFlowDocumentId) {
    NavigationContext navigationContext = new NavigationContext();
    NavigationCase navigationCase = null;
    try {
        navigationCase = getNavigationCommand(facesContext, navigationContext, fromAction, outcome, toFlowDocumentId);
    } finally {
        navigationContext.finish(facesContext);
    }
    if (navigationCase != null) {
        if (log.isLoggable(Level.FINEST)) {
            log.finest("handleNavigation fromAction=" + fromAction + " outcome=" + outcome + " toViewId =" + navigationCase.getToViewId(facesContext) + " redirect=" + navigationCase.isRedirect());
        }
        boolean isViewActionProcessingBroadcastAndRequiresRedirect = false;
        if (UIViewAction.isProcessingBroadcast(facesContext)) {
            // f:viewAction tag always triggers a redirect to enforce execution of
            // the lifecycle again. Note this requires enables flash scope
            // keepMessages automatically, because a view action can add messages
            // and these ones requires to be renderer afterwards.
            facesContext.getExternalContext().getFlash().setKeepMessages(true);
            String fromViewId = (facesContext.getViewRoot() == null) ? null : facesContext.getViewRoot().getViewId();
            String toViewId = navigationCase.getToViewId(facesContext);
            // lifecycle is not necessary.
            if (fromViewId == null && toViewId != null) {
                isViewActionProcessingBroadcastAndRequiresRedirect = true;
            } else if (fromViewId != null && !fromViewId.equals(toViewId)) {
                isViewActionProcessingBroadcastAndRequiresRedirect = true;
            }
        }
        if (navigationCase.isRedirect() || isViewActionProcessingBroadcastAndRequiresRedirect) {
            // Need to add the FlowHandler parameters here.
            FlowHandler flowHandler = facesContext.getApplication().getFlowHandler();
            List<Flow> activeFlows = FlowHandlerImpl.getActiveFlows(facesContext, flowHandler);
            Flow currentFlow = flowHandler.getCurrentFlow(facesContext);
            Flow targetFlow = calculateTargetFlow(facesContext, outcome, flowHandler, activeFlows, toFlowDocumentId);
            Map<String, List<String>> navigationCaseParameters = navigationCase.getParameters();
            // sourceFlow and targetFlow could both be null so need to have multiple checks here
            if (currentFlow != targetFlow) {
                // Ensure that at least one has a value and check for equality
                if ((currentFlow != null && !currentFlow.equals(targetFlow)) || (targetFlow != null && !targetFlow.equals(currentFlow))) {
                    if (navigationCaseParameters == null) {
                        navigationCaseParameters = new HashMap<>(5, 1f);
                    }
                    // include the following entries:
                    if (currentFlow != null && targetFlow == null) {
                        // Set the TO_FLOW_DOCUMENT_ID_REQUEST_PARAM_NAME parameter
                        navigationCaseParameters.put(FlowHandler.TO_FLOW_DOCUMENT_ID_REQUEST_PARAM_NAME, Arrays.asList(FlowHandler.NULL_FLOW));
                        // Set the FLOW_ID_REQUEST_PARAM_NAME
                        navigationCaseParameters.put(FlowHandler.FLOW_ID_REQUEST_PARAM_NAME, Arrays.asList(""));
                    } else {
                        // If current flow (sourceFlow) is null and new flow (targetFlow) is not null,
                        // include the following entries:
                        // If we make it this far we know the above statement is true due to the other
                        // logical checks we have hit to this point.
                        // Set the TO_FLOW_DOCUMENT_ID_REQUEST_PARAM_NAME parameter
                        navigationCaseParameters.put(FlowHandler.TO_FLOW_DOCUMENT_ID_REQUEST_PARAM_NAME, Arrays.asList((toFlowDocumentId == null ? "" : toFlowDocumentId)));
                        // Set the FLOW_ID_REQUEST_PARAM_NAME
                        navigationCaseParameters.put(FlowHandler.FLOW_ID_REQUEST_PARAM_NAME, Arrays.asList(targetFlow.getId()));
                    }
                }
            }
            ExternalContext externalContext = facesContext.getExternalContext();
            ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
            String toViewId = navigationCase.getToViewId(facesContext);
            String redirectPath = viewHandler.getRedirectURL(facesContext, toViewId, NavigationUtils.getEvaluatedNavigationParameters(facesContext, navigationCaseParameters), navigationCase.isIncludeViewParams());
            // The spec doesn't say anything about how to handle redirect but it is
            // better to apply the transition here where we have already calculated the
            // route than add the parameters and delegate to
            // FlowHandler.clientWindowTransition(facesContext)
            applyFlowTransition(facesContext, navigationContext);
            // Clear ViewMap if we are redirecting to other resource
            UIViewRoot viewRoot = facesContext.getViewRoot();
            if (viewRoot != null && !toViewId.equals(viewRoot.getViewId())) {
                // call getViewMap(false) to prevent unnecessary map creation
                Map<String, Object> viewMap = viewRoot.getViewMap(false);
                if (viewMap != null) {
                    viewMap.clear();
                }
            }
            // JSF 2.0 the javadoc of handleNavigation() says something like this
            // "...If the view has changed after an application action, call
            // PartialViewContext.setRenderAll(true)...". The effect is that ajax requests
            // are included on navigation.
            PartialViewContext partialViewContext = facesContext.getPartialViewContext();
            String viewId = facesContext.getViewRoot() != null ? facesContext.getViewRoot().getViewId() : null;
            if (partialViewContext.isPartialRequest() && !partialViewContext.isRenderAll() && toViewId != null && !toViewId.equals(viewId)) {
                partialViewContext.setRenderAll(true);
            }
            // Dispose view if the view has been marked as disposable by default action listener
            ViewPoolProcessor processor = ViewPoolProcessor.getInstance(facesContext);
            if (processor != null && processor.isViewPoolEnabledForThisView(facesContext, facesContext.getViewRoot())) {
                processor.disposeView(facesContext, facesContext.getViewRoot());
            }
            // JSF 2.0 Spec call Flash.setRedirect(true) to notify Flash scope and take proper actions
            externalContext.getFlash().setRedirect(true);
            try {
                externalContext.redirect(redirectPath);
                facesContext.responseComplete();
            } catch (IOException e) {
                throw new FacesException(e.getMessage(), e);
            }
        } else {
            ViewHandler viewHandler = facesContext.getApplication().getViewHandler();
            // create new view
            String newViewId = navigationCase.getToViewId(facesContext);
            // JSF 2.0 the javadoc of handleNavigation() says something like this
            // "...If the view has changed after an application action, call
            // PartialViewContext.setRenderAll(true)...". The effect is that ajax requests
            // are included on navigation.
            PartialViewContext partialViewContext = facesContext.getPartialViewContext();
            String viewId = facesContext.getViewRoot() != null ? facesContext.getViewRoot().getViewId() : null;
            if (partialViewContext.isPartialRequest() && !partialViewContext.isRenderAll() && newViewId != null && !newViewId.equals(viewId)) {
                partialViewContext.setRenderAll(true);
            }
            if (facesContext.getViewRoot() != null && facesContext.getViewRoot().getAttributes().containsKey(CALL_PRE_DISPOSE_VIEW)) {
                try {
                    facesContext.getAttributes().put(MyFacesVisitHints.SKIP_ITERATION_HINT, Boolean.TRUE);
                    VisitContext visitContext = VisitContext.createVisitContext(facesContext, null, MyFacesVisitHints.SET_SKIP_ITERATION);
                    facesContext.getViewRoot().visitTree(visitContext, PreDisposeViewCallback.INSTANCE);
                } finally {
                    facesContext.getAttributes().remove(MyFacesVisitHints.SKIP_ITERATION_HINT);
                }
            }
            applyFlowTransition(facesContext, navigationContext);
            // Dispose view if the view has been marked as disposable by default action listener
            ViewPoolProcessor processor = ViewPoolProcessor.getInstance(facesContext);
            if (processor != null && processor.isViewPoolEnabledForThisView(facesContext, facesContext.getViewRoot())) {
                processor.disposeView(facesContext, facesContext.getViewRoot());
            }
            // create UIViewRoot for new view
            UIViewRoot viewRoot = null;
            String derivedViewId = viewHandler.deriveViewId(facesContext, newViewId);
            if (derivedViewId != null) {
                ViewDeclarationLanguage vdl = viewHandler.getViewDeclarationLanguage(facesContext, derivedViewId);
                if (vdl != null) {
                    ViewMetadata metadata = vdl.getViewMetadata(facesContext, newViewId);
                    if (metadata != null) {
                        viewRoot = metadata.createMetadataView(facesContext);
                    }
                }
            }
            // - viewHandler.deriveViewId() returned null
            if (viewRoot == null) {
                viewRoot = viewHandler.createView(facesContext, newViewId);
            }
            facesContext.setViewRoot(viewRoot);
            facesContext.renderResponse();
        }
    } else {
        // no navigationcase found, stay on current ViewRoot
        if (log.isLoggable(Level.FINEST)) {
            log.finest("handleNavigation fromAction=" + fromAction + " outcome=" + outcome + " no matching navigation-case found, staying on current ViewRoot");
        }
    }
}
Also used : ViewHandler(jakarta.faces.application.ViewHandler) VisitContext(jakarta.faces.component.visit.VisitContext) IOException(java.io.IOException) ViewDeclarationLanguage(jakarta.faces.view.ViewDeclarationLanguage) ViewPoolProcessor(org.apache.myfaces.view.facelets.ViewPoolProcessor) FacesException(jakarta.faces.FacesException) Flow(jakarta.faces.flow.Flow) NavigationCase(jakarta.faces.application.NavigationCase) ExternalContext(jakarta.faces.context.ExternalContext) List(java.util.List) ArrayList(java.util.ArrayList) PartialViewContext(jakarta.faces.context.PartialViewContext) FlowHandler(jakarta.faces.flow.FlowHandler) UIViewRoot(jakarta.faces.component.UIViewRoot) ViewMetadata(jakarta.faces.view.ViewMetadata)

Example 5 with PartialViewContext

use of jakarta.faces.context.PartialViewContext in project myfaces by apache.

the class UIViewRoot method encodeEnd.

@Override
public void encodeEnd(FacesContext context) throws IOException {
    Assert.notNull(context, "context");
    if (!context.getResponseComplete()) {
        super.encodeEnd(context);
        // the call to encodeAll() on every UIViewParameter here is only necessary
        // if the current request is _not_ an AJAX request, because if it was an
        // AJAX request, the call would already have happened in PartialViewContextImpl and
        // would anyway be too late here, because the state would already have been generated
        PartialViewContext partialContext = context.getPartialViewContext();
        if (!partialContext.isAjaxRequest()) {
            ViewDeclarationLanguage vdl = context.getApplication().getViewHandler().getViewDeclarationLanguage(context, getViewId());
            if (vdl != null) {
                // If the current view has view parameters, as indicated by a non-empty
                // and non-UnsupportedOperationException throwing
                // return from ViewDeclarationLanguage.getViewMetadata(jakarta.faces.context.FacesContext, String)
                ViewMetadata metadata = null;
                try {
                    metadata = vdl.getViewMetadata(context, getViewId());
                } catch (UnsupportedOperationException e) {
                    _getLogger().log(Level.SEVERE, "Exception while obtaining the view metadata: " + e.getMessage(), e);
                }
                if (metadata != null) {
                    try {
                        Collection<UIViewParameter> viewParams = ViewMetadata.getViewParameters(this);
                        if (!viewParams.isEmpty()) {
                            // call UIViewParameter.encodeAll(jakarta.faces.context.FacesContext) on each parameter.
                            for (UIViewParameter param : viewParams) {
                                param.encodeAll(context);
                            }
                        }
                    } catch (UnsupportedOperationException e) {
                    // If calling getViewParameters() causes UnsupportedOperationException
                    // to be thrown, the exception must be silently swallowed.
                    }
                }
            }
        }
    }
    try {
        notifyListeners(context, PhaseId.RENDER_RESPONSE, getAfterPhaseListener(), false);
    } catch (Exception e) {
        // following the spec we have to swallow the exception
        _getLogger().log(Level.SEVERE, "Exception while processing phase listener: " + e.getMessage(), e);
    }
}
Also used : PartialViewContext(jakarta.faces.context.PartialViewContext) ViewDeclarationLanguage(jakarta.faces.view.ViewDeclarationLanguage) AbortProcessingException(jakarta.faces.event.AbortProcessingException) IOException(java.io.IOException) ViewMetadata(jakarta.faces.view.ViewMetadata)

Aggregations

PartialViewContext (jakarta.faces.context.PartialViewContext)28 FacesContext (jakarta.faces.context.FacesContext)15 FacesContextImpl (org.apache.myfaces.context.servlet.FacesContextImpl)9 HashMap (java.util.HashMap)8 PartialResponseWriter (jakarta.faces.context.PartialResponseWriter)7 IOException (java.io.IOException)7 ExternalContext (jakarta.faces.context.ExternalContext)4 FacesException (jakarta.faces.FacesException)3 VisitContext (jakarta.faces.component.visit.VisitContext)3 ArrayList (java.util.ArrayList)3 UIComponent (jakarta.faces.component.UIComponent)2 UIViewRoot (jakarta.faces.component.UIViewRoot)2 ResponseWriter (jakarta.faces.context.ResponseWriter)2 AbortProcessingException (jakarta.faces.event.AbortProcessingException)2 ClientWindow (jakarta.faces.lifecycle.ClientWindow)2 ViewDeclarationLanguage (jakarta.faces.view.ViewDeclarationLanguage)2 ViewMetadata (jakarta.faces.view.ViewMetadata)2 ServletException (jakarta.servlet.ServletException)2 PrintWriter (java.io.PrintWriter)2 NavigationCase (jakarta.faces.application.NavigationCase)1