Search in sources :

Example 1 with VisitContext

use of jakarta.faces.component.visit.VisitContext 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 VisitContext

use of jakarta.faces.component.visit.VisitContext 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 VisitContext

use of jakarta.faces.component.visit.VisitContext 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 4 with VisitContext

use of jakarta.faces.component.visit.VisitContext in project myfaces by apache.

the class IdSearchKeywordResolver method resolve.

@Override
public void resolve(SearchKeywordContext expressionContext, UIComponent current, String keyword) {
    FacesContext facesContext = expressionContext.getSearchExpressionContext().getFacesContext();
    final String targetId = extractId(keyword);
    if (expressionContext.getSearchExpressionContext().getExpressionHints() != null && expressionContext.getSearchExpressionContext().getExpressionHints().contains(SearchExpressionHint.SKIP_VIRTUAL_COMPONENTS)) {
        // Avoid visit tree because in this case we need real component instances.
        // This means components inside UIData will not be scanned.
        withId(facesContext, targetId, current, expressionContext.getCallback());
        expressionContext.setKeywordResolved(true);
    } else {
        current.visitTree(VisitContext.createVisitContext(facesContext, null, expressionContext.getSearchExpressionContext().getVisitHints()), new VisitCallback() {

            @Override
            public VisitResult visit(VisitContext context, UIComponent target) {
                if (targetId.equals(target.getId())) {
                    expressionContext.invokeContextCallback(target);
                    if (expressionContext.getSearchExpressionContext().getExpressionHints() != null && expressionContext.getSearchExpressionContext().getExpressionHints().contains(SearchExpressionHint.RESOLVE_SINGLE_COMPONENT)) {
                        return VisitResult.COMPLETE;
                    }
                    return VisitResult.ACCEPT;
                } else {
                    return VisitResult.ACCEPT;
                }
            }
        });
    }
}
Also used : FacesContext(jakarta.faces.context.FacesContext) VisitCallback(jakarta.faces.component.visit.VisitCallback) VisitContext(jakarta.faces.component.visit.VisitContext) UIComponent(jakarta.faces.component.UIComponent) VisitResult(jakarta.faces.component.visit.VisitResult)

Example 5 with VisitContext

use of jakarta.faces.component.visit.VisitContext in project myfaces by apache.

the class UISelectOne method processValidators.

/**
 * Verify that when ever there is a ValueExpression and submitted value is not empty, then
 * visit all the UISelectItem elements within the UISelectOne radio components to check if
 * the submitted value exists in any of the select items.
 *
 * @see jakarta.faces.component.UIInput#processValidators(jakarta.faces.context.FacesContext)
 */
@Override
public void processValidators(FacesContext context) {
    String group = getGroup();
    ValueExpression ve = getValueExpression("value");
    String submittedValue = (String) getSubmittedValue();
    if (group != null && !group.isEmpty() && ve != null && !isEmpty(submittedValue)) {
        final UIComponent form = getRadioNestingForm(context, this);
        form.visitTree(VisitContext.createVisitContext(context), new VisitCallback() {

            @Override
            public VisitResult visit(VisitContext visitContext, UIComponent target) {
                if (target instanceof UISelectOne && ((UISelectOne) target).getGroup().equals(group)) {
                    UISelectOne radio = (UISelectOne) target;
                    // and verify if the submitted value exists
                    for (Iterator<UIComponent> iter = radio.getChildren().iterator(); iter.hasNext(); ) {
                        UIComponent component = iter.next();
                        if (component instanceof UISelectItem) {
                            UISelectItem item = (UISelectItem) component;
                            if (item.getItemValue().equals(submittedValue)) {
                                selectItemValueFound = true;
                                return VisitResult.COMPLETE;
                            }
                        }
                    }
                    return VisitResult.REJECT;
                }
                return VisitResult.ACCEPT;
            }
        });
    }
    super.processValidators(context);
}
Also used : VisitCallback(jakarta.faces.component.visit.VisitCallback) VisitContext(jakarta.faces.component.visit.VisitContext) ValueExpression(jakarta.el.ValueExpression) Iterator(java.util.Iterator) SelectItemsIterator(org.apache.myfaces.core.api.shared.SelectItemsIterator) VisitResult(jakarta.faces.component.visit.VisitResult) UISelectItem(jakarta.faces.component.UISelectItem)

Aggregations

VisitContext (jakarta.faces.component.visit.VisitContext)27 UIComponent (jakarta.faces.component.UIComponent)13 VisitResult (jakarta.faces.component.visit.VisitResult)12 VisitHint (jakarta.faces.component.visit.VisitHint)11 UIViewRoot (jakarta.faces.component.UIViewRoot)8 FacesContext (jakarta.faces.context.FacesContext)8 ArrayList (java.util.ArrayList)6 VisitCallback (jakarta.faces.component.visit.VisitCallback)5 StateContext (com.sun.faces.context.StateContext)4 HashMap (java.util.HashMap)4 FacesException (jakarta.faces.FacesException)3 UIForm (jakarta.faces.component.UIForm)3 PartialViewContext (jakarta.faces.context.PartialViewContext)3 IOException (java.io.IOException)3 NamingContainer (jakarta.faces.component.NamingContainer)2 ExternalContext (jakarta.faces.context.ExternalContext)2 Map (java.util.Map)2 MockVisitCallback (org.apache.myfaces.test.mock.visit.MockVisitCallback)2 PartialVisitContext (com.sun.faces.component.visit.PartialVisitContext)1 ValueExpression (jakarta.el.ValueExpression)1