Search in sources :

Example 6 with EnumClass

use of com.haulmont.chile.core.datatypes.impl.EnumClass in project cuba by cuba-platform.

the class AppPropertiesLocator method setDataType.

private void setDataType(Method method, AppPropertyEntity entity) {
    Class<?> returnType = method.getReturnType();
    if (returnType.isPrimitive()) {
        if (returnType == boolean.class)
            entity.setDataTypeName(datatypes.getIdByJavaClass(Boolean.class));
        if (returnType == int.class)
            entity.setDataTypeName(datatypes.getIdByJavaClass(Integer.class));
        if (returnType == long.class)
            entity.setDataTypeName(datatypes.getIdByJavaClass(Long.class));
        if (returnType == double.class || returnType == float.class)
            entity.setDataTypeName(datatypes.getIdByJavaClass(Double.class));
    } else if (returnType.isEnum()) {
        entity.setDataTypeName("enum");
        EnumStore enumStoreAnn = method.getAnnotation(EnumStore.class);
        if (enumStoreAnn != null && enumStoreAnn.value() == EnumStoreMode.ID) {
            // noinspection unchecked
            Class<EnumClass> enumeration = (Class<EnumClass>) returnType;
            entity.setEnumValues(Arrays.asList(enumeration.getEnumConstants()).stream().map(ec -> String.valueOf(ec.getId())).collect(Collectors.joining(",")));
        } else {
            entity.setEnumValues(Arrays.asList(returnType.getEnumConstants()).stream().map(Object::toString).collect(Collectors.joining(",")));
        }
    } else {
        Datatype<?> datatype = datatypes.get(returnType);
        if (datatype != null)
            entity.setDataTypeName(datatypes.getId(datatype));
        else
            entity.setDataTypeName(datatypes.getIdByJavaClass(String.class));
    }
    String dataTypeName = entity.getDataTypeName();
    if (!dataTypeName.equals("enum")) {
        Datatype datatype = Datatypes.get(dataTypeName);
        String v = null;
        try {
            v = entity.getDefaultValue();
            datatype.parse(v);
            v = entity.getCurrentValue();
            datatype.parse(v);
        } catch (ParseException e) {
            log.debug("Cannot parse '{}' with {} datatype, using StringDatatype for property {}", v, datatype, entity.getName());
            entity.setDataTypeName(datatypes.getIdByJavaClass(String.class));
        }
    }
}
Also used : StringUtils(org.apache.commons.lang.StringUtils) java.util(java.util) ReflectionHelper(com.haulmont.bali.util.ReflectionHelper) LoggerFactory(org.slf4j.LoggerFactory) ClassMetadata(org.springframework.core.type.ClassMetadata) DatatypeRegistry(com.haulmont.chile.core.datatypes.DatatypeRegistry) com.haulmont.cuba.core.global(com.haulmont.cuba.core.global) PathMatchingResourcePatternResolver(org.springframework.core.io.support.PathMatchingResourcePatternResolver) Inject(javax.inject.Inject) Datatype(com.haulmont.chile.core.datatypes.Datatype) MetadataReader(org.springframework.core.type.classreading.MetadataReader) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass) ParseException(java.text.ParseException) Method(java.lang.reflect.Method) Nullable(javax.annotation.Nullable) Resource(org.springframework.core.io.Resource) com.haulmont.cuba.core.config.type(com.haulmont.cuba.core.config.type) Logger(org.slf4j.Logger) Datatypes(com.haulmont.chile.core.datatypes.Datatypes) CachingMetadataReaderFactory(org.springframework.core.type.classreading.CachingMetadataReaderFactory) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) InvocationTargetException(java.lang.reflect.InvocationTargetException) Component(org.springframework.stereotype.Component) MetadataReaderFactory(org.springframework.core.type.classreading.MetadataReaderFactory) com.haulmont.cuba.core.config.defaults(com.haulmont.cuba.core.config.defaults) AppContext(com.haulmont.cuba.core.sys.AppContext) ResourcePatternResolver(org.springframework.core.io.support.ResourcePatternResolver) Entity(com.haulmont.cuba.core.entity.Entity) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass) ParseException(java.text.ParseException) Datatype(com.haulmont.chile.core.datatypes.Datatype)

Example 7 with EnumClass

use of com.haulmont.chile.core.datatypes.impl.EnumClass in project cuba by cuba-platform.

the class ConfigUtil method getDefaultValue.

/**
 * Get the default value of a configuration interface method. If a
 * {@link Default} annotation is present then that string is converted
 * to the appropriate type using the {@link TypeFactory} class.
 * Otherwise, for the type Foo, this searches for a FooDefault
 * annotation. If such an annotation is present then its value is
 * returned.
 *
 * @param configInterface The configuration interface.
 * @param method          The method.
 * @return The default value, or null.
 */
public static String getDefaultValue(Class<?> configInterface, Method method) {
    // TODO: returnType.cast()?
    try {
        Default defaultValue = method.getAnnotation(Default.class);
        if (defaultValue != null) {
            return defaultValue.value();
        } else {
            Class<?> type = method.getReturnType();
            if (EnumClass.class.isAssignableFrom(type)) {
                @SuppressWarnings("unchecked") Class<EnumClass> enumeration = (Class<EnumClass>) type;
                EnumStore mode = getAnnotation(configInterface, method, EnumStore.class, true);
                if (mode != null && EnumStoreMode.ID == mode.value()) {
                    Class<?> idType = getEnumIdType(enumeration);
                    String name = "Default" + StringUtils.capitalize(ClassUtils.getShortClassName(idType));
                    Object value = getAnnotationValue(method, name);
                    if (value != null) {
                        Method fromId = enumeration.getDeclaredMethod("fromId", idType);
                        TypeStringify stringConverter = TypeStringify.getInstance(configInterface, method);
                        return stringConverter.stringify(fromId.invoke(null, value));
                    }
                    return NO_DEFAULT;
                }
            }
            String name = "Default" + StringUtils.capitalize(ClassUtils.getShortClassName(type));
            Object value = getAnnotationValue(method, name);
            if (value != null) {
                TypeStringify stringConverter = TypeStringify.getInstance(configInterface, method);
                return stringConverter.stringify(value);
            }
        }
        return NO_DEFAULT;
    } catch (Exception ex) {
        throw new RuntimeException("Default value error", ex);
    }
}
Also used : Method(java.lang.reflect.Method) Default(com.haulmont.cuba.core.config.defaults.Default) TypeStringify(com.haulmont.cuba.core.config.type.TypeStringify) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass)

Example 8 with EnumClass

use of com.haulmont.chile.core.datatypes.impl.EnumClass in project cuba by cuba-platform.

the class TypeFactory method getInstance.

/**
 * Get a TypeFactory instance appropriate for the return type of the
 * specified configuration interface method.
 *
 * @param configInterface The configuration interface.
 * @param method          The method.
 * @return An appropriate TypeFactory.
 * @throws IllegalArgumentException If the type is not supported.
 */
public static TypeFactory getInstance(Class<?> configInterface, Method method) {
    Class<?> returnType = method.getReturnType();
    if (returnType.isPrimitive()) {
        returnType = ClassUtils.primitiveToWrapper(returnType);
    }
    Factory factory = ConfigUtil.getAnnotation(configInterface, method, Factory.class, true);
    if (factory != null) {
        try {
            if ("".equals(factory.method())) {
                return factory.factory().newInstance();
            } else {
                String methodName = factory.method();
                Method factoryMethod = returnType.getMethod(methodName, String.class);
                if (!isAcceptableMethod(returnType, factoryMethod)) {
                    throw new IllegalArgumentException("Invalid factory method: " + factoryMethod);
                }
                return new StaticTypeFactory(factoryMethod);
            }
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("Unable to instantiate an type factory", e);
        }
    } else {
        if (Entity.class.isAssignableFrom(returnType)) {
            return AppBeans.get(ENTITY_FACTORY_BEAN_NAME, TypeFactory.class);
        } else {
            if (EnumClass.class.isAssignableFrom(returnType)) {
                EnumStore mode = ConfigUtil.getAnnotation(configInterface, method, EnumStore.class, true);
                if (mode != null && EnumStoreMode.ID == mode.value()) {
                    @SuppressWarnings("unchecked") Class<EnumClass> enumeration = (Class<EnumClass>) returnType;
                    Class<?> idType = ConfigUtil.getEnumIdType(enumeration);
                    TypeFactory idFactory = getInferred(idType);
                    try {
                        Method fromIdMethod = returnType.getMethod("fromId", idType);
                        if (!isAcceptableMethod(returnType, fromIdMethod) || idFactory == null) {
                            throw new IllegalArgumentException("Cannot use method as factory method: " + method);
                        }
                        return new EnumClassFactory(idFactory, fromIdMethod);
                    } catch (NoSuchMethodException e) {
                        throw new IllegalArgumentException("fromId method is not found for " + enumeration.getName());
                    }
                }
            }
            TypeFactory factoryT = getInferred(returnType);
            if (factoryT == null) {
                throw new IllegalArgumentException("Unsupported return type for " + method);
            }
            return factoryT;
        }
    }
}
Also used : Method(java.lang.reflect.Method) EnumStore(com.haulmont.cuba.core.config.EnumStore) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass)

Example 9 with EnumClass

use of com.haulmont.chile.core.datatypes.impl.EnumClass in project cuba by cuba-platform.

the class TypeStringify method getInstance.

/**
 * Get a TypeStringify instance appropriate for the parameter type of the
 * specified configuration interface method.
 *
 * @param configInterface The configuration interface.
 * @param method          The method.
 * @return An appropriate TypeStringify.
 * @throws IllegalArgumentException If the type is not supported.
 */
public static TypeStringify getInstance(Class<?> configInterface, Method method) {
    Class<?> methodType = ConfigUtil.getMethodType(method);
    try {
        Stringify stringify = ConfigUtil.getAnnotation(configInterface, method, Stringify.class, true);
        if (stringify != null) {
            if ("".equals(stringify.method())) {
                return stringify.stringify().newInstance();
            } else {
                String methodName = stringify.method();
                return new MethodTypeStringify(methodType.getMethod(methodName));
            }
        } else {
            if ((method.getParameterTypes().length > 0)) {
                if (Entity.class.isAssignableFrom(method.getParameterTypes()[0])) {
                    return new EntityStringify();
                }
            }
            if (EnumClass.class.isAssignableFrom(methodType)) {
                EnumStore mode = ConfigUtil.getAnnotation(configInterface, method, EnumStore.class, true);
                if (mode != null && EnumStoreMode.ID == mode.value()) {
                    @SuppressWarnings("unchecked") Class<EnumClass> enumeration = (Class<EnumClass>) methodType;
                    TypeStringify idStringify = getInferred(ConfigUtil.getEnumIdType(enumeration));
                    return new EnumClassStringify(idStringify);
                }
            }
            return getInferred(methodType);
        }
    } catch (NoSuchMethodException | InstantiationException | IllegalAccessException | RuntimeException e) {
        throw new RuntimeException("Type stringify error", e);
    }
}
Also used : EnumStore(com.haulmont.cuba.core.config.EnumStore) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass)

Example 10 with EnumClass

use of com.haulmont.chile.core.datatypes.impl.EnumClass in project cuba by cuba-platform.

the class DataServiceQueryBuilder method getQuery.

public Query getQuery(EntityManager em) {
    Query query = em.createQuery(queryString);
    // we have to replace parameter names in macros because for {@link com.haulmont.cuba.core.sys.querymacro.TimeBetweenQueryMacroHandler}
    // we need to replace a parameter with number of days with its value before macros is expanded to JPQL expression
    replaceParamsInMacros(query);
    applyConstraints(query);
    QueryParser parser = QueryTransformerFactory.createParser(queryString);
    Set<String> paramNames = parser.getParamNames();
    for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
        String name = entry.getKey();
        if (paramNames.contains(name)) {
            Object value = entry.getValue();
            boolean convert = noConversionParams == null || Arrays.stream(noConversionParams).noneMatch(s -> s.equals(name));
            if (convert) {
                if (value instanceof Entity) {
                    value = ((Entity) value).getId();
                } else if (value instanceof EnumClass) {
                    value = ((EnumClass) value).getId();
                } else if (value instanceof Collection) {
                    List<Object> list = new ArrayList<>(((Collection) value).size());
                    for (Object item : (Collection) value) {
                        if (item instanceof Entity)
                            list.add(((Entity) item).getId());
                        else if (item instanceof EnumClass)
                            list.add(((EnumClass) item).getId());
                        else
                            list.add(item);
                    }
                    value = list;
                }
            }
            if (value instanceof TemporalValue) {
                TemporalValue temporalValue = (TemporalValue) value;
                query.setParameter(name, temporalValue.date, temporalValue.type);
            } else {
                if (!convert) {
                    query.setParameter(name, value, false);
                } else {
                    query.setParameter(name, value);
                }
            }
        } else
            throw new DevelopmentException("Parameter '" + name + "' is not used in the query");
    }
    return query;
}
Also used : QueryMacroHandler(com.haulmont.cuba.core.sys.QueryMacroHandler) PersistenceSecurity(com.haulmont.cuba.core.PersistenceSecurity) Query(com.haulmont.cuba.core.Query) StringUtils(org.apache.commons.lang.StringUtils) java.util(java.util) Logger(org.slf4j.Logger) EntityManager(com.haulmont.cuba.core.EntityManager) MetaProperty(com.haulmont.chile.core.model.MetaProperty) LoggerFactory(org.slf4j.LoggerFactory) StringHelper(com.haulmont.bali.util.StringHelper) MetaClass(com.haulmont.chile.core.model.MetaClass) Scope(org.springframework.context.annotation.Scope) com.haulmont.cuba.core.global(com.haulmont.cuba.core.global) Inject(javax.inject.Inject) Component(org.springframework.stereotype.Component) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass) Entity(com.haulmont.cuba.core.entity.Entity) Entity(com.haulmont.cuba.core.entity.Entity) Query(com.haulmont.cuba.core.Query) EnumClass(com.haulmont.chile.core.datatypes.impl.EnumClass)

Aggregations

EnumClass (com.haulmont.chile.core.datatypes.impl.EnumClass)10 Method (java.lang.reflect.Method)4 MetaProperty (com.haulmont.chile.core.model.MetaProperty)3 Entity (com.haulmont.cuba.core.entity.Entity)3 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 ParseException (java.text.ParseException)3 Inject (javax.inject.Inject)3 LoggerFactory (org.slf4j.LoggerFactory)3 Component (org.springframework.stereotype.Component)3 Datatype (com.haulmont.chile.core.datatypes.Datatype)2 MetaClass (com.haulmont.chile.core.model.MetaClass)2 EnumStore (com.haulmont.cuba.core.config.EnumStore)2 com.haulmont.cuba.core.global (com.haulmont.cuba.core.global)2 Messages (com.haulmont.cuba.core.global.Messages)2 IOException (java.io.IOException)2 java.util (java.util)2 Nullable (javax.annotation.Nullable)2 StringUtils (org.apache.commons.lang.StringUtils)2 Logger (org.slf4j.Logger)2 CachingMetadataReaderFactory (org.springframework.core.type.classreading.CachingMetadataReaderFactory)2