Search in sources :

Example 1 with FacesException

use of jakarta.faces.FacesException in project myfaces by apache.

the class UIComponentBase method getClientId.

/**
 * Get a string which can be output to the response which uniquely identifies this UIComponent within the current
 * view.
 * <p>
 * The component should have an id attribute already assigned to it; however if the id property is currently null
 * then a unique id is generated and set for this component. This only happens when components are programmatically
 * created without ids, as components created by a ViewHandler should be assigned ids when they are created.
 * <p>
 * If this component is a descendant of a NamingContainer then the client id is of form
 * "{namingContainerId}:{componentId}". Note that the naming container's id may itself be of compound form if it has
 * an ancestor naming container. Note also that this only applies to naming containers; other UIComponent types in
 * the component's ancestry do not affect the clientId.
 * <p>
 * Finally the renderer associated with this component is asked to convert the id into a suitable form. This allows
 * escaping of any characters in the clientId which are significant for the markup language generated by that
 * renderer.
 */
@Override
public String getClientId(FacesContext context) {
    Assert.notNull(context, "context");
    if (_clientId != null) {
        return _clientId;
    }
    String id = getId();
    if (id == null) {
        // Although this is an error prone side effect, we automatically create a new id
        // just to be compatible to the RI
        // The documentation of UniqueIdVendor says that this interface should be implemented by
        // components that also implements NamingContainer. The only component that does not implement
        // NamingContainer but UniqueIdVendor is UIViewRoot. Anyway we just can't be 100% sure about this
        // fact, so it is better to scan for the closest UniqueIdVendor. If it is not found use
        // viewRoot.createUniqueId, otherwise use UniqueIdVendor.createUniqueId(context,seed).
        UniqueIdVendor parentUniqueIdVendor = ComponentUtils.findClosest(UniqueIdVendor.class, this);
        if (parentUniqueIdVendor == null) {
            UIViewRoot viewRoot = context.getViewRoot();
            if (viewRoot != null) {
                id = viewRoot.createUniqueId();
            } else {
                // The RI throws a NPE
                String location = getComponentLocation(this);
                throw new FacesException("Cannot create clientId. No id is assigned for component" + " to create an id and UIViewRoot is not defined: " + ComponentUtils.getPathToComponent(this) + (location != null ? " created from: " + location : ""));
            }
        } else {
            id = parentUniqueIdVendor.createUniqueId(context, null);
        }
        setId(id);
    }
    UIComponent namingContainer = ComponentUtils.findClosestNamingContainer(this, false);
    if (namingContainer != null) {
        String containerClientId = namingContainer.getContainerClientId(context);
        if (containerClientId != null) {
            StringBuilder bld = _getSharedStringBuilder(context);
            _clientId = bld.append(containerClientId).append(context.getNamingContainerSeparatorChar()).append(id).toString();
        } else {
            _clientId = id;
        }
    } else {
        _clientId = id;
    }
    Renderer renderer = getRenderer(context);
    if (renderer != null) {
        _clientId = renderer.convertClientId(context, _clientId);
    }
    return _clientId;
}
Also used : SharedStringBuilder(org.apache.myfaces.core.api.shared.lang.SharedStringBuilder) Renderer(jakarta.faces.render.Renderer) FacesException(jakarta.faces.FacesException)

Example 2 with FacesException

use of jakarta.faces.FacesException in project myfaces by apache.

the class UIData method invokeOnComponent.

@Override
public boolean invokeOnComponent(FacesContext context, String clientId, ContextCallback callback) throws FacesException {
    Assert.notNull(context, "context");
    Assert.notNull(clientId, "clientId");
    Assert.notNull(callback, "callback");
    final String baseClientId = getClientId(context);
    // searching for this component?
    boolean returnValue = baseClientId.equals(clientId);
    boolean isCachedFacesContext = isCachedFacesContext();
    if (!isCachedFacesContext) {
        setCachedFacesContext(context);
    }
    pushComponentToEL(context, this);
    try {
        if (returnValue) {
            try {
                callback.invokeContextCallback(context, this);
                return true;
            } catch (Exception e) {
                throw new FacesException(e);
            }
        }
        // Now Look throught facets on this UIComponent
        if (this.getFacetCount() > 0) {
            for (Iterator<UIComponent> it = this.getFacets().values().iterator(); !returnValue && it.hasNext(); ) {
                returnValue = it.next().invokeOnComponent(context, clientId, callback);
            }
        }
        if (returnValue) {
            return returnValue;
        }
        // is the component an inner component?
        if (clientId.startsWith(baseClientId)) {
            // Check if the clientId for the component, which we
            // are looking for, has a rowIndex attached
            char separator = context.getNamingContainerSeparatorChar();
            Pattern pattern = getSubIdPattern(context, separator);
            String subId = clientId.substring(baseClientId.length() + 1);
            // the subId matches the regular expression
            if (clientId.charAt(baseClientId.length()) == separator && pattern.matcher(subId).matches()) {
                String clientRow = subId.substring(0, subId.indexOf(separator));
                // Now we save the current position
                int oldRow = this.getRowIndex();
                // try-finally --> make sure, that the old row index is restored
                try {
                    // The conversion is safe, because its already checked on the
                    // regular expresion
                    this.setRowIndex(Integer.parseInt(clientRow));
                    // check, if the row is available
                    if (!isRowAvailable()) {
                        return false;
                    }
                    for (Iterator<UIComponent> it1 = getChildren().iterator(); !returnValue && it1.hasNext(); ) {
                        // recursive call to find the component
                        returnValue = it1.next().invokeOnComponent(context, clientId, callback);
                    }
                } finally {
                    // Restore the old position. Doing this prevent
                    // side effects.
                    this.setRowIndex(oldRow);
                }
            } else {
                // attached to the clientId of UIColumns' Facets' children.
                for (Iterator<UIComponent> itChildren = this.getChildren().iterator(); !returnValue && itChildren.hasNext(); ) {
                    UIComponent child = itChildren.next();
                    if (child instanceof UIColumn && clientId.equals(child.getClientId(context))) {
                        try {
                            callback.invokeContextCallback(context, child);
                        } catch (Exception e) {
                            throw new FacesException(e);
                        }
                        returnValue = true;
                    }
                    // process the child's facets
                    if (child.getFacetCount() > 0) {
                        for (Iterator<UIComponent> itChildFacets = child.getFacets().values().iterator(); !returnValue && itChildFacets.hasNext(); ) {
                            // recursive call to find the component
                            returnValue = itChildFacets.next().invokeOnComponent(context, clientId, callback);
                        }
                    }
                }
            }
        }
    } finally {
        // all components must call popComponentFromEl after visiting is finished
        popComponentFromEL(context);
        if (!isCachedFacesContext) {
            setCachedFacesContext(null);
        }
    }
    return returnValue;
}
Also used : Pattern(java.util.regex.Pattern) AbortProcessingException(jakarta.faces.event.AbortProcessingException) FacesException(jakarta.faces.FacesException) IOException(java.io.IOException) InvocationTargetException(java.lang.reflect.InvocationTargetException) FacesException(jakarta.faces.FacesException) VisitHint(jakarta.faces.component.visit.VisitHint)

Example 3 with FacesException

use of jakarta.faces.FacesException in project myfaces by apache.

the class ErrorPageWriter method handle.

public static void handle(FacesContext facesContext, Collection<UIComponent> components, Throwable... exs) throws FacesException {
    for (Throwable ex : exs) {
        prepareExceptionStack(ex);
    }
    if (!facesContext.getExternalContext().isResponseCommitted()) {
        facesContext.getExternalContext().responseReset();
    }
    int responseStatus = -1;
    for (Throwable ex : exs) {
        if (ex instanceof ViewNotFoundException) {
            responseStatus = HttpServletResponse.SC_NOT_FOUND;
            break;
        } else {
            responseStatus = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        }
    }
    if (responseStatus != -1) {
        facesContext.getExternalContext().setResponseStatus(responseStatus);
    }
    // normal request --> html error page
    facesContext.getExternalContext().setResponseContentType("text/html");
    facesContext.getExternalContext().setResponseCharacterEncoding("UTF-8");
    try {
        // We need the real one, because the one returned from FacesContext.getResponseWriter()
        // is configured with the encoding of the view.
        Writer writer = facesContext.getExternalContext().getResponseOutputWriter();
        debugHtml(writer, facesContext, facesContext.getViewRoot(), components, exs);
    } catch (IOException ioe) {
        throw new FacesException("Could not write the error page", ioe);
    }
    // mark the response as complete
    facesContext.responseComplete();
}
Also used : IOException(java.io.IOException) ViewNotFoundException(org.apache.myfaces.lifecycle.ViewNotFoundException) PrintWriter(java.io.PrintWriter) Writer(java.io.Writer) StringWriter(java.io.StringWriter) FacesException(jakarta.faces.FacesException)

Example 4 with FacesException

use of jakarta.faces.FacesException in project myfaces by apache.

the class RendererUtils method findUISelectManyConverter.

/**
 * Find proper Converter for the entries in the associated Collection or array of
 * the given UISelectMany as specified in API Doc of UISelectMany.
 * If considerValueType is true, the valueType attribute will be used
 * in addition to the standard algorithm to get a valid converter.
 *
 * @return the Converter or null if no Converter specified or needed
 * @throws FacesException if the Converter could not be created
 */
public static Converter findUISelectManyConverter(FacesContext facesContext, UISelectMany component, boolean considerValueType) {
    // If the component has an attached Converter, use it.
    Converter converter = component.getConverter();
    if (converter != null) {
        return converter;
    }
    if (considerValueType) {
        // try to get a converter from the valueType attribute
        converter = SharedRendererUtils.getValueTypeConverter(facesContext, component);
        if (converter != null) {
            return converter;
        }
    }
    // Try to find out by value expression
    ValueExpression ve = component.getValueExpression("value");
    if (ve == null) {
        return null;
    }
    // Try to get the type from the actual value or,
    // if value == null, obtain the type from the ValueExpression
    Class<?> valueType = null;
    Object value = ve.getValue(facesContext.getELContext());
    valueType = (value != null) ? value.getClass() : ve.getType(facesContext.getELContext());
    if (valueType == null) {
        return null;
    }
    // managed bean properties of type Object that resolve to null at this point
    if (Collection.class.isAssignableFrom(valueType) || Object.class.equals(valueType)) {
        // try to get the by-type-converter from the type of the SelectItems
        return SharedRendererUtils.getSelectItemsValueConverter(new SelectItemsIterator(component, facesContext), facesContext);
    }
    if (!valueType.isArray()) {
        throw new IllegalArgumentException("ValueExpression for UISelectMany : " + ComponentUtils.getPathToComponent(component) + " must be of type Collection or Array");
    }
    Class<?> arrayComponentType = valueType.getComponentType();
    if (String.class.equals(arrayComponentType)) {
        // No converter needed for String type
        return null;
    }
    if (Object.class.equals(arrayComponentType)) {
        // try to get the by-type-converter from the type of the SelectItems
        return SharedRendererUtils.getSelectItemsValueConverter(new SelectItemsIterator(component, facesContext), facesContext);
    }
    try {
        return facesContext.getApplication().createConverter(arrayComponentType);
    } catch (FacesException e) {
        log.log(Level.SEVERE, "No Converter for type " + arrayComponentType.getName() + " found", e);
        return null;
    }
}
Also used : ValueExpression(jakarta.el.ValueExpression) Converter(jakarta.faces.convert.Converter) Collection(java.util.Collection) SelectItemsIterator(org.apache.myfaces.core.api.shared.SelectItemsIterator) FacesException(jakarta.faces.FacesException)

Example 5 with FacesException

use of jakarta.faces.FacesException in project myfaces by apache.

the class RenderResponseExecutor method execute.

@Override
public boolean execute(FacesContext facesContext) {
    Application application = facesContext.getApplication();
    ViewHandler viewHandler = application.getViewHandler();
    UIViewRoot root;
    UIViewRoot previousRoot;
    String viewId;
    String newViewId;
    boolean isNotSameRoot;
    int loops = 0;
    int maxLoops = 15;
    if (facesContext.getViewRoot() == null) {
        throw new ViewNotFoundException("A view is required to execute " + facesContext.getCurrentPhaseId());
    }
    forceSessionCreation(facesContext);
    try {
        // do-while, because the view might change in PreRenderViewEvent-listeners
        do {
            root = facesContext.getViewRoot();
            previousRoot = root;
            viewId = root.getViewId();
            ViewDeclarationLanguage vdl = viewHandler.getViewDeclarationLanguage(facesContext, viewId);
            if (vdl != null) {
                vdl.buildView(facesContext, root);
            }
            // publish a PreRenderViewEvent: note that the event listeners
            // of this event can change the view, so we have to perform the algorithm
            // until the viewId does not change when publishing this event.
            application.publishEvent(facesContext, PreRenderViewEvent.class, root);
            // was the response marked as complete by an event listener?
            if (facesContext.getResponseComplete()) {
                return false;
            }
            root = facesContext.getViewRoot();
            newViewId = root.getViewId();
            isNotSameRoot = !((newViewId == null ? newViewId == viewId : newViewId.equals(viewId)) && previousRoot.equals(root));
            loops++;
        } while ((newViewId == null && viewId != null) || (newViewId != null && (!newViewId.equals(viewId) || isNotSameRoot)) && loops < maxLoops);
        if (loops == maxLoops) {
            // PreRenderView reach maxLoops - probably a infinitive recursion:
            Level level = facesContext.isProjectStage(ProjectStage.Production) ? Level.FINE : Level.WARNING;
            if (log.isLoggable(level)) {
                log.log(level, "Cicle over buildView-PreRenderViewEvent on RENDER_RESPONSE phase " + "reaches maximal limit, please check listeners for infinite recursion.");
            }
        }
        viewHandler.renderView(facesContext, root);
        application.publishEvent(facesContext, PostRenderViewEvent.class, root);
        // log all unhandled FacesMessages, don't swallow them
        // perf: org.apache.myfaces.context.servlet.FacesContextImpl.getMessageList() creates
        // new Collections.unmodifiableList with every invocation->  call it only once
        // and messageList is RandomAccess -> use index based loop
        List<FacesMessage> messageList = facesContext.getMessageList();
        if (!messageList.isEmpty()) {
            StringBuilder builder = new StringBuilder();
            boolean shouldLog = false;
            for (int i = 0, size = messageList.size(); i < size; i++) {
                FacesMessage message = messageList.get(i);
                if (!message.isRendered()) {
                    builder.append("\n- ");
                    builder.append(message.getDetail());
                    shouldLog = true;
                }
            }
            if (shouldLog) {
                log.log(Level.WARNING, "There are some unhandled FacesMessages, " + "this means not every FacesMessage had a chance to be rendered.\n" + "These unhandled FacesMessages are: " + builder.toString());
            }
        }
    } catch (IOException e) {
        throw new FacesException(e.getMessage(), e);
    }
    return false;
}
Also used : ViewHandler(jakarta.faces.application.ViewHandler) ViewDeclarationLanguage(jakarta.faces.view.ViewDeclarationLanguage) IOException(java.io.IOException) FacesException(jakarta.faces.FacesException) Level(java.util.logging.Level) Application(jakarta.faces.application.Application) UIViewRoot(jakarta.faces.component.UIViewRoot) FacesMessage(jakarta.faces.application.FacesMessage)

Aggregations

FacesException (jakarta.faces.FacesException)246 IOException (java.io.IOException)71 UIViewRoot (jakarta.faces.component.UIViewRoot)37 ExternalContext (jakarta.faces.context.ExternalContext)37 FacesContext (jakarta.faces.context.FacesContext)33 UIComponent (jakarta.faces.component.UIComponent)28 InvocationTargetException (java.lang.reflect.InvocationTargetException)22 PrivilegedActionException (java.security.PrivilegedActionException)19 ELException (jakarta.el.ELException)18 ArrayList (java.util.ArrayList)18 ValueExpression (jakarta.el.ValueExpression)17 ViewHandler (jakarta.faces.application.ViewHandler)16 Converter (jakarta.faces.convert.Converter)16 AbortProcessingException (jakarta.faces.event.AbortProcessingException)16 HashMap (java.util.HashMap)16 Map (java.util.Map)16 Test (org.junit.Test)16 Application (jakarta.faces.application.Application)14 ViewDeclarationLanguage (jakarta.faces.view.ViewDeclarationLanguage)14 ExceptionQueuedEvent (jakarta.faces.event.ExceptionQueuedEvent)12