All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.vaadin.ui.declarative.converters.DesignEnumConverter Maven / Gradle / Ivy

There is a newer version: 8.27.3
Show newest version
/*
 * Copyright (C) 2000-2024 Vaadin Ltd
 *
 * This program is available under Vaadin Commercial License and Service Terms.
 *
 * See  for the full
 * license.
 */
package com.vaadin.ui.declarative.converters;

import java.util.Locale;

import com.vaadin.data.Converter;
import com.vaadin.data.Result;
import com.vaadin.data.ValueContext;
import com.vaadin.ui.declarative.DesignAttributeHandler;

/**
 * An converter for Enum to/from String for {@link DesignAttributeHandler} to
 * use internally.
 *
 * @since 7.4
 * @author Vaadin Ltd
 */
@SuppressWarnings("rawtypes")
public class DesignEnumConverter
        implements Converter {

    private final Class type;

    /**
     * Creates a converter for the given enum type.
     *
     * @param type
     *            the enum type to convert to/from
     */
    public DesignEnumConverter(Class type) {
        this.type = type;
    }

    @SuppressWarnings("unchecked")
    @Override
    public Result convertToModel(String value, ValueContext context) {
        if (value == null || value.trim().isEmpty()) {
            return Result.ok(null);
        }
        try {
            T result = (T) Enum.valueOf(type, value.toUpperCase(Locale.ROOT));
            return Result.ok(result);
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Override
    public String convertToPresentation(T value, ValueContext context) {
        if (value == null) {
            return null;
        }

        return value.name().toLowerCase(Locale.ROOT);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy