Example usage for java.lang Class isEnum

List of usage examples for java.lang Class isEnum

Introduction

In this page you can find the example usage for java.lang Class isEnum.

Prototype

public boolean isEnum() 

Source Link

Document

Returns true if and only if this class was declared as an enum in the source code.

Usage

From source file:org.gvnix.web.datatables.util.QuerydslUtils.java

/**
 * Return an expression for {@code entityPath.fieldName} with the
 * {@code operator} or "equal" by default.
 * <p/>/*from  ww w. ja v  a  2  s . co  m*/
 * Expr: {@code entityPath.fieldName eq searchObj}
 * 
 * @param entityPath Full path to entity and associations. For example:
 *        {@code Pet} , {@code Pet.owner}
 * @param fieldName Property name in the given entity path. For example:
 *        {@code name} in {@code Pet} entity, {@code firstName} in
 *        {@code Pet.owner} entity.
 * @param searchObj the value to find, may be null
 * @param operator the operator to use into the expression. Supported
 *        operators:
 *        <ul>
 *        <li>For all types: {@code eq}, {@code in}, {@code ne},
 *        {@code notIn}, {@code isNull} and {@code isNotNull}.</li> <li> For
 *        strings and numbers: {@code goe}, {@code gt}, {@code loe},
 *        {@code lt} and {@code like}.</li> <li> For booleans: {@code goe},
 *        {@code gt}, {@code loe} and {@code lt}.</li> <li> For dates:
 *        {@code goe}, {@code gt}, {@code before}, {@code loe}, {@code lt}
 *        and {@code after}. </li>
 *        </ul>
 * @return BooleanExpression
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> BooleanExpression createObjectExpression(PathBuilder<T> entityPath, String fieldName,
        Object searchObj, String operator, ConversionService conversionService) {
    if (searchObj == null) {
        return null;
    }

    TypeDescriptor typeDescriptor = getTypeDescriptor(fieldName, entityPath);
    if (typeDescriptor == null) {
        throw new IllegalArgumentException(
                String.format("Can't found field '%s' on entity '%s'", fieldName, entityPath.getType()));
    }

    if (StringUtils.isBlank(operator) || StringUtils.equalsIgnoreCase(operator, "eq")) {
        return entityPath.get(fieldName).eq(searchObj);
    } else if (StringUtils.equalsIgnoreCase(operator, "in")) {
        return entityPath.get(fieldName).in(searchObj);
    } else if (StringUtils.equalsIgnoreCase(operator, "ne")) {
        return entityPath.get(fieldName).ne(searchObj);
    } else if (StringUtils.equalsIgnoreCase(operator, "notIn")) {
        return entityPath.get(fieldName).notIn(searchObj);
    } else if (StringUtils.equalsIgnoreCase(operator, OPERATOR_ISNULL)) {
        return entityPath.get(fieldName).isNull();
    } else if (StringUtils.equalsIgnoreCase(operator, "isNotNull")) {
        return entityPath.get(fieldName).isNotNull();
    }

    Class<?> fieldType = getFieldType(fieldName, entityPath);
    if (String.class == fieldType && String.class == searchObj.getClass()) {
        return createStringExpression(entityPath, fieldName, searchObj, operator);
    } else if ((Boolean.class == fieldType || boolean.class == fieldType)
            && String.class == searchObj.getClass()) {
        return createBooleanExpression(entityPath, fieldName, searchObj, operator);
    } else if ((Number.class.isAssignableFrom(fieldType) || NUMBER_PRIMITIVES.contains(fieldType))
            && String.class == searchObj.getClass()
            && isValidValueFor((String) searchObj, typeDescriptor, conversionService)) {
        return createNumericExpression(entityPath, fieldName, searchObj, operator, fieldType);

    } else if ((Date.class.isAssignableFrom(fieldType) || Calendar.class.isAssignableFrom(fieldType))
            && String.class == searchObj.getClass()) {
        return createDateExpression(entityPath, fieldName, searchObj, operator, fieldType);
    } else if (fieldType.isEnum() && String.class == searchObj.getClass()) {
        return createEnumExpression(entityPath, fieldName, (String) searchObj,
                (Class<? extends Enum>) fieldType);
    }

    return entityPath.get(fieldName).eq(searchObj);
}

From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java

@SuppressWarnings("unchecked")
public <T> T generateRandom(Class<T> clazz, Map<String, Type> itestGenericMap, ITestContext iTestContext) {
    Object res;//from   ww  w .ja v a 2s.com
    ITestParamState iTestState = iTestContext.getCurrentParam();
    if (null != iTestState && null == iTestState.getNames()) {
        res = iTestConfig.getITestValueConverter().convert(clazz, iTestState.getValue());
    } else if (Void.class == clazz || void.class == clazz) {
        res = null;
    } else if (String.class == clazz && (null == iTestState || null == iTestState.getNames())) {
        res = RandomStringUtils.randomAlphanumeric(20);
    } else if (Long.class == clazz || long.class == clazz) {
        res = new Long(random.nextLong());
    } else if (Integer.class == clazz || int.class == clazz) {
        res = new Integer(random.nextInt());
    } else if (Boolean.class == clazz || boolean.class == clazz) {
        res = random.nextBoolean() ? Boolean.TRUE : Boolean.FALSE;
    } else if (Date.class == clazz) {
        res = new Date(random.nextLong());
    } else if (Double.class == clazz || double.class == clazz) {
        res = random.nextDouble();
    } else if (Float.class == clazz || float.class == clazz) {
        res = random.nextFloat();
    } else if (Character.class == clazz || char.class == clazz) {
        res = RandomStringUtils.random(1).charAt(0);
    } else if (clazz.isEnum()) {
        res = clazz.getEnumConstants()[random.nextInt(clazz.getEnumConstants().length)];
    } else if (clazz.isArray()) {
        int size = random.nextInt(RANDOM_MAX - RANDOM_MIN) + RANDOM_MIN;
        if (null != iTestState && iTestState.getSizeParam() != null) {
            size = iTestState.getSizeParam();
        }
        Object array = Array.newInstance(clazz.getComponentType(), size);
        for (int i = 0; i < size; i++) {
            iTestContext.enter(array, String.valueOf(i));
            ITestParamState elementITestState = iTestState == null ? null
                    : iTestState.getElement(String.valueOf(i));
            Object value = generateRandom((Type) clazz.getComponentType(), itestGenericMap, iTestContext);
            Array.set(array, i, value);
            iTestContext.leave(value);
        }
        res = array;
    } else {
        res = newInstance(clazz, iTestContext);
        fillFields(clazz, res, iTestState, Collections.EMPTY_MAP, iTestContext);
    }
    return (T) res;
}

From source file:org.projectforge.business.user.UserPrefDao.java

/**
 * @param value/*w ww . j  a v a 2s . co  m*/
 * @return
 * @see #convertParameterValueToString(Object)
 */
@SuppressWarnings("unchecked")
public Object getParameterValue(final Class<?> type, final String str) {
    if (str == null) {
        return null;
    }
    if (type.isAssignableFrom(String.class) == true) {
        return str;
    } else if (type.isAssignableFrom(Integer.class) == true) {
        return Integer.valueOf(str);
    } else if (DefaultBaseDO.class.isAssignableFrom(type) == true) {
        final Integer id = NumberHelper.parseInteger(str);
        if (id != null) {
            if (PFUserDO.class.isAssignableFrom(type) == true) {
                return userDao.getOrLoad(id);
            } else if (TaskDO.class.isAssignableFrom(type) == true) {
                return taskDao.getOrLoad(id);
            } else if (Kost2DO.class.isAssignableFrom(type) == true) {
                return kost2Dao.getOrLoad(id);
            } else if (ProjektDO.class.isAssignableFrom(type) == true) {
                return projektDao.getOrLoad(id);
            } else {
                log.warn("getParameterValue: Type '" + type + "' not supported. May-be it does not work.");
                return getHibernateTemplate().load(type, id);
            }
        } else {
            return null;
        }
    } else if (KundeDO.class.isAssignableFrom(type) == true) {
        final Integer id = NumberHelper.parseInteger(str);
        if (id != null) {
            return kundeDao.getOrLoad(id);
        } else {
            return null;
        }
    } else if (type.isEnum() == true) {
        return Enum.valueOf((Class<Enum>) type, str);
    }
    log.error("UserPrefDao does not yet support parameters from type: " + type);
    return null;
}

From source file:org.grails.datastore.mapping.engine.NativeEntryEntityPersister.java

protected void refreshObjectStateFromNativeEntry(PersistentEntity persistentEntity, Object obj,
        Serializable nativeKey, T nativeEntry, boolean isEmbedded) {
    EntityAccess ea = createEntityAccess(persistentEntity, obj, nativeEntry);
    ea.setConversionService(getMappingContext().getConversionService());
    if (!(persistentEntity instanceof EmbeddedPersistentEntity)) {

        String idName = ea.getIdentifierName();
        ea.setProperty(idName, nativeKey);
    }// w  ww. j  a v  a2 s .c  om

    final List<PersistentProperty> props = persistentEntity.getPersistentProperties();
    for (final PersistentProperty prop : props) {
        String propKey = getNativePropertyKey(prop);
        if (prop instanceof Simple) {
            ea.setProperty(prop.getName(), getEntryValue(nativeEntry, propKey));
        } else if (prop instanceof Basic) {
            Object entryValue = getEntryValue(nativeEntry, propKey);
            if (entryValue instanceof Map) {
                entryValue = new LinkedHashMap((Map) entryValue);
            } else if (entryValue instanceof Collection) {
                Collection collection = MappingUtils.createConcreteCollection(prop.getType());

                Class propertyType = prop.getType();
                Class genericType = MappingUtils.getGenericTypeForProperty(persistentEntity.getJavaClass(),
                        prop.getName());
                Collection collectionValue = (Collection) entryValue;
                if (genericType != null && genericType.isEnum()) {
                    for (Object o : collectionValue) {
                        if (!(o instanceof Enum)) {
                            collection.add(Enum.valueOf(genericType, o.toString()));
                        }
                    }
                } else {
                    collection.addAll(collectionValue);
                }

                entryValue = collection;
            }
            ea.setProperty(prop.getName(), entryValue);
        } else if (prop instanceof Custom) {
            handleCustom(prop, ea, nativeEntry);
        } else if (prop instanceof ToOne) {
            if (prop instanceof Embedded) {
                Embedded embedded = (Embedded) prop;
                T embeddedEntry = getEmbedded(nativeEntry, propKey);

                if (embeddedEntry != null) {
                    Object embeddedInstance = newEntityInstance(embedded.getAssociatedEntity());
                    createEntityAccess(embedded.getAssociatedEntity(), embeddedInstance);
                    refreshObjectStateFromNativeEntry(embedded.getAssociatedEntity(), embeddedInstance, null,
                            embeddedEntry, true);
                    ea.setProperty(propKey, embeddedInstance);
                }
            }

            else {
                ToOne association = (ToOne) prop;

                Serializable tmp = null;
                if (!association.isForeignKeyInChild()) {
                    tmp = (Serializable) getEntryValue(nativeEntry, propKey);
                } else {
                    if (association.isBidirectional()) {

                        Query query = session.createQuery(association.getAssociatedEntity().getJavaClass());
                        query.eq(association.getInverseSide().getName(), obj).projections().id();

                        tmp = (Serializable) query.singleResult();
                    } else {
                        // TODO: handle unidirectional?
                    }

                }
                if (isEmbeddedEntry(tmp)) {
                    PersistentEntity associatedEntity = ((ToOne) prop).getAssociatedEntity();
                    Object instance = newEntityInstance(associatedEntity);
                    refreshObjectStateFromNativeEntry(associatedEntity, instance, null, (T) tmp, false);
                    ea.setProperty(prop.getName(), instance);
                } else if (tmp != null && !prop.getType().isInstance(tmp)) {
                    PersistentEntity associatedEntity = association.getAssociatedEntity();
                    final Serializable associationKey = (Serializable) getMappingContext()
                            .getConversionService().convert(tmp, associatedEntity.getIdentity().getType());
                    if (associationKey != null) {

                        PropertyMapping<Property> associationPropertyMapping = prop.getMapping();
                        boolean isLazy = isLazyAssociation(associationPropertyMapping);

                        final Class propType = prop.getType();
                        if (isLazy) {
                            Object proxy = getProxyFactory().createProxy(session, propType, associationKey);
                            ea.setProperty(prop.getName(), proxy);
                        } else {
                            ea.setProperty(prop.getName(), session.retrieve(propType, associationKey));
                        }
                    }
                }
            }
        } else if (prop instanceof EmbeddedCollection) {
            final Object embeddedInstances = getEntryValue(nativeEntry, propKey);
            loadEmbeddedCollection((EmbeddedCollection) prop, ea, embeddedInstances, propKey);
        } else if (prop instanceof OneToMany) {
            Association association = (Association) prop;
            PropertyMapping<Property> associationPropertyMapping = association.getMapping();

            if (isEmbedded) {
                List keys = loadEmbeddedCollectionKeys((Association) prop, ea, nativeEntry);
                if (List.class.isAssignableFrom(association.getType())) {
                    ea.setPropertyNoConversion(association.getName(), new PersistentList(keys,
                            association.getAssociatedEntity().getJavaClass(), session));
                } else if (Set.class.isAssignableFrom(association.getType())) {
                    ea.setPropertyNoConversion(association.getName(),
                            new PersistentSet(keys, association.getAssociatedEntity().getJavaClass(), session));
                }
            } else {
                boolean isLazy = isLazyAssociation(associationPropertyMapping);
                AssociationIndexer indexer = getAssociationIndexer(nativeEntry, association);
                nativeKey = (Serializable) getMappingContext().getConversionService().convert(nativeKey,
                        getPersistentEntity().getIdentity().getType());
                if (isLazy) {
                    if (List.class.isAssignableFrom(association.getType())) {
                        ea.setPropertyNoConversion(association.getName(),
                                new PersistentList(nativeKey, session, indexer));
                    } else if (SortedSet.class.isAssignableFrom(association.getType())) {
                        ea.setPropertyNoConversion(association.getName(),
                                new PersistentSortedSet(nativeKey, session, indexer));
                    } else if (Set.class.isAssignableFrom(association.getType())) {
                        ea.setPropertyNoConversion(association.getName(),
                                new PersistentSet(nativeKey, session, indexer));
                    }
                } else {
                    if (indexer != null) {
                        List keys = indexer.query(nativeKey);
                        ea.setProperty(association.getName(),
                                session.retrieveAll(association.getAssociatedEntity().getJavaClass(), keys));
                    }
                }
            }
        } else if (prop instanceof ManyToMany) {
            ManyToMany manyToMany = (ManyToMany) prop;
            PropertyMapping<Property> associationPropertyMapping = manyToMany.getMapping();

            boolean isLazy = isLazyAssociation(associationPropertyMapping);
            nativeKey = (Serializable) getMappingContext().getConversionService().convert(nativeKey,
                    getPersistentEntity().getIdentity().getType());
            Class childType = manyToMany.getAssociatedEntity().getJavaClass();
            Collection cached = ((SessionImplementor) session).getCachedCollection(persistentEntity, nativeKey,
                    manyToMany.getName());
            if (cached == null) {
                Collection collection;
                if (isLazy) {
                    Collection keys = getManyToManyKeys(persistentEntity, obj, nativeKey, nativeEntry,
                            manyToMany);
                    if (List.class.isAssignableFrom(manyToMany.getType())) {
                        collection = new PersistentList(keys, childType, session);
                        ea.setPropertyNoConversion(manyToMany.getName(), collection);
                    } else if (Set.class.isAssignableFrom(manyToMany.getType())) {
                        collection = new PersistentSet(keys, childType, session);
                        ea.setPropertyNoConversion(manyToMany.getName(), collection);
                    } else {
                        collection = Collections.emptyList();
                    }
                } else {
                    AssociationIndexer indexer = getAssociationIndexer(nativeEntry, manyToMany);
                    if (indexer == null) {
                        if (List.class.isAssignableFrom(manyToMany.getType())) {
                            collection = Collections.emptyList();
                        } else if (Set.class.isAssignableFrom(manyToMany.getType())) {
                            collection = Collections.emptySet();
                        } else {
                            collection = Collections.emptyList();
                        }
                    } else {
                        List keys = indexer.query(nativeKey);
                        collection = session.retrieveAll(childType, keys);
                        ea.setProperty(manyToMany.getName(), collection);
                    }
                }
                ((SessionImplementor) session).cacheCollection(persistentEntity, nativeKey, collection,
                        manyToMany.getName());
            } else {
                ea.setProperty(manyToMany.getName(), cached);
            }
        }
    }
}

From source file:org.openmrs.util.OpenmrsUtil.java

/**
 * Takes a String (e.g. a user-entered one) and parses it into an object of the specified class
 * /*w  w  w  .ja v  a 2s .  c  o  m*/
 * @param string
 * @param clazz
 * @return Object of type <code>clazz</code> with the data from <code>string</code>
 */
@SuppressWarnings("unchecked")
public static Object parse(String string, Class clazz) {
    try {
        // If there's a valueOf(String) method, just use that (will cover at
        // least String, Integer, Double, Boolean)
        Method valueOfMethod = null;
        try {
            valueOfMethod = clazz.getMethod("valueOf", String.class);
        } catch (NoSuchMethodException ex) {
        }
        if (valueOfMethod != null) {
            return valueOfMethod.invoke(null, string);
        } else if (clazz.isEnum()) {
            // Special-case for enum types
            List<Enum> constants = Arrays.asList((Enum[]) clazz.getEnumConstants());
            for (Enum e : constants) {
                if (e.toString().equals(string)) {
                    return e;
                }
            }
            throw new IllegalArgumentException(string + " is not a legal value of enum class " + clazz);
        } else if (String.class.equals(clazz)) {
            return string;
        } else if (Location.class.equals(clazz)) {
            try {
                Integer.parseInt(string);
                LocationEditor ed = new LocationEditor();
                ed.setAsText(string);
                return ed.getValue();
            } catch (NumberFormatException ex) {
                return Context.getLocationService().getLocation(string);
            }
        } else if (Concept.class.equals(clazz)) {
            ConceptEditor ed = new ConceptEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (Program.class.equals(clazz)) {
            ProgramEditor ed = new ProgramEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (ProgramWorkflowState.class.equals(clazz)) {
            ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (EncounterType.class.equals(clazz)) {
            EncounterTypeEditor ed = new EncounterTypeEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (Form.class.equals(clazz)) {
            FormEditor ed = new FormEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (Drug.class.equals(clazz)) {
            DrugEditor ed = new DrugEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (PersonAttributeType.class.equals(clazz)) {
            PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (Cohort.class.equals(clazz)) {
            CohortEditor ed = new CohortEditor();
            ed.setAsText(string);
            return ed.getValue();
        } else if (Date.class.equals(clazz)) {
            // TODO: this uses the date format from the current session,
            // which could cause problems if the user changes it after
            // searching.
            CustomDateEditor ed = new CustomDateEditor(Context.getDateFormat(), true, 10);
            ed.setAsText(string);
            return ed.getValue();
        } else if (Object.class.equals(clazz)) {
            // TODO: Decide whether this is a hack. Currently setting Object
            // arguments with a String
            return string;
        } else {
            throw new IllegalArgumentException("Don't know how to handle class: " + clazz);
        }
    } catch (Exception ex) {
        log.error("error converting \"" + string + "\" to " + clazz, ex);
        throw new IllegalArgumentException(ex);
    }
}

From source file:ca.oson.json.util.ObjectUtil.java

public static void addAnnotationToMethod(String className, String methodName, String annotationFullName,
        String postFix, Map<String, Object> nameValues) throws Exception {

    // pool creation
    ClassPool pool = ClassPool.getDefault();
    // extracting the class
    CtClass cc = pool.getCtClass(className);
    // looking for the method to apply the annotation on
    CtMethod methodDescriptor = cc.getDeclaredMethod(methodName);

    for (Object obj : methodDescriptor.getAnnotations()) {
        Annotation an = (Annotation) obj;

        if (an.getClass().getName().equals(annotationFullName)) {
            return;
        }//  w ww .j a va2 s  .co  m
    }

    // create the annotation
    ClassFile ccFile = cc.getClassFile();
    ConstPool constpool = ccFile.getConstPool();
    AnnotationsAttribute attr = new AnnotationsAttribute(constpool, AnnotationsAttribute.visibleTag);
    javassist.bytecode.annotation.Annotation annot = new javassist.bytecode.annotation.Annotation(
            annotationFullName, constpool);

    if (nameValues != null) {
        for (Entry<String, Object> entry : nameValues.entrySet()) {
            String name = entry.getKey();
            Object value = entry.getValue();
            Class<?> returnType = value.getClass();

            if (returnType == String.class) {
                annot.addMemberValue(name, new StringMemberValue((String) value, ccFile.getConstPool()));

            } else if (returnType == Boolean.class || returnType == boolean.class) {
                annot.addMemberValue(entry.getKey(),
                        new BooleanMemberValue((boolean) value, ccFile.getConstPool()));

            } else if (returnType == Character.class || returnType == char.class) {
                annot.addMemberValue(entry.getKey(), new CharMemberValue((char) value, ccFile.getConstPool()));

            } else if (returnType == Long.class || returnType == long.class) {
                annot.addMemberValue(entry.getKey(), new LongMemberValue((long) value, ccFile.getConstPool()));

            } else if (returnType == Integer.class || returnType == int.class) {
                annot.addMemberValue(entry.getKey(),
                        new IntegerMemberValue((int) value, ccFile.getConstPool()));

            } else if (returnType == Double.class || returnType == double.class) {
                annot.addMemberValue(entry.getKey(),
                        new DoubleMemberValue((double) value, ccFile.getConstPool()));

            } else if (returnType == Byte.class || returnType == byte.class) {
                annot.addMemberValue(entry.getKey(), new ByteMemberValue((byte) value, ccFile.getConstPool()));

            } else if (returnType == Short.class || returnType == short.class) {
                annot.addMemberValue(entry.getKey(),
                        new ShortMemberValue((short) value, ccFile.getConstPool()));

            } else if (returnType == Float.class || returnType == float.class) {
                annot.addMemberValue(entry.getKey(),
                        new FloatMemberValue((float) value, ccFile.getConstPool()));

            } else if (returnType.isEnum() || Enum.class.isAssignableFrom(returnType)) {
                annot.addMemberValue(entry.getKey(), new EnumMemberValue(ccFile.getConstPool()));

            } else if (returnType.isArray()) {
                annot.addMemberValue(entry.getKey(), new ArrayMemberValue(ccFile.getConstPool()));

            } else if (Annotation.class.isAssignableFrom(returnType)) {
                annot.addMemberValue(entry.getKey(), new AnnotationMemberValue(
                        (javassist.bytecode.annotation.Annotation) value, ccFile.getConstPool()));

            } else if (value instanceof Class) {
                annot.addMemberValue(entry.getKey(),
                        new ClassMemberValue(((Class) value).getName(), ccFile.getConstPool()));

            }
        }
    }

    attr.addAnnotation(annot);
    // add the annotation to the method descriptor
    methodDescriptor.getMethodInfo().addAttribute(attr);

    if (postFix != null) {
        String newClassName = className + postFix;
        cc.setName(newClassName);
        cc = pool.makeClass(newClassName);
        //cc.writeFile();
    }

    // transform the ctClass to java class
    Class dynamiqueBeanClass = cc.toClass();
    //http://stackoverflow.com/questions/23336172/adding-an-annotation-to-a-runtime-generated-class-using-javassist

    // instanciating the updated class
    //dynamiqueBeanClass.newInstance();
}

From source file:com.nonninz.robomodel.RoboModel.java

private void loadField(Field field, Cursor query) throws DatabaseNotUpToDateException {
    final Class<?> type = field.getType();
    final boolean wasAccessible = field.isAccessible();
    final int columnIndex = query.getColumnIndex(field.getName());
    field.setAccessible(true);//ww  w  .j a v  a  2s. c om

    /*
     * TODO: There is the potential of a problem here:
     * What happens if the developer changes the type of a field between releases?
     *
     * If he saves first, then the column type will be changed (In the future).
     * If he loads first, we don't know if an Exception will be thrown if the
     * types are incompatible, because it's undocumented in the Cursor documentation.
     */

    try {
        if (type == String.class) {
            field.set(this, query.getString(columnIndex));
        } else if (type == Boolean.TYPE) {
            final boolean value = query.getInt(columnIndex) == 1 ? true : false;
            field.setBoolean(this, value);
        } else if (type == Byte.TYPE) {
            field.setByte(this, (byte) query.getShort(columnIndex));
        } else if (type == Double.TYPE) {
            field.setDouble(this, query.getDouble(columnIndex));
        } else if (type == Float.TYPE) {
            field.setFloat(this, query.getFloat(columnIndex));
        } else if (type == Integer.TYPE) {
            field.setInt(this, query.getInt(columnIndex));
        } else if (type == Long.TYPE) {
            field.setLong(this, query.getLong(columnIndex));
        } else if (type == Short.TYPE) {
            field.setShort(this, query.getShort(columnIndex));
        } else if (type.isEnum()) {
            final String string = query.getString(columnIndex);
            if (string != null && string.length() > 0) {
                final Object[] constants = type.getEnumConstants();
                final Method method = type.getMethod("valueOf", Class.class, String.class);
                final Object value = method.invoke(constants[0], type, string);
                field.set(this, value);
            }
        } else {
            // Try to de-json it (db column must be of type text)
            try {
                final Object value = mMapper.readValue(query.getString(columnIndex), field.getType());
                field.set(this, value);
            } catch (final Exception e) {
                final String msg = String.format("Type %s is not supported for field %s", type,
                        field.getName());
                Ln.w(e, msg);
                throw new IllegalArgumentException(msg);
            }
        }
    } catch (final IllegalAccessException e) {
        final String msg = String.format("Field %s is not accessible", type, field.getName());
        throw new IllegalArgumentException(msg);
    } catch (final NoSuchMethodException e) {
        // Should not happen
        throw new RuntimeException(e);
    } catch (final InvocationTargetException e) {
        // Should not happen
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        // This is when there is no column in db, but there is in the model
        throw new DatabaseNotUpToDateException(e);
    } finally {
        field.setAccessible(wasAccessible);
    }
}

From source file:org.openehr.build.RMObjectBuilder.java

/**
 * Construct an instance of RM class of given name and values. <p/> If the
 * input is a string, and the required attribute is some other types
 * (integer, double etc), it will be converted into right type. if there is
 * any error during conversion, AttributeFormatException will be thrown.
 * /* w w w. ja  v  a 2 s .co  m*/
 * @param rmClassName
 * @param valueMap
 * @return created instance
 * @throws RMObjectBuildingException
 */
public RMObject construct(String rmClassName, Map<String, Object> valueMap) throws RMObjectBuildingException {

    Class rmClass = retrieveRMType(rmClassName);

    // replace underscore separated names with camel case
    Map<String, Object> filteredMap = new HashMap<String, Object>();
    for (String name : valueMap.keySet()) {
        filteredMap.put(toCamelCase(name), valueMap.get(name));
    }
    Constructor constructor = fullConstructor(rmClass);
    Map<String, Class> typeMap = attributeType(rmClass);
    Map<String, Integer> indexMap = attributeIndex(rmClass);
    Map<String, Attribute> attributeMap = attributeMap(rmClass);
    Object[] valueArray = new Object[indexMap.size()];

    for (String name : typeMap.keySet()) {

        Object value = filteredMap.get(name);

        if (!typeMap.containsKey(name) || !attributeMap.containsKey(name)) {
            throw new RMObjectBuildingException("unknown attribute " + name);
        }

        Class type = typeMap.get(name);
        Integer index = indexMap.get(name);

        Attribute attribute = attributeMap.get(name);
        if (index == null || type == null) {
            throw new RMObjectBuildingException("unknown attribute \"" + name + "\"");
        }

        // system supplied value
        if (attribute.system()) {
            SystemValue sysvalue = SystemValue.fromId(name);
            if (sysvalue == null) {
                throw new RMObjectBuildingException("unknonw system value" + "\"" + name + "\"");
            }
            value = systemValues.get(sysvalue);
            if (value == null) {
                throw new AttributeMissingException("missing value for " + "system attribute \"" + name
                        + "\" in class: " + rmClass + ", with valueMap: " + valueMap);
            }
        }

        // check required attributes
        if (value == null && attribute.required()) {
            log.info(attribute);
            throw new AttributeMissingException("missing value for " + "required attribute \"" + name
                    + "\" of type " + type + " while constructing " + rmClass + " with valueMap: " + valueMap);
        }

        // enum
        else if (type.isEnum() && !value.getClass().isEnum()) {
            // OG added
            if (type.equals(ProportionKind.class))
                value = ProportionKind.fromValue(Integer.parseInt(value.toString()));
            else
                value = Enum.valueOf(type, value.toString());
        }

        // in case of null, create a default value
        else if (value == null) {
            value = defaultValue(type);
        }

        // in case of string value, convert to right type if necessary
        else if (value instanceof String) {
            String str = (String) value;
            try {

                // for DvCount
                if (type.equals(int.class)) {
                    value = Integer.parseInt(str);

                    // for DvQuantity
                } else if (type.equals(double.class)) {
                    value = Double.parseDouble(str);

                    // for DvProportion.precision
                } else if (type.equals(Integer.class)) {
                    value = new Integer(str);
                }

            } catch (NumberFormatException e) {
                throw new AttributeFormatException(
                        "wrong format of " + "attribute " + name + ", expect " + type);
            }

            // deal with mismatch between array and list
        } else if (type.isAssignableFrom(List.class) && value.getClass().isArray()) {

            Object[] array = (Object[]) value;
            List list = new ArrayList();
            for (Object o : array) {
                list.add(o);
            }
            value = list;

            // deal with mismatch between array and set
        } else if (type.isAssignableFrom(Set.class) && value.getClass().isArray()) {

            Object[] array = (Object[]) value;
            Set set = new HashSet();
            for (Object o : array) {
                set.add(o);
            }
            value = set;
        }
        // check type
        else if (value != null && !type.isPrimitive()) {
            try {
                type.cast(value);
            } catch (ClassCastException e) {
                throw new RMObjectBuildingException("Failed to construct: " + rmClassName
                        + ", value for attribute '" + name + "' has wrong type, expected \"" + type
                        + "\", but got \"" + value.getClass() + "\"");
            }
        }
        valueArray[index] = value;
    }

    Object ret = null;

    try {
        // OG added hack
        if (rmClassName.equalsIgnoreCase("DVCOUNT")) {
            log.debug("Fixing DVCOUNT...");
            for (int i = 0; i < valueArray.length; i++) {
                Object value = valueArray[i];
                if (value != null && value.getClass().equals(Float.class))
                    valueArray[i] = Double.parseDouble(value.toString());
                else if (value != null && value.getClass().equals(Long.class))
                    valueArray[i] = Integer.parseInt(value.toString());
            }
        }
        ret = constructor.newInstance(valueArray);
    } catch (Exception e) {

        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }

        log.debug("failed in constructor.newInstance()", e);

        if (stringParsingTypes.contains(rmClassName)) {
            throw new AttributeFormatException("wrong format for type " + rmClassName);
        }

        throw new RMObjectBuildingException("failed to create new instance of  " + rmClassName
                + " with valueMap: " + toString(valueMap) + ", cause: " + e.getMessage());
    }
    return (RMObject) ret;
}

From source file:org.openengsb.core.ekb.common.EDBConverter.java

/**
 * Generate the value for a specific property of a model out of an EDBObject.
 *///from w w w.j av  a  2 s .  c  o m
private Object getValueForProperty(PropertyDescriptor propertyDescriptor, EDBObject object) {
    Method setterMethod = propertyDescriptor.getWriteMethod();
    String propertyName = propertyDescriptor.getName();
    Object value = object.getObject(propertyName);
    Class<?> parameterType = setterMethod.getParameterTypes()[0];

    // TODO: OPENENGSB-2719 do that in a better way than just an if-else series
    if (Map.class.isAssignableFrom(parameterType)) {
        List<Class<?>> classes = getGenericMapParameterClasses(setterMethod);
        value = getMapValue(classes.get(0), classes.get(1), propertyName, object);
    } else if (List.class.isAssignableFrom(parameterType)) {
        Class<?> clazz = getGenericListParameterClass(setterMethod);
        value = getListValue(clazz, propertyName, object);
    } else if (parameterType.isArray()) {
        Class<?> clazz = parameterType.getComponentType();
        value = getArrayValue(clazz, propertyName, object);
    } else if (value == null) {
        return null;
    } else if (OpenEngSBModel.class.isAssignableFrom(parameterType)) {
        EDBObject obj = edbService.getObject((String) value);
        value = convertEDBObjectToUncheckedModel(parameterType, obj);
        object.remove(propertyName);
    } else if (parameterType.equals(FileWrapper.class)) {
        FileWrapper wrapper = new FileWrapper();
        String filename = object.getString(propertyName + EDBConverterUtils.FILEWRAPPER_FILENAME_SUFFIX);
        String content = (String) value;
        wrapper.setFilename(filename);
        wrapper.setContent(Base64.decodeBase64(content));
        value = wrapper;
        object.remove(propertyName + EDBConverterUtils.FILEWRAPPER_FILENAME_SUFFIX);
    } else if (parameterType.equals(File.class)) {
        return null;
    } else if (object.containsKey(propertyName)) {
        if (parameterType.isEnum()) {
            value = getEnumValue(parameterType, value);
        } else if (Number.class.isAssignableFrom(parameterType)) {
            value = NumberUtils.createNumber((String) value);
        }
    }
    object.remove(propertyName);
    return value;
}

From source file:fr.certu.chouette.command.Command.java

private void addAttribute(Object object, String attrname, String value) throws Exception {
    Class<?> beanClass = object.getClass();
    Method adder = findAdder(beanClass, attrname);
    Class<?> type = adder.getParameterTypes()[0];
    Object arg = null;//from www .ja  va 2  s  .com
    if (type.isEnum()) {
        arg = toEnum(type, value);
    } else if (type.isPrimitive()) {
        arg = toPrimitive(type, value);
    } else {
        arg = toObject(type, value);
    }
    adder.invoke(object, arg);

}