Search in sources :

Example 1 with FacesConverter

use of jakarta.faces.convert.FacesConverter in project myfaces by apache.

the class ApplicationImpl method internalCreateConverter.

@SuppressWarnings("unchecked")
private Converter<?> internalCreateConverter(final Class<?> targetClass) {
    // Locate a Converter registered for the target class itself.
    Object converterClassOrClassName = _converterTargetClassToConverterClassMap.get(targetClass);
    // (save 3 additional lookups over a concurrent map per request).
    if (converterClassOrClassName == null && !String.class.equals(targetClass)) {
        final Class<?>[] interfaces = targetClass.getInterfaces();
        if (interfaces != null) {
            for (int i = 0, len = interfaces.length; i < len; i++) {
                // search all superinterfaces for a matching converter,
                // create it
                final Converter<?> converter = internalCreateConverter(interfaces[i]);
                if (converter != null) {
                    return converter;
                }
            }
        }
    }
    // here as recursive call with java.lang.Enum will not work
    if (converterClassOrClassName == null && targetClass.isEnum()) {
        converterClassOrClassName = _converterTargetClassToConverterClassMap.get(Enum.class);
    }
    if (converterClassOrClassName != null) {
        try {
            Class<? extends Converter> converterClass = null;
            if (converterClassOrClassName instanceof Class<?>) {
                converterClass = (Class<? extends Converter>) converterClassOrClassName;
            } else if (converterClassOrClassName instanceof String) {
                converterClass = ClassUtils.simpleClassForName((String) converterClassOrClassName);
                _converterTargetClassToConverterClassMap.put(targetClass, converterClass);
            } else {
                // object stored in the map for this id is an invalid type.  remove it and return null
                _converterTargetClassToConverterClassMap.remove(targetClass);
            }
            if (!_cdiManagedConverterMap.containsKey(converterClass)) {
                FacesConverter annotation = converterClass.getAnnotation(FacesConverter.class);
                if (annotation != null && annotation.managed()) {
                    _cdiManagedConverterMap.put(converterClass, true);
                } else {
                    _cdiManagedConverterMap.put(converterClass, false);
                }
            }
            Converter<?> converter = null;
            if (Boolean.TRUE.equals(_cdiManagedConverterMap.get(converterClass))) {
                converter = new FacesConverterCDIWrapper(converterClass, targetClass, null);
                setConverterProperties(converterClass, ((FacesWrapper<Converter>) converter).getWrapped());
            } else {
                // check cached constructor information
                if (!_noArgConstructorConverterClasses.contains(converterClass)) {
                    // or has never been processed before
                    try {
                        // look for a constructor that takes a single Class object
                        // See JSF 1.2 javadoc for Converter
                        Constructor<? extends Converter> constructor = converterClass.getConstructor(new Class[] { Class.class });
                        converter = constructor.newInstance(new Object[] { targetClass });
                    } catch (Exception e) {
                        // the constructor does not exist
                        // add the class to the no-arg constructor classes cache
                        _noArgConstructorConverterClasses.add(converterClass);
                        // use no-arg constructor
                        converter = createConverterInstance(converterClass);
                    }
                } else {
                    // use no-arg constructor
                    converter = createConverterInstance(converterClass);
                }
                setConverterProperties(converterClass, converter);
            }
            return converter;
        } catch (Exception e) {
            log.log(Level.SEVERE, "Could not instantiate converter " + converterClassOrClassName.toString(), e);
            throw new FacesException("Could not instantiate converter: " + converterClassOrClassName.toString(), e);
        }
    }
    // locate converter for primitive types
    if (targetClass == Long.TYPE) {
        return internalCreateConverter(Long.class);
    } else if (targetClass == Boolean.TYPE) {
        return internalCreateConverter(Boolean.class);
    } else if (targetClass == Double.TYPE) {
        return internalCreateConverter(Double.class);
    } else if (targetClass == Byte.TYPE) {
        return internalCreateConverter(Byte.class);
    } else if (targetClass == Short.TYPE) {
        return internalCreateConverter(Short.class);
    } else if (targetClass == Integer.TYPE) {
        return internalCreateConverter(Integer.class);
    } else if (targetClass == Float.TYPE) {
        return internalCreateConverter(Float.class);
    } else if (targetClass == Character.TYPE) {
        return internalCreateConverter(Character.class);
    }
    // Locate a Converter registered for the superclass (if any) of the
    // target class,
    // recursively working up the inheritance hierarchy.
    Class<?> superClazz = targetClass.getSuperclass();
    return superClazz != null ? internalCreateConverter(superClazz) : null;
}
Also used : FacesConverter(jakarta.faces.convert.FacesConverter) FacesConverterCDIWrapper(org.apache.myfaces.cdi.wrapper.FacesConverterCDIWrapper) MissingResourceException(java.util.MissingResourceException) NamingException(javax.naming.NamingException) ELException(jakarta.el.ELException) FacesException(jakarta.faces.FacesException) FacesException(jakarta.faces.FacesException) FacesConverter(jakarta.faces.convert.FacesConverter) Converter(jakarta.faces.convert.Converter) DateTimeConverter(jakarta.faces.convert.DateTimeConverter)

Example 2 with FacesConverter

use of jakarta.faces.convert.FacesConverter in project myfaces by apache.

the class ApplicationImpl method createConverter.

/**
 * Return an instance of the converter class that has been registered under the specified id.
 * <p>
 * Converters are registered via faces-config.xml files, and can also be registered via the addConverter(String id,
 * Class converterClass) method on this class. Here the the appropriate Class definition is found, then an instance
 * is created and returned.
 * <p>
 * A converter registered via a config file can have any number of nested attribute or property tags. The JSF
 * specification is very vague about what effect these nested tags have. This method ignores nested attribute
 * definitions, but for each nested property tag the corresponding setter is invoked on the new Converter instance
 * passing the property's defaultValuer. Basic typeconversion is done so the target properties on the Converter
 * instance can be String, int, boolean, etc. Note that:
 * <ol>
 * <li>the Sun Mojarra JSF implemenation ignores nested property tags completely, so this behaviour cannot be
 * relied on across implementations.
 * <li>there is no equivalent functionality for converter classes registered via the Application.addConverter api
 * method.
 * </ol>
 * <p>
 * Note that this method is most commonly called from the standard f:attribute tag. As an alternative, most
 * components provide a "converter" attribute which uses an EL expression to create a Converter instance, in which
 * case this method is not invoked at all. The converter attribute allows the returned Converter instance to be
 * configured via normal dependency-injection, and is generally a better choice than using this method.
 */
@Override
public final Converter createConverter(final String converterId) {
    Assert.notEmpty(converterId, "converterId");
    final Class<? extends Converter> converterClass = getObjectFromClassMap(converterId, _converterIdToClassMap);
    if (converterClass == null) {
        throw new FacesException("Could not find any registered converter-class by converterId : " + converterId);
    }
    try {
        if (!_cdiManagedConverterMap.containsKey(converterClass)) {
            FacesConverter annotation = converterClass.getAnnotation(FacesConverter.class);
            if (annotation != null && annotation.managed()) {
                _cdiManagedConverterMap.put(converterClass, true);
            } else {
                _cdiManagedConverterMap.put(converterClass, false);
            }
        }
        boolean managed = _cdiManagedConverterMap.get(converterClass);
        Converter converter = null;
        if (managed) {
            converter = new FacesConverterCDIWrapper(converterClass, null, converterId);
            setConverterProperties(converterClass, ((FacesWrapper<Converter>) converter).getWrapped());
            _handleAttachedResourceDependencyAnnotations(getFacesContext(), ((FacesWrapper<Converter>) converter).getWrapped());
        } else {
            converter = createConverterInstance(converterClass);
            setConverterProperties(converterClass, converter);
            _handleAttachedResourceDependencyAnnotations(getFacesContext(), converter);
        }
        return converter;
    } catch (Exception e) {
        log.log(Level.SEVERE, "Could not instantiate converter " + converterClass, e);
        throw new FacesException("Could not instantiate converter: " + converterClass, e);
    }
}
Also used : FacesConverter(jakarta.faces.convert.FacesConverter) FacesConverterCDIWrapper(org.apache.myfaces.cdi.wrapper.FacesConverterCDIWrapper) FacesConverter(jakarta.faces.convert.FacesConverter) Converter(jakarta.faces.convert.Converter) DateTimeConverter(jakarta.faces.convert.DateTimeConverter) FacesException(jakarta.faces.FacesException) MissingResourceException(java.util.MissingResourceException) NamingException(javax.naming.NamingException) ELException(jakarta.el.ELException) FacesException(jakarta.faces.FacesException)

Example 3 with FacesConverter

use of jakarta.faces.convert.FacesConverter in project myfaces by apache.

the class AnnotationConfigurator method createFacesConfig.

/**
 * TODO: Implement strategy pattern over this method.
 *
 * @param map
 * @return
 */
protected FacesConfigImpl createFacesConfig(Map<Class<? extends Annotation>, Set<Class<?>>> map) {
    FacesConfigImpl facesConfig = new FacesConfigImpl();
    Set<Class<?>> classes = map.get(FacesComponent.class);
    if (classes != null && !classes.isEmpty()) {
        for (Class<?> clazz : classes) {
            FacesComponent comp = (FacesComponent) clazz.getAnnotation(FacesComponent.class);
            if (comp != null) {
                if (log.isLoggable(Level.FINEST)) {
                    log.finest("addComponent(" + comp.value() + ',' + clazz.getName() + ')');
                }
                String value = comp.value();
                if (StringUtils.isEmpty(value)) {
                    String simpleName = clazz.getSimpleName();
                    value = Character.toLowerCase(simpleName.charAt(0)) + simpleName.substring(1);
                }
                facesConfig.addComponent(new ComponentImpl(value, clazz.getName()));
                if (comp.createTag()) {
                    String tagName = comp.tagName();
                    if (StringUtils.isEmpty(tagName)) {
                        tagName = clazz.getSimpleName();
                        tagName = Character.toLowerCase(tagName.charAt(0)) + tagName.substring(1);
                    }
                    facesConfig.addComponentTagDeclaration(value, new ComponentTagDeclarationImpl(value, comp.namespace(), tagName));
                }
            }
        }
    }
    classes = map.get(FacesConverter.class);
    if (classes != null && !classes.isEmpty()) {
        for (Class<?> clazz : classes) {
            FacesConverter conv = (FacesConverter) clazz.getAnnotation(FacesConverter.class);
            if (conv != null) {
                if (log.isLoggable(Level.FINEST)) {
                    log.finest("addConverter(" + conv.value() + ',' + clazz.getName() + ')');
                }
                // If there is a previous entry on Application Configuration Resources,
                // the entry there takes precedence
                boolean hasForClass = !Object.class.equals(conv.forClass());
                boolean hasValue = conv.value().length() > 0;
                if (hasForClass || hasValue) {
                    ConverterImpl converter = new ConverterImpl();
                    if (hasForClass) {
                        converter.setForClass(conv.forClass().getName());
                    }
                    if (hasValue) {
                        converter.setConverterId(conv.value());
                    }
                    converter.setConverterClass(clazz.getName());
                    facesConfig.addConverter(converter);
                } else {
                    throw new FacesException("@FacesConverter must have value, forClass or both. Check annotation " + "@FacesConverter on class: " + clazz.getName());
                }
            }
        }
    }
    classes = map.get(FacesValidator.class);
    if (classes != null && !classes.isEmpty()) {
        for (Class<?> clazz : classes) {
            FacesValidator val = (FacesValidator) clazz.getAnnotation(FacesValidator.class);
            if (val != null) {
                if (log.isLoggable(Level.FINEST)) {
                    log.finest("addValidator(" + val.value() + ',' + clazz.getName() + ')');
                }
                String value = val.value();
                if (value == null || value.isEmpty()) {
                    String simpleName = clazz.getSimpleName();
                    value = Character.toLowerCase(simpleName.charAt(0)) + simpleName.substring(1);
                }
                facesConfig.addValidator(value, clazz.getName());
                if (val.isDefault()) {
                    ApplicationImpl app = null;
                    if (facesConfig.getApplications().isEmpty()) {
                        app = new ApplicationImpl();
                    } else {
                        app = (ApplicationImpl) facesConfig.getApplications().get(0);
                    }
                    app.addDefaultValidatorId(value);
                }
            }
        }
    }
    classes = map.get(FacesRenderer.class);
    if (classes != null && !classes.isEmpty()) {
        for (Class<?> clazz : classes) {
            FacesRenderer rend = (FacesRenderer) clazz.getAnnotation(FacesRenderer.class);
            if (rend != null) {
                String renderKitId = rend.renderKitId();
                if (renderKitId == null) {
                    renderKitId = RenderKitFactory.HTML_BASIC_RENDER_KIT;
                }
                if (log.isLoggable(Level.FINEST)) {
                    log.finest("addRenderer(" + renderKitId + ", " + rend.componentFamily() + ", " + rend.rendererType() + ", " + clazz.getName() + ')');
                }
                org.apache.myfaces.config.impl.element.RenderKitImpl renderKit = (org.apache.myfaces.config.impl.element.RenderKitImpl) facesConfig.getRenderKit(renderKitId);
                if (renderKit == null) {
                    renderKit = new org.apache.myfaces.config.impl.element.RenderKitImpl();
                    renderKit.setId(renderKitId);
                    facesConfig.addRenderKit(renderKit);
                }
                org.apache.myfaces.config.impl.element.RendererImpl renderer = new org.apache.myfaces.config.impl.element.RendererImpl();
                renderer.setComponentFamily(rend.componentFamily());
                renderer.setRendererClass(clazz.getName());
                renderer.setRendererType(rend.rendererType());
                renderKit.addRenderer(renderer);
            }
        }
    }
    classes = map.get(NamedEvent.class);
    if (classes != null && !classes.isEmpty()) {
        handleNamedEvent(facesConfig, classes);
    }
    classes = map.get(FacesBehavior.class);
    if (classes != null && !classes.isEmpty()) {
        handleFacesBehavior(facesConfig, classes);
    }
    classes = map.get(FacesBehaviorRenderer.class);
    if (classes != null && !classes.isEmpty()) {
        handleFacesBehaviorRenderer(facesConfig, classes);
    }
    classes = map.get(FaceletsResourceResolver.class);
    if (classes != null && !classes.isEmpty()) {
        handleFaceletsResourceResolver(facesConfig, classes);
    }
    return facesConfig;
}
Also used : FacesBehaviorRenderer(jakarta.faces.render.FacesBehaviorRenderer) ApplicationImpl(org.apache.myfaces.config.impl.element.ApplicationImpl) ConverterImpl(org.apache.myfaces.config.impl.element.ConverterImpl) ComponentImpl(org.apache.myfaces.config.impl.element.ComponentImpl) ComponentTagDeclarationImpl(org.apache.myfaces.config.impl.element.ComponentTagDeclarationImpl) FaceletsResourceResolver(jakarta.faces.view.facelets.FaceletsResourceResolver) FacesConfigImpl(org.apache.myfaces.config.impl.element.FacesConfigImpl) FacesValidator(jakarta.faces.validator.FacesValidator) FacesRenderer(jakarta.faces.render.FacesRenderer) FacesConverter(jakarta.faces.convert.FacesConverter) NamedEvent(jakarta.faces.event.NamedEvent) FacesException(jakarta.faces.FacesException) FacesComponent(jakarta.faces.component.FacesComponent) FacesBehavior(jakarta.faces.component.behavior.FacesBehavior)

Example 4 with FacesConverter

use of jakarta.faces.convert.FacesConverter in project mojarra by eclipse-ee4j.

the class ConverterConfigHandler method collect.

/**
 * @see com.sun.faces.application.annotation.ConfigAnnotationHandler#collect(Class, java.lang.annotation.Annotation)
 */
@Override
public void collect(Class<?> target, Annotation annotation) {
    if (converters == null) {
        converters = new HashMap<>();
    }
    Object key;
    FacesConverter converterAnnotation = (FacesConverter) annotation;
    if (converterAnnotation.value().length() > 0 && converterAnnotation.forClass() != null && converterAnnotation.forClass() != Object.class) {
        if (LOGGER.isLoggable(Level.WARNING)) {
            LOGGER.log(Level.WARNING, "@FacesConverter is using both value and forClass, only value will be applied.");
        }
    }
    if (0 == converterAnnotation.value().length()) {
        key = converterAnnotation.forClass();
    } else {
        key = converterAnnotation.value();
    }
    converters.put(key, target.getName());
}
Also used : FacesConverter(jakarta.faces.convert.FacesConverter)

Aggregations

FacesConverter (jakarta.faces.convert.FacesConverter)4 FacesException (jakarta.faces.FacesException)3 ELException (jakarta.el.ELException)2 Converter (jakarta.faces.convert.Converter)2 DateTimeConverter (jakarta.faces.convert.DateTimeConverter)2 MissingResourceException (java.util.MissingResourceException)2 NamingException (javax.naming.NamingException)2 FacesConverterCDIWrapper (org.apache.myfaces.cdi.wrapper.FacesConverterCDIWrapper)2 FacesComponent (jakarta.faces.component.FacesComponent)1 FacesBehavior (jakarta.faces.component.behavior.FacesBehavior)1 NamedEvent (jakarta.faces.event.NamedEvent)1 FacesBehaviorRenderer (jakarta.faces.render.FacesBehaviorRenderer)1 FacesRenderer (jakarta.faces.render.FacesRenderer)1 FacesValidator (jakarta.faces.validator.FacesValidator)1 FaceletsResourceResolver (jakarta.faces.view.facelets.FaceletsResourceResolver)1 ApplicationImpl (org.apache.myfaces.config.impl.element.ApplicationImpl)1 ComponentImpl (org.apache.myfaces.config.impl.element.ComponentImpl)1 ComponentTagDeclarationImpl (org.apache.myfaces.config.impl.element.ComponentTagDeclarationImpl)1 ConverterImpl (org.apache.myfaces.config.impl.element.ConverterImpl)1 FacesConfigImpl (org.apache.myfaces.config.impl.element.FacesConfigImpl)1