Algunas veces es agradable ver un segmento de código sólo por si mismo, sin que realmente este dedicado a resolver ningún problema específico… simplemente se percibe una sensación agradable al verlo. Este es un ejemplito de ello:

@UiParamConverter
public class VersionConverter implements GenericConverter {

    @Target({ ElementType.PARAMETER, ElementType.FIELD })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface VersionCode {

    }

    @Target({ ElementType.PARAMETER, ElementType.FIELD })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface VersionId {

    }

    @Autowired(required = false)
    private VersionService versionService;

    private static final Logger log = LoggerFactory.getLogger(VersionConverter.class);

    @Override
    public Set getConvertibleTypes() {
        return Collections.singleton(new ConvertiblePair(String.class, PublishingVersion.class));
    }

    @Override
    public Object convert(final Object source, final TypeDescriptor sourceType, final TypeDescriptor targetType) {
        if ((!(source instanceof String)) || StringUtils.isBlank((String) source)) {
            return null;
        }

        final String fieldValue = (String) source;
        String fieldType = null;

        PublishingVersion version = null;

        try {
            // see what Version type annotation is on the TargetType
            if (targetType.hasAnnotation(VersionId.class)) {
                fieldType = new String("versionId");
                version = versionService.getVersionById(fieldValue);
            } else if (targetType.hasAnnotation(VersionCode.class)) {
                fieldType = new String("code");
                version = versionService.getVersionByCode(fieldValue);
            } else {
                // Default - assume we're dealing with a code
                fieldType = new String("code");
                version = versionService.getVersionByCode(fieldValue);
            }
        } catch (final Exception e) {
            log.warn(String.format("Error fetching version using field '%s' and value '%s'.", fieldType, fieldValue), e);
        }

        if (version == null) {
            log.info(String.format("Could not find version using field '%s' and value '%s'.", fieldType, fieldValue));
        }
        return version;
    }
}

Cheers,
Goose

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

© 2019 Goose Workshop Suffusion theme by Sayontan Sinha