Example usage for java.lang Class getComponentType

List of usage examples for java.lang Class getComponentType

Introduction

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

Prototype

public Class<?> getComponentType() 

Source Link

Document

Returns the Class representing the component type of an array.

Usage

From source file:nl.strohalm.cyclos.utils.conversion.CoercionHelper.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private static Object convert(Class toType, Object value) {
    if ("".equals(value)) {
        value = null;//w  w w.  jav a 2s.co m
    }
    // If we do not want a collection, but the value is one, use the first value
    if (value != null && !(Collection.class.isAssignableFrom(toType) || toType.isArray())
            && (value.getClass().isArray() || value instanceof Collection)) {
        final Iterator it = IteratorUtils.getIterator(value);
        if (!it.hasNext()) {
            value = null;
        } else {
            value = it.next();
        }
    }

    // Check for null values
    if (value == null) {
        if (toType.isPrimitive()) {
            // On primitives, use the default value
            if (toType == Boolean.TYPE) {
                value = Boolean.FALSE;
            } else if (toType == Character.TYPE) {
                value = '\0';
            } else {
                value = 0;
            }
        } else {
            // For objects, return null
            return null;
        }
    }

    // Check if the value is already of the expected type
    if (toType.isInstance(value)) {
        return value;
    }

    // If the class is primitive, use the wrapper, so we have an easier work of testing instances
    if (toType.isPrimitive()) {
        toType = ClassUtils.primitiveToWrapper(toType);
    }

    // Convert to well-known types
    if (String.class.isAssignableFrom(toType)) {
        if (value instanceof Entity) {
            final Long entityId = ((Entity) value).getId();
            return entityId == null ? null : entityId.toString();
        }
        return value.toString();
    } else if (Number.class.isAssignableFrom(toType)) {
        if (!(value instanceof Number)) {
            if (value instanceof String) {
                value = new BigDecimal((String) value);
            } else if (value instanceof Date) {
                value = ((Date) value).getTime();
            } else if (value instanceof Calendar) {
                value = ((Calendar) value).getTimeInMillis();
            } else if (value instanceof Entity) {
                value = ((Entity) value).getId();
                if (value == null) {
                    return null;
                }
            } else {
                throw new ConversionException("Invalid number: " + value);
            }
        }
        final Number number = (Number) value;
        if (Byte.class.isAssignableFrom(toType)) {
            return number.byteValue();
        } else if (Short.class.isAssignableFrom(toType)) {
            return number.shortValue();
        } else if (Integer.class.isAssignableFrom(toType)) {
            return number.intValue();
        } else if (Long.class.isAssignableFrom(toType)) {
            return number.longValue();
        } else if (Float.class.isAssignableFrom(toType)) {
            return number.floatValue();
        } else if (Double.class.isAssignableFrom(toType)) {
            return number.doubleValue();
        } else if (BigInteger.class.isAssignableFrom(toType)) {
            return new BigInteger(number.toString());
        } else if (BigDecimal.class.isAssignableFrom(toType)) {
            return new BigDecimal(number.toString());
        }
    } else if (Boolean.class.isAssignableFrom(toType)) {
        if (value instanceof Number) {
            return ((Number) value).intValue() != 0;
        } else if ("on".equalsIgnoreCase(value.toString())) {
            return true;
        } else {
            return Boolean.parseBoolean(value.toString());
        }
    } else if (Character.class.isAssignableFrom(toType)) {
        final String str = value.toString();
        return (str.length() == 0) ? null : str.charAt(0);
    } else if (Calendar.class.isAssignableFrom(toType)) {
        if (value instanceof Date) {
            final Calendar cal = new GregorianCalendar();
            cal.setTime((Date) value);
            return cal;
        }
    } else if (Date.class.isAssignableFrom(toType)) {
        if (value instanceof Calendar) {
            final long millis = ((Calendar) value).getTimeInMillis();
            try {
                return ConstructorUtils.invokeConstructor(toType, millis);
            } catch (final Exception e) {
                throw new IllegalStateException(e);
            }
        }
    } else if (Enum.class.isAssignableFrom(toType)) {
        Object ret;
        try {
            ret = Enum.valueOf(toType, value.toString());
        } catch (final Exception e) {
            ret = null;
        }
        if (ret == null) {
            Object[] possible;
            try {
                possible = (Object[]) toType.getMethod("values").invoke(null);
            } catch (final Exception e) {
                throw new IllegalStateException(
                        "Couldn't invoke the 'values' method for enum " + toType.getName());
            }
            if (StringValuedEnum.class.isAssignableFrom(toType)) {
                final String test = coerce(String.class, value);
                for (final Object item : possible) {
                    if (((StringValuedEnum) item).getValue().equals(test)) {
                        ret = item;
                        break;
                    }
                }
            } else if (IntValuedEnum.class.isAssignableFrom(toType)) {
                final int test = coerce(Integer.TYPE, value);
                for (final Object item : possible) {
                    if (((IntValuedEnum) item).getValue() == test) {
                        ret = item;
                        break;
                    }
                }
            } else {
                throw new ConversionException("Invalid enum: " + value);
            }
        }
        return ret;
    } else if (Entity.class.isAssignableFrom(toType)) {
        final Long id = coerce(Long.class, value);
        return EntityHelper.reference(toType, id);
    } else if (Locale.class.isAssignableFrom(toType)) {
        return LocaleConverter.instance().valueOf(value.toString());
    } else if (Collection.class.isAssignableFrom(toType)) {
        final Collection collection = (Collection) ClassHelper.instantiate(toType);
        final Iterator iterator = IteratorUtils.getIterator(value);
        while (iterator.hasNext()) {
            collection.add(iterator.next());
        }
        return collection;
    } else if (toType.isArray()) {
        final Collection collection = coerceCollection(toType.getComponentType(), value);
        final Object[] array = (Object[]) Array.newInstance(toType.getComponentType(), collection.size());
        return collection.toArray(array);
    }

    // We don't know how to convert the value
    throw new ConversionException("Cannot coerce value to: " + toType.getName());
}

From source file:CustomControlExample.java

String parameterInfo(String methodRoot) {
    String typeName = null;/*w  w w .j  a  v  a 2 s  .  c  om*/
    Class returnType = getReturnType(methodRoot);
    boolean isArray = returnType.isArray();
    if (isArray) {
        typeName = returnType.getComponentType().getName();
    } else {
        typeName = returnType.getName();
    }
    String typeNameString = typeName;
    int index = typeName.lastIndexOf('.');
    if (index != -1 && index + 1 < typeName.length())
        typeNameString = typeName.substring(index + 1);
    String info = ControlExample.getResourceString("Info_" + typeNameString + (isArray ? "A" : ""));
    if (isArray) {
        typeNameString += "[]";
    }
    return ControlExample.getResourceString("Parameter_Info", new Object[] { typeNameString, info });
}

From source file:ca.oson.json.Oson.java

@SuppressWarnings("unchecked")
private <E> E json2Object(FieldData objectDTO) {
    // String value, Class<E> returnType
    Class<E> returnType = objectDTO.returnType;

    Object value = objectDTO.valueToProcess;
    if (StringUtil.isNull(value)) {
        if (objectDTO.required()) {
            return (E) DefaultValue.getSystemDefault(returnType);
        }/*from   w w  w  .j a v  a2 s.c om*/

        return null;
    }

    if (returnType == null || returnType == Object.class) {
        if (StringUtil.isEmpty(value)) {
            return null;
        }

        returnType = (Class<E>) value.getClass();
        objectDTO.returnType = returnType;
    }

    // first, get the class mapper
    //if (objectDTO.fieldMapper == null && objectDTO.classMapper == null) {
    objectDTO.classMapper = getGlobalizedClassMapper(returnType);
    //}

    if (returnType == String.class) {
        return (E) json2String(objectDTO);

        //      } else if (returnType == Optional.class) {
        //         return (E) json2Optional(objectDTO);

    } else if (returnType == Character.class || returnType == char.class) {
        return (E) json2Character(objectDTO);

    } else if (returnType == Boolean.class || returnType == boolean.class
            || returnType == AtomicBoolean.class) {
        return (E) json2Boolean(objectDTO);

    } else if (Number.class.isAssignableFrom(returnType) || returnType.isPrimitive()) {

        objectDTO.valueToProcess = StringUtil.unquote(objectDTO.valueToProcess, isEscapeHtml());

        if (returnType == Integer.class || returnType == int.class) {
            return (E) json2Integer(objectDTO);
        } else if (returnType == Long.class || returnType == long.class) {
            return (E) json2Long(objectDTO);

        } else if (returnType == Double.class || returnType == double.class) {
            return (E) json2Double(objectDTO);

        } else if (returnType == Byte.class || returnType == byte.class) {
            return (E) json2Byte(objectDTO);

        } else if (returnType == Short.class || returnType == short.class) {
            return (E) json2Short(objectDTO);

        } else if (returnType == Float.class || returnType == float.class) {
            return (E) json2Float(objectDTO);

        } else if (returnType == BigDecimal.class) {
            return (E) json2BigDecimal(objectDTO);

        } else if (returnType == BigInteger.class) {
            return (E) json2BigInteger(objectDTO);

        } else if (returnType == AtomicInteger.class) {
            return (E) json2AtomicInteger(objectDTO);

        } else if (returnType == AtomicLong.class) {
            return (E) json2AtomicLong(objectDTO);

        } else { // default to Double, in case no specific type is specified
            return (E) json2Double(objectDTO);
        }

    } else if (returnType.isEnum() || Enum.class.isAssignableFrom(returnType)) {
        return (E) json2Enum(objectDTO);

    } else if (returnType == Date.class || Date.class.isAssignableFrom(returnType)) {
        return (E) json2Date(objectDTO);

    } else if (returnType.isArray() || Collection.class.isAssignableFrom(returnType)) {

        Collection<E> values = null;
        Class<?> valueType = value.getClass();
        if (Collection.class.isAssignableFrom(valueType)) {
            values = (Collection<E>) value;
        } else if (valueType.isArray()) {
            values = Arrays.asList((E[]) value);
        }

        if (values == null) {
            //return null;
        } else {
            objectDTO.valueToProcess = values;
        }

        Class<E> componentType = (Class<E>) returnType.getComponentType();
        if (componentType == null) {
            objectDTO.incrLevel();
            componentType = guessComponentType(objectDTO);
            objectDTO.descLevel();
        }
        if (componentType == null) {
            componentType = CollectionArrayTypeGuesser.guessElementType(values, returnType, getJsonClassType());
        }
        if (componentType == null)
            componentType = (Class<E>) Object.class;

        if (componentType.isPrimitive()) {
            E arr = null;
            if (componentType == int.class) {
                arr = (E) json2ArrayInt(objectDTO);

            } else if (componentType == byte.class) {
                arr = (E) json2ArrayByte(objectDTO);
            } else if (componentType == char.class) {
                arr = (E) json2ArrayChar(objectDTO);
            } else if (componentType == float.class) {
                arr = (E) json2ArrayFloat(objectDTO);
            } else if (componentType == double.class) {
                arr = (E) json2ArrayDouble(objectDTO);
            } else if (componentType == long.class) {
                arr = (E) json2ArrayLong(objectDTO);
            } else if (componentType == short.class) {
                arr = (E) json2ArrayShort(objectDTO);
            } else if (componentType == boolean.class) {
                arr = (E) json2ArrayBoolean(objectDTO);
            } else {
                // return null;
            }

            if (arr != null && objectDTO.classMapper.orderArrayAndList) {
                Arrays.sort((E[]) arr);
            }

            return arr;

        } else if (Collection.class.isAssignableFrom(returnType)) {
            return (E) json2Collection(objectDTO);

        } else {
            return (E) json2Array(objectDTO);
        }

    } else if (returnType != Optional.class && Map.class.isAssignableFrom(returnType)) {
        return (E) json2Map(objectDTO);

    } else {
        if (objectDTO.returnObj == null) {
            return (E) deserialize2Object(value, returnType, objectDTO);

        } else {
            objectDTO.returnType = returnType;
            return (E) deserialize2Object(objectDTO);
        }
    }
}

From source file:ca.oson.json.Oson.java

private <E, R> Class guessComponentType(FieldData newFieldData) {
    boolean json2Java = newFieldData.json2Java;

    if (!json2Java) {
        return newFieldData.returnType;
    } else {/*from w  w w  .  j  a v  a 2s  .  c  om*/

        E obj = (E) newFieldData.valueToProcess;

        Class returnType = newFieldData.returnType;
        Class itemType = null;
        if (obj != null) {
            itemType = obj.getClass();
        }

        if (newFieldData.componentType != null) {
            Class classType = newFieldData.componentType.getClassType();
            Class cls = newFieldData.componentType.getMainComponentType();
            if (cls != null
                    && (ObjectUtil.isBasicDataType(cls) || ObjectUtil.isSameDataType(classType, returnType))) {
                return cls;
            }
        }

        String returnTypeName = null;
        if (returnType != null) {
            returnTypeName = returnType.getName();
        }
        String itemTypeName = null;
        if (itemType != null) {
            itemTypeName = itemType.getName();
        }

        int returnTypeCount = 0;
        int itemTypeCount = 0;
        String toGenericString = null;
        Class fieldType = null;
        if (newFieldData.field != null) {
            toGenericString = newFieldData.field.toGenericString();
            Class[] fieldTypes = ObjectUtil.getComponentTypes(toGenericString);

            if (fieldTypes != null && fieldTypes.length > 0) {
                if (fieldTypes.length == 1) {
                    fieldType = fieldTypes[0];
                } else {
                    fieldType = fieldTypes[0];

                    if (newFieldData.isMapValue) {
                        fieldType = fieldTypes[1];
                    } else {
                        fieldType = fieldTypes[0];
                    }
                }
            }

            if (returnTypeName != null && toGenericString.indexOf(returnTypeName) > -1) {
                returnTypeCount++;
            }
            if (itemTypeName != null && toGenericString.indexOf(itemTypeName) > -1) {
                itemTypeCount++;
            }
        }
        if (fieldType == null && returnType != null) {
            toGenericString = returnType.toGenericString();
            fieldType = ObjectUtil.getComponentType(toGenericString);
            if (returnTypeName != null && toGenericString.indexOf(returnTypeName) > -1) {
                returnTypeCount++;
            }
            if (itemTypeName != null && toGenericString.indexOf(itemTypeName) > -1) {
                itemTypeCount++;
            }
        }
        if (fieldType == null && newFieldData.setter != null) {
            toGenericString = newFieldData.setter.toGenericString();
            fieldType = ObjectUtil.getComponentType(toGenericString);
            if (returnTypeName != null && toGenericString.indexOf(returnTypeName) > -1) {
                returnTypeCount++;
            }
            if (itemTypeName != null && toGenericString.indexOf(itemTypeName) > -1) {
                itemTypeCount++;
            }

            if (fieldType == null) {
                Class[] types = newFieldData.setter.getParameterTypes();
                if (types != null && types.length > 0) {
                    toGenericString = types[0].toGenericString();
                    fieldType = ObjectUtil.getComponentType(toGenericString);
                    if (returnTypeName != null && toGenericString.indexOf(returnTypeName) > -1) {
                        returnTypeCount++;
                    }
                    if (itemTypeName != null && toGenericString.indexOf(itemTypeName) > -1) {
                        itemTypeCount++;
                    }
                }
            }
        }

        ComponentType type = getComponentType();
        if (type == null) {
            Class enclosingtype = newFieldData.getEnclosingtype();
            if (enclosingtype != null) {
                type = cachedComponentTypes(enclosingtype);
            }
        }

        int level = newFieldData.level;

        if (fieldType != null) {
            if (returnTypeCount < itemTypeCount) {
                newFieldData.returnType = itemType;
            }

            if (type == null) {
                type = new ComponentType(newFieldData.returnType, fieldType);
                type = cachedComponentTypes(type);

            } else {
                type.add(fieldType);
            }

            if (newFieldData.returnType == Object.class) {
                newFieldData.returnType = fieldType;
            }

            return fieldType;
        }

        if (returnType != null) {
            Class comptype = returnType.getComponentType();
            if (comptype != null && !comptype.isInterface() && !Modifier.isAbstract(comptype.getModifiers())) {
                return comptype;
            }
        }

        if ((returnType != null && Map.class.isAssignableFrom(returnType))
                || (itemType != null && Map.class.isAssignableFrom(itemType))) {
            String className = ((Map<String, String>) obj).get(getJsonClassType());
            if (className != null && className.length() > 0) {
                try {
                    // figure out obj's class
                    fieldType = Class.forName(className);

                    if (type == null) {
                        if (newFieldData.returnType != fieldType) {
                            type = new ComponentType(newFieldData.returnType, fieldType);
                            type = cachedComponentTypes(type);
                        }

                    } else {
                        type.add(fieldType);
                    }
                    newFieldData.returnType = fieldType;

                    return fieldType;

                } catch (ClassNotFoundException e) {
                    // e.printStackTrace();
                }
            }

            if (returnTypeCount > 0 && !Map.class.isAssignableFrom(returnType)
                    && !Collection.class.isAssignableFrom(returnType) && returnType != Optional.class
                    && returnType != Object.class && !returnType.isArray()) {
                if (type != null) {
                    type.add(returnType);
                }

                return returnType;
            }

            if (type != null) {
                ComponentType componentType = type.getComponentType();
                while (componentType != null && componentType.getComponentType() != null && level > 1) {
                    componentType = componentType.getComponentType();
                    level--;
                }

                if (level == 1 && componentType != null && componentType.getClassType() != null) {
                    return componentType.getClassType();
                }

                Class[] ctypes = type.getComponentClassType();
                float MIN_MAX_COUNT = 20.0f;
                if (ctypes != null && ctypes.length > 0) {
                    int length = ctypes.length;

                    Map<String, R> map = (Map) obj;

                    Map<String, Class> lnames = new HashMap<>(); //names.stream().map(name -> name.toLowerCase()).collect(Collectors.toSet());
                    for (String name : map.keySet()) {
                        Object value = map.get(name);
                        if (value != null) {
                            lnames.put(name.toLowerCase(), map.get(name).getClass());
                        }
                    }
                    int maxIdx = -1;
                    float maxCount = 0.0f;
                    for (int i = 0; i < length; i++) {
                        Class ctype = ctypes[i];

                        Field[] fields = getFields(ctype);
                        if (fields != null && fields.length > 0) {
                            int count = 0;

                            for (Field field : fields) {
                                String name = field.getName().toLowerCase();
                                if (lnames.containsKey(name)) {
                                    count++;

                                    Class ftype = field.getType();
                                    Class mtype = lnames.get(name);
                                    if (ObjectUtil.isSameDataType(ftype, mtype)) {
                                        count++;
                                    }
                                }
                            }
                            float currentCount = count * 100.0f / fields.length;
                            if (currentCount > maxCount) {
                                maxCount = currentCount;
                                maxIdx = i;
                            } else if (maxIdx == -1 && ctype.isAssignableFrom(itemType)) {
                                maxIdx = i;
                            }
                        }
                    }

                    if (maxIdx > -1) {
                        newFieldData.returnType = ctypes[maxIdx];

                        return ctypes[maxIdx];
                    }

                    Set<Class> processed = new HashSet(Arrays.asList(ctypes));

                    // now try to locate it in all cachedComponentTypes
                    for (Entry<Class, ComponentType> entry : cachedComponentTypes.entrySet()) {
                        Class myMasterClass = entry.getKey();

                        if (myMasterClass != this.masterClass && entry.getValue() != null) {
                            ctypes = entry.getValue().getComponentClassType();
                            if (ctypes != null) {
                                length = ctypes.length;

                                maxCount = 0.0f;
                                for (int i = 0; i < length; i++) {
                                    Class ctype = ctypes[i];

                                    if (!processed.contains(ctype)) {
                                        Field[] fields = getFields(ctype);
                                        if (fields != null && fields.length > 0) {
                                            int count = 0;

                                            for (Field field : fields) {
                                                String name = field.getName();
                                                if (name != null) {
                                                    name = name.toLowerCase();
                                                    if (lnames.containsKey(name)) {
                                                        count++;

                                                        Class ftype = field.getType();
                                                        Class mtype = lnames.get(name);
                                                        if (ObjectUtil.isSameType(ftype, mtype)) {
                                                            count++;
                                                        }
                                                    }
                                                }
                                            }
                                            float currentCount = count * 100.0f / fields.length;
                                            if (currentCount > maxCount) {
                                                maxCount = currentCount;
                                                maxIdx = i;
                                            }
                                            //                                 else if (maxIdx == -1 && ctype.isAssignableFrom(itemType)) {
                                            //                                    maxIdx = i;
                                            //                                 }
                                        }
                                    }
                                }

                                if (maxIdx > -1 && maxCount > MIN_MAX_COUNT) {
                                    newFieldData.returnType = ctypes[maxIdx];

                                    type.add(ctypes[maxIdx]);

                                    return ctypes[maxIdx];
                                }

                                processed.addAll(Arrays.asList(ctypes));
                            }
                        }
                    }

                    if (ctypes != null && ctypes.length == 1) {
                        return ctypes[0];
                    }
                }

            }

        } else if ((returnType != null
                && (Collection.class.isAssignableFrom(returnType) || returnType.isArray()))
                || (itemType != null && (Collection.class.isAssignableFrom(itemType) || itemType.isArray()))) {

            //  && ComponentType.class.isAssignableFrom(erasedType.getClass())
            if (type != null) {

                ComponentType componentType = type.getComponentType();
                while (componentType != null && componentType.getComponentType() != null && level > 1) {
                    componentType = componentType.getComponentType();
                    level--;
                }

                if (level == 1 && componentType != null && componentType.getClassType() != null) {
                    return componentType.getClassType();
                }

                Class[] ctypes = type.getComponentClassType();

                if (ctypes != null && ctypes.length > 0) {
                    if (ctypes.length == 1) {
                        Class cmptype = ctypes[0].getComponentType();
                        if (cmptype != null
                                && (cmptype.isArray() || Collection.class.isAssignableFrom(cmptype))) {
                            type.add(cmptype);
                        }
                        //if (!ObjectUtil.isBasicDataType(ctypes[0])) {
                        return ctypes[0];
                        //}
                    }

                    int length = ctypes.length;
                    int depth = CollectionArrayTypeGuesser.getDepth(obj);
                    Class baseType = CollectionArrayTypeGuesser.getBaseType(obj);
                    Class possible = null;
                    for (int i = 0; i < length; i++) {
                        Class ctype = ctypes[i];

                        if (ctype.isArray() || Collection.class.isAssignableFrom(ctype)) {
                            //Class compType = CollectionArrayTypeGuesser.guessElementType(collection, ctype, getJsonClassType());
                            int typedepth = CollectionArrayTypeGuesser.getDepth(ctype);
                            Class cbaseType = CollectionArrayTypeGuesser.getBaseType(ctype);
                            if (depth == typedepth) {
                                if (ObjectUtil.isSameType(baseType, cbaseType)) {
                                    Class cmptype = ctype.getComponentType();
                                    if (cmptype.isArray() || Collection.class.isAssignableFrom(cmptype)) {
                                        type.add(cmptype);
                                    }

                                    return ctype;

                                } else if (itemType.isAssignableFrom(ctype)
                                        || ctype.isAssignableFrom(itemType)) {
                                    possible = ctype;
                                }
                            }
                        }

                    }

                    if (possible != null) {
                        return possible;
                    }

                }

            }

        }
        //         else if (StringUtil.isNumeric(obj.toString())) {
        //            if (obj.toString().contains(".")) {
        //               return Double.class;
        //            } else {
        //               return Integer.class;
        //            }
        //         }

        if (type != null && type.getComponentType() != null) {
            Class classType = type.getComponentType().getClassType();
            if (classType != null && ObjectUtil.isSameDataType(classType, itemType)) {
                return classType;
            }
        }

        return itemType;
    }
}

From source file:org.dasein.persist.PersistentCache.java

@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object mapValue(String fieldName, Object dataStoreValue, Class<?> toType, ParameterizedType ptype)
        throws PersistenceException {
    LookupDelegate delegate = getLookupDelegate(fieldName);

    if (dataStoreValue != null && delegate != null && !delegate.validate(dataStoreValue.toString())) {
        throw new PersistenceException("Value " + dataStoreValue + " for " + fieldName + " is not valid.");
    }//from  w w w .  ja v a  2s  .  co m
    try {
        if (toType.equals(String.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof String)) {
                dataStoreValue = dataStoreValue.toString();
            }
        } else if (Enum.class.isAssignableFrom(toType)) {
            if (dataStoreValue != null) {
                Enum e = Enum.valueOf((Class<? extends Enum>) toType, dataStoreValue.toString());

                dataStoreValue = e;
            }
        } else if (toType.equals(Boolean.class) || toType.equals(boolean.class)) {
            if (dataStoreValue == null) {
                dataStoreValue = false;
            } else if (!(dataStoreValue instanceof Boolean)) {
                if (Number.class.isAssignableFrom(dataStoreValue.getClass())) {
                    dataStoreValue = (((Number) dataStoreValue).intValue() != 0);
                } else {
                    dataStoreValue = (dataStoreValue.toString().trim().equalsIgnoreCase("true")
                            || dataStoreValue.toString().trim().equalsIgnoreCase("y"));
                }
            }
        } else if (Number.class.isAssignableFrom(toType) || toType.equals(byte.class)
                || toType.equals(short.class) || toType.equals(long.class) || toType.equals(int.class)
                || toType.equals(float.class) || toType.equals(double.class)) {
            if (dataStoreValue == null) {
                if (toType.equals(int.class) || toType.equals(short.class) || toType.equals(long.class)) {
                    dataStoreValue = 0;
                } else if (toType.equals(float.class) || toType.equals(double.class)) {
                    dataStoreValue = 0.0f;
                }
            } else if (toType.equals(Number.class)) {
                if (!(dataStoreValue instanceof Number)) {
                    if (dataStoreValue instanceof String) {
                        try {
                            dataStoreValue = Double.parseDouble((String) dataStoreValue);
                        } catch (NumberFormatException e) {
                            throw new PersistenceException("Unable to map " + fieldName + " as " + toType
                                    + " using " + dataStoreValue);
                        }
                    } else if (dataStoreValue instanceof Boolean) {
                        dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                    } else {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                }
            } else if (toType.equals(Integer.class) || toType.equals(int.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Integer)) {
                        dataStoreValue = ((Number) dataStoreValue).intValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Integer.parseInt((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Long.class) || toType.equals(long.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Long)) {
                        dataStoreValue = ((Number) dataStoreValue).longValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Long.parseLong((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1L : 0L);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Byte.class) || toType.equals(byte.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Byte)) {
                        dataStoreValue = ((Number) dataStoreValue).byteValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Byte.parseByte((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Short.class) || toType.equals(short.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Short)) {
                        dataStoreValue = ((Number) dataStoreValue).shortValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Short.parseShort((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1 : 0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Double.class) || toType.equals(double.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Double)) {
                        dataStoreValue = ((Number) dataStoreValue).doubleValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Double.parseDouble((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1.0 : 0.0);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(Float.class) || toType.equals(float.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof Float)) {
                        dataStoreValue = ((Number) dataStoreValue).floatValue();
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = Float.parseFloat((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = (((Boolean) dataStoreValue) ? 1.0f : 0.0f);
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(BigDecimal.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof BigDecimal)) {
                        if (dataStoreValue instanceof BigInteger) {
                            dataStoreValue = new BigDecimal((BigInteger) dataStoreValue);
                        } else {
                            dataStoreValue = BigDecimal.valueOf(((Number) dataStoreValue).doubleValue());
                        }
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = new BigDecimal((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0));
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (toType.equals(BigInteger.class)) {
                if (dataStoreValue instanceof Number) {
                    if (!(dataStoreValue instanceof BigInteger)) {
                        if (dataStoreValue instanceof BigDecimal) {
                            dataStoreValue = ((BigDecimal) dataStoreValue).toBigInteger();
                        } else {
                            dataStoreValue = BigInteger.valueOf(((Number) dataStoreValue).longValue());
                        }
                    }
                } else if (dataStoreValue instanceof String) {
                    try {
                        dataStoreValue = new BigDecimal((String) dataStoreValue);
                    } catch (NumberFormatException e) {
                        throw new PersistenceException(
                                "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                    }
                } else if (dataStoreValue instanceof Boolean) {
                    dataStoreValue = new BigDecimal((((Boolean) dataStoreValue) ? 1.0 : 0.0));
                } else {
                    throw new PersistenceException(
                            "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
                }
            } else if (dataStoreValue != null) {
                logger.error("Type of dataStoreValue=" + dataStoreValue.getClass());
                throw new PersistenceException(
                        "Unable to map " + fieldName + " as " + toType + " using " + dataStoreValue);
            }
        } else if (toType.equals(Locale.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof Locale)) {
                String[] parts = dataStoreValue.toString().split("_");

                if (parts != null && parts.length > 1) {
                    dataStoreValue = new Locale(parts[0], parts[1]);
                } else {
                    dataStoreValue = new Locale(parts[0]);
                }
            }
        } else if (Measured.class.isAssignableFrom(toType)) {
            if (dataStoreValue != null && ptype != null) {
                if (Number.class.isAssignableFrom(dataStoreValue.getClass())) {
                    Constructor<? extends Measured> constructor = null;
                    double value = ((Number) dataStoreValue).doubleValue();

                    for (Constructor<?> c : toType.getDeclaredConstructors()) {
                        Class[] args = c.getParameterTypes();

                        if (args != null && args.length == 2 && Number.class.isAssignableFrom(args[0])
                                && UnitOfMeasure.class.isAssignableFrom(args[1])) {
                            constructor = (Constructor<? extends Measured>) c;
                            break;
                        }
                    }
                    if (constructor == null) {
                        throw new PersistenceException("Unable to map with no proper constructor");
                    }
                    dataStoreValue = constructor.newInstance(value,
                            ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance());
                } else if (!(dataStoreValue instanceof Measured)) {
                    try {
                        dataStoreValue = Double.parseDouble(dataStoreValue.toString());
                    } catch (NumberFormatException e) {
                        Method method = null;

                        for (Method m : toType.getDeclaredMethods()) {
                            if (Modifier.isStatic(m.getModifiers()) && m.getName().equals("valueOf")) {
                                if (m.getParameterTypes().length == 1
                                        && m.getParameterTypes()[0].equals(String.class)) {
                                    method = m;
                                    break;
                                }
                            }
                        }
                        if (method == null) {
                            throw new PersistenceException("Don't know how to map " + dataStoreValue + " to "
                                    + toType + "<" + ptype + ">");
                        }
                        dataStoreValue = method.invoke(null, dataStoreValue.toString());
                    }
                }
                // just because we converted it to a measured object above doesn't mean
                // we have the unit of measure right
                if (dataStoreValue instanceof Measured) {
                    UnitOfMeasure targetUom = (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0])
                            .newInstance();

                    if (!(((Measured) dataStoreValue).getUnitOfMeasure()).equals(targetUom)) {
                        dataStoreValue = ((Measured) dataStoreValue).convertTo(
                                (UnitOfMeasure) ((Class<?>) ptype.getActualTypeArguments()[0]).newInstance());
                    }
                }
            }
        } else if (toType.equals(UUID.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof UUID)) {
                dataStoreValue = UUID.fromString(dataStoreValue.toString());
            }
        } else if (toType.equals(TimeZone.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof TimeZone)) {
                dataStoreValue = TimeZone.getTimeZone(dataStoreValue.toString());
            }
        } else if (toType.equals(Currency.class)) {
            if (dataStoreValue != null && !(dataStoreValue instanceof Currency)) {
                dataStoreValue = Currency.getInstance(dataStoreValue.toString());
            }
        } else if (toType.isArray()) {
            Class<?> t = toType.getComponentType();

            if (dataStoreValue == null) {
                dataStoreValue = Array.newInstance(t, 0);
            } else if (dataStoreValue instanceof JSONArray) {
                JSONArray arr = (JSONArray) dataStoreValue;

                if (long.class.isAssignableFrom(t)) {
                    long[] replacement = (long[]) Array.newInstance(long.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Long) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (int.class.isAssignableFrom(t)) {
                    int[] replacement = (int[]) Array.newInstance(int.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Integer) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (float.class.isAssignableFrom(t)) {
                    float[] replacement = (float[]) Array.newInstance(float.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Float) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (double.class.isAssignableFrom(t)) {
                    double[] replacement = (double[]) Array.newInstance(double.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Double) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else if (boolean.class.isAssignableFrom(t)) {
                    boolean[] replacement = (boolean[]) Array.newInstance(boolean.class, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = (Boolean) mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                } else {
                    Object[] replacement = (Object[]) Array.newInstance(t, arr.length());

                    for (int i = 0; i < arr.length(); i++) {
                        replacement[i] = mapValue(fieldName, arr.get(i), t, null);
                    }
                    dataStoreValue = replacement;
                }
            } else if (!dataStoreValue.getClass().isArray()) {
                logger.error("Unable to map data store type " + dataStoreValue.getClass().getName() + " to "
                        + toType.getName());
                logger.error("Value of " + fieldName + "=" + dataStoreValue);
                throw new PersistenceException("Data store type=" + dataStoreValue.getClass().getName());
            }
        } else if (dataStoreValue != null && !toType.isAssignableFrom(dataStoreValue.getClass())) {
            Annotation[] alist = toType.getDeclaredAnnotations();
            boolean autoJSON = false;

            for (Annotation a : alist) {
                if (a instanceof AutoJSON) {
                    autoJSON = true;
                }
            }
            if (autoJSON) {
                dataStoreValue = autoDeJSON(toType, (JSONObject) dataStoreValue);
            } else {
                try {
                    Method m = toType.getDeclaredMethod("valueOf", JSONObject.class);

                    dataStoreValue = m.invoke(null, dataStoreValue);
                } catch (NoSuchMethodException ignore) {
                    try {
                        Method m = toType.getDeclaredMethod("valueOf", String.class);

                        if (m != null) {
                            dataStoreValue = m.invoke(null, dataStoreValue.toString());
                        } else {
                            throw new PersistenceException(
                                    "No valueOf() field in " + toType + " for mapping " + fieldName);
                        }
                    } catch (NoSuchMethodException e) {
                        throw new PersistenceException("No valueOf() field in " + toType + " for mapping "
                                + fieldName + " with " + dataStoreValue + ": ("
                                + dataStoreValue.getClass().getName() + " vs " + toType.getName() + ")");
                    }
                }
            }
        }
    } catch (Exception e) {
        String err = "Error mapping field in " + toType + " for " + fieldName + ": " + e.getMessage();
        logger.error(err, e);
        throw new PersistenceException();
    }
    return dataStoreValue;
}

From source file:org.exolab.castor.xml.StartElementProcessor.java

public void compute(String name, String namespace, AttributeSet atts) throws SAXException {

    UnmarshalState state = null;/*from   www. j a va  2  s.c om*/
    String xmlSpace = null;

    // -- handle special atts
    if (atts != null) {
        // -- xml:space
        xmlSpace = atts.getValue(UnmarshalHandler.XML_SPACE, Namespaces.XML_NAMESPACE);
        if (xmlSpace == null) {
            xmlSpace = atts.getValue(UnmarshalHandler.XML_SPACE_WITH_PREFIX, "");
        }
    }

    if (_unmarshalHandler.getStateStack().isEmpty()) {
        // -- Initialize since this is the first element
        _unmarshalHandler.processFirstElement(name, namespace, atts, xmlSpace);
        return;
    } // --rootElement

    // -- get MarshalDescriptor for the given element
    UnmarshalState parentState = _unmarshalHandler.getStateStack().getLastState();

    // Test if we can accept the field in the parentState
    // in case the parentState fieldDesc is a container
    // -- This following logic tests to see if we are in a
    // -- container and we need to close out the container
    // -- before proceeding:
    boolean canAccept = false;
    while ((parentState.getFieldDescriptor() != null)
            && (parentState.getFieldDescriptor().isContainer() && !canAccept)) {
        XMLClassDescriptor tempClassDesc = parentState.getClassDescriptor();

        // -- Find ClassDescriptor for Parent
        if (tempClassDesc == null) {
            tempClassDesc = (XMLClassDescriptor) parentState.getFieldDescriptor().getClassDescriptor();
            if (tempClassDesc == null)
                tempClassDesc = _unmarshalHandler.getClassDescriptor(parentState.getObject().getClass());
        }

        canAccept = tempClassDesc.canAccept(name, namespace, parentState.getObject());

        if (!canAccept) {
            // -- Does container class even handle this field?
            if (tempClassDesc.getFieldDescriptor(name, namespace, NodeType.Element) != null) {
                if (!parentState.getFieldDescriptor().isMultivalued()) {
                    String error = MessageFormat.format(
                            resourceBundle.getString("unmarshalHandler.error.container.full"),
                            new Object[] { tempClassDesc.getJavaClass().getName(), name });
                    ValidationException vx = new ValidationException(error);
                    throw new SAXException(vx);
                }
            }
            _unmarshalHandler.endElement(parentState.getElementName());
            parentState = _unmarshalHandler.getStateStack().getLastState();
        }
        tempClassDesc = null;
    }

    // -- create new state object
    state = new UnmarshalState();
    state.setElementName(name);
    state.setParent(parentState);

    if (xmlSpace != null) {
        state.setWhitespacePreserving(UnmarshalHandler.PRESERVE.equals(xmlSpace));
    } else {
        state.setWhitespacePreserving(parentState.isWhitespacePreserving());
    }

    _unmarshalHandler.getStateStack().pushState(state);

    // -- make sure we should proceed
    if (parentState.getObject() == null) {
        if (!parentState.isWrapper()) {
            return;
        }
    }

    Class cls = null;

    // -- Find ClassDescriptor for Parent
    XMLClassDescriptor classDesc = parentState.getClassDescriptor();
    if (classDesc == null) {
        classDesc = (XMLClassDescriptor) parentState.getFieldDescriptor().getClassDescriptor();
        if (classDesc == null)
            classDesc = _unmarshalHandler.getClassDescriptor(parentState.getObject().getClass());
    } else {
        // classDesc.resetElementCount();
    }

    // ----------------------------------------------------/
    // - Find FieldDescriptor associated with the element -/
    // ----------------------------------------------------/

    // -- A reference to the FieldDescriptor associated
    // -- the the "current" element
    XMLFieldDescriptor descriptor = null;

    // -- inherited class descriptor
    // -- (only needed if descriptor cannot be found directly)
    XMLClassDescriptor cdInherited = null;

    // -- loop through stack and find correct descriptor
    // int pIdx = _stateInfo.size() - 2; //-- index of parentState
    UnmarshalState targetState = parentState;
    String path = "";
    int count = 0;
    boolean isWrapper = false;
    XMLClassDescriptor oldClassDesc = classDesc;
    while (descriptor == null) {

        // -- NOTE (kv 20050228):
        // -- we need to clean this code up, I made this
        // -- fix to make sure the correct descriptor which
        // -- matches the location path is used
        if (path.length() > 0) {
            String tmpName = path + "/" + name;
            descriptor = classDesc.getFieldDescriptor(tmpName, namespace, NodeType.Element);
        }
        // -- End Patch

        if (descriptor == null) {
            descriptor = classDesc.getFieldDescriptor(name, namespace, NodeType.Element);
        }

        // -- Namespace patch, should be moved to XMLClassDescriptor, but
        // -- this is the least intrusive patch at the moment. kv - 20030423
        if ((descriptor != null) && (!descriptor.isContainer())) {
            if (StringUtils.isNotEmpty(namespace)) {
                if (!MarshalFramework.namespaceEquals(namespace, descriptor.getNameSpaceURI())) {
                    // -- if descriptor namespace is not null, then we must
                    // -- have a namespace match, so set descriptor to null,
                    // -- or if descriptor is not a wildcard we can also
                    // -- set to null.
                    if ((descriptor.getNameSpaceURI() != null) || (!descriptor.matches("*"))) {
                        descriptor = null;
                    }

                }
            }
        }
        // -- end namespace patch

        /*
         * If descriptor is null, we need to handle possible inheritence, which might not be described
         * in the current ClassDescriptor. This can be a slow process...for speed use the match
         * attribute of the xml element in the mapping file. This logic might not be completely
         * necessary, and perhaps we should remove it.
         */
        // handle multiple level locations (where count > 0) (CASTOR-1039)
        // if ((descriptor == null) && (count == 0) &&
        // (!targetState.wrapper)) {
        if ((descriptor == null) && (!targetState.isWrapper())) {
            MarshalFramework.InheritanceMatch[] matches = null;
            try {
                matches = _unmarshalHandler.searchInheritance(name, namespace, classDesc); // TODO:
                                                                                           // Joachim,
                                                                                           // _cdResolver);
            } catch (MarshalException rx) {
                // -- TODO:
            }
            if (matches.length != 0) {
                InheritanceMatch match = null;
                // It may be the case that this class descriptor can
                // appear under multiple parent field descriptors. Look
                // for the first match whose parent file descriptor XML
                // name matches the name of the element we are under
                for (int i = 0; i < matches.length; i++) {
                    if (parentState.getElementName().equals(matches[i].parentFieldDesc.getLocationPath())) {
                        match = matches[i];
                        break;
                    }
                }
                if (match == null)
                    match = matches[0];
                descriptor = match.parentFieldDesc;
                cdInherited = match.inheritedClassDesc;
                break; // -- found
            }
            /* */

            // handle multiple level locations (where count > 0)
            // (CASTOR-1039)
            // isWrapper = (isWrapper || hasFieldsAtLocation(name,
            // classDesc));
            StringBuilder tmpLocation = new StringBuilder();
            if (count > 0) {
                tmpLocation.append(path).append('/');
            }
            tmpLocation.append(name);
            isWrapper = (isWrapper || MarshalFramework.hasFieldsAtLocation(tmpLocation.toString(), classDesc));
        } else if (descriptor != null) {
            String tmpPath = descriptor.getLocationPath();
            if (path.equals(StringUtils.defaultString(tmpPath)))
                break; // -- found
            descriptor = null; // -- not found, try again
        } else {
            isWrapper = (isWrapper || MarshalFramework.hasFieldsAtLocation(path + '/' + name, classDesc));
        }

        // -- Make sure there are more parent classes on stack
        // -- otherwise break, since there is nothing to do
        // if (pIdx == 0) break;
        if (targetState == _unmarshalHandler.getTopState())
            break;

        // -- adjust name and try parent
        if (count == 0)
            path = targetState.getElementName();
        else {
            path = targetState.getElementName() + '/' + path;
        }

        // -- get
        // --pIdx;
        // targetState = (UnmarshalState)_stateInfo.elementAt(pIdx);
        targetState = targetState.getParent();
        classDesc = targetState.getClassDescriptor();
        count++;
    }

    if (descriptor != null && _unmarshalHandler.isValidating()
            && !_unmarshalHandler.getInternalContext().getLenientSequenceOrder()) {
        try {
            classDesc.checkDescriptorForCorrectOrderWithinSequence(descriptor, parentState, name);
        } catch (ValidationException e) {
            throw new SAXException(e);
        }
    }

    // -- The field descriptor is still null, we face a problem
    if (descriptor == null) {

        // -- reset classDesc
        classDesc = oldClassDesc;

        // -- isWrapper?
        if (isWrapper) {
            state.setClassDescriptor(new XMLClassDescriptorImpl(ContainerElement.class, name));
            state.setWrapper(true);
            if (LOG.isDebugEnabled()) {
                LOG.debug("wrapper-element: " + name);
            }
            // -- process attributes
            _unmarshalHandler.processWrapperAttributes(atts);
            return;
        }

        String error = MessageFormat.format(
                resourceBundle.getString("unmarshalHandler.error.find.field.descriptor"),
                new Object[] { name, classDesc.getXMLName() });

        // -- unwrap classDesc, if necessary, for the check
        // -- Introspector.introspected done below
        if (classDesc instanceof InternalXMLClassDescriptor) {
            classDesc = ((InternalXMLClassDescriptor) classDesc).getClassDescriptor();
        }

        // -- If we are skipping elements that have appeared in the XML but
        // for
        // -- which we have no mapping, increase the ignore depth counter
        // and return
        boolean lenientElementStrictnessForIntrospection = _unmarshalHandler.getInternalContext()
                .getBooleanProperty(XMLProperties.LENIENT_INTROSPECTED_ELEMENT_STRICTNESS).booleanValue();
        // checks if the element could be skipped
        if (_unmarshalHandler.getStrictElementHandler().skipStartElementIgnoringDepth()) {
            // -- remove the StateInfo we just added
            _unmarshalHandler.getStateStack().removeLastState();
            // drop Namespace instance as well
            _unmarshalHandler.getNamespaceHandling().removeCurrentNamespaceInstance();
            if (LOG.isDebugEnabled()) {
                String debug = MessageFormat.format(
                        resourceBundle.getString("unmarshalHandler.log.debug.ignore.extra.element"),
                        new Object[] { error });
                LOG.debug(debug);
            }
            return;
        }
        // if we have no field descriptor and
        // the class descriptor was introspected
        // just log it
        else if (lenientElementStrictnessForIntrospection && Introspector.introspected(classDesc)) {
            LOG.warn(error);
            return;
        }
        // -- otherwise report error since we cannot find a suitable
        // -- descriptor
        else {
            throw new SAXException(error);
        }
    } // -- end null descriptor

    // / DEBUG: System.out.println("path: " + path);

    // -- Save targetState (used in endElement)
    if (targetState != parentState) {
        state.setTargetState(targetState);
        parentState = targetState; // -- reassign
    }

    Object object = parentState.getObject();
    // --container support
    if (descriptor.isContainer()) {
        // create a new state to set the container as the object
        // don't save the current state, it will be recreated later

        if (LOG.isDebugEnabled()) {
            LOG.debug("#container: " + descriptor.getFieldName());
        }

        // -- clear current state and re-use for the container
        state.clear();
        // -- inherit whitespace preserving from the parentState
        state.setWhitespacePreserving(parentState.isWhitespacePreserving());
        state.setParent(parentState);

        // here we can hard-code a name or take the field name
        state.setElementName(descriptor.getFieldName());
        state.setFieldDescriptor(descriptor);
        state.setClassDescriptor((XMLClassDescriptor) descriptor.getClassDescriptor());
        Object containerObject = null;

        // 1-- the container is not multivalued (not a collection)
        if (!descriptor.isMultivalued()) {
            // Check if the container object has already been instantiated
            FieldHandler handler = descriptor.getHandler();
            containerObject = handler.getValue(object);
            if (containerObject != null) {
                if (state.getClassDescriptor() != null) {
                    if (state.getClassDescriptor().canAccept(name, namespace, containerObject)) {
                        // remove the descriptor from the used list
                        parentState.markAsNotUsed(descriptor);
                    }
                } else {
                    // remove the descriptor from the used list
                    parentState.markAsNotUsed(descriptor);
                }
            } else {
                containerObject = handler.newInstance(object);
            }

        }
        // 2-- the container is multivalued
        else {
            Class containerClass = descriptor.getFieldType();
            try {
                containerObject = containerClass.newInstance();
            } catch (Exception ex) {
                throw new SAXException(ex);
            }
        }
        state.setObject(containerObject);
        state.setType(containerObject.getClass());

        // we need to recall startElement()
        // so that we can find a more appropriate descriptor in for the
        // given name
        _unmarshalHandler.getNamespaceHandling().createNamespace();
        _unmarshalHandler.startElementProcessing(name, namespace, atts);
        return;
    }
    // --End of the container support

    // -- Find object type and create new Object of that type
    state.setFieldDescriptor(descriptor);

    /*
     * <update> we need to add this code back in, to make sure we have proper access rights.
     * 
     * if (!descriptor.getAccessRights().isWritable()) { if (debug) { buf.setLength(0); buf.append(
     * "The field for element '"); buf.append(name); buf.append("' is read-only.");
     * message(buf.toString()); } return; }
     */

    // -- Find class to instantiate
    // -- check xml names to see if we should look for a more specific
    // -- ClassDescriptor, otherwise just use the one found in the
    // -- descriptor
    classDesc = null;
    if (cdInherited != null)
        classDesc = cdInherited;
    else if (!name.equals(descriptor.getXMLName()))
        classDesc = _unmarshalHandler.resolveByXMLName(name, namespace, null);

    if (classDesc == null)
        classDesc = (XMLClassDescriptor) descriptor.getClassDescriptor();
    FieldHandler handler = descriptor.getHandler();
    boolean useHandler = true;

    try {

        // -- Get Class type...first use ClassDescriptor,
        // -- since it could be more specific than
        // -- the FieldDescriptor
        if (classDesc != null) {
            cls = classDesc.getJavaClass();

            // -- XXXX This is a hack I know...but we
            // -- XXXX can't use the handler if the field
            // -- XXXX types are different
            if (descriptor.getFieldType() != cls) {
                state.setDerived(true);
            }
        } else {
            cls = descriptor.getFieldType();
        }

        // -- This *shouldn't* happen, but a custom implementation
        // -- could return null in the XMLClassDesctiptor#getJavaClass
        // -- or XMLFieldDescriptor#getFieldType. If so, just replace
        // -- with java.lang.Object.class (basically "anyType").
        if (cls == null) {
            cls = java.lang.Object.class;
        }

        // Retrieving the xsi:type attribute, if present
        String currentPackage = _unmarshalHandler.getJavaPackage(parentState.getType());
        String instanceType = _unmarshalHandler.getInstanceType(atts, currentPackage);
        if (instanceType != null) {

            Class instanceClass = null;
            try {

                XMLClassDescriptor instanceDesc = _unmarshalHandler.getClassDescriptor(instanceType,
                        _unmarshalHandler.getClassLoader());

                boolean loadClass = true;

                if (instanceDesc != null) {
                    instanceClass = instanceDesc.getJavaClass();
                    classDesc = instanceDesc;
                    if (instanceClass != null) {
                        loadClass = (!instanceClass.getName().equals(instanceType));
                    }
                }

                if (loadClass) {
                    instanceClass = _unmarshalHandler.loadClass(instanceType, null);
                    // the FieldHandler can be either an XMLFieldHandler
                    // or a FieldHandlerImpl
                    FieldHandler tempHandler = descriptor.getHandler();

                    boolean collection = false;
                    if (tempHandler instanceof FieldHandlerImpl) {
                        collection = ((FieldHandlerImpl) tempHandler).isCollection();
                    } else {
                        collection = Introspector.isCollection(instanceClass);
                    }

                    if ((!collection) && !cls.isAssignableFrom(instanceClass)) {
                        if (!MarshalFramework.isPrimitive(cls)) {
                            String err = MessageFormat.format(
                                    resourceBundle.getString("unmarshalHandler.error.not.subclass"),
                                    new Object[] { instanceClass.getName(), cls.getName() });
                            throw new SAXException(err);
                        }
                    }
                }
                cls = instanceClass;
                useHandler = false;
            } catch (Exception ex) {
                String err = MessageFormat.format(
                        resourceBundle.getString("unmarshalHandler.error.unable.instantiate.exception"),
                        new Object[] { instanceType, ex.getMessage() });
                throw new SAXException(err, ex);
            }

        }

        // -- Handle ArrayHandler
        if (cls == Object.class) {
            if (parentState.getObject() instanceof ArrayHandler)
                cls = ((ArrayHandler) parentState.getObject()).componentType();
        }

        // -- Handle support for "Any" type

        if (cls == Object.class) {
            Class pClass = parentState.getType();
            ClassLoader loader = pClass.getClassLoader();
            // -- first look for a descriptor based
            // -- on the XML name
            classDesc = _unmarshalHandler.resolveByXMLName(name, namespace, loader);
            // -- if null, create classname, and try resolving
            String cname = null;
            if (classDesc == null) {
                // -- create class name
                cname = _unmarshalHandler.getJavaNaming().toJavaClassName(name);
                classDesc = _unmarshalHandler.getClassDescriptor(cname, loader);
            }
            // -- if still null, try using parents package
            if (classDesc == null) {
                // -- use parent to get package information
                String pkg = pClass.getName();
                int idx = pkg.lastIndexOf('.');
                if (idx > 0) {
                    pkg = pkg.substring(0, idx + 1);
                    cname = pkg + cname;
                    classDesc = _unmarshalHandler.getClassDescriptor(cname, loader);
                }
            }

            if (classDesc != null) {
                cls = classDesc.getJavaClass();
                useHandler = false;
            } else {
                // we are dealing with an AnyNode
                state.setObject(_unmarshalHandler.getAnyNodeHandler().commonStartElement(name, namespace,
                        state.isWhitespacePreserving()));
                state.setType(cls);
                return;
            }
        }

        boolean byteArray = false;
        if (cls.isArray())
            byteArray = (cls.getComponentType() == Byte.TYPE);

        // -- check for immutable
        if (MarshalFramework.isPrimitive(cls) || descriptor.isImmutable() || byteArray) {
            state.setObject(null);
            state.setPrimitiveOrImmutable(true);
            // -- handle immutable types, such as java.util.Locale
            if (descriptor.isImmutable()) {
                if (classDesc == null)
                    classDesc = _unmarshalHandler.getClassDescriptor(cls);
                state.setClassDescriptor(classDesc);
                Arguments args = _unmarshalHandler.processConstructorArgs(atts, classDesc);
                if (args != null && args.size() > 0) {
                    state.setConstructorArguments(args);
                }
            }
        } else {
            if (classDesc == null)
                classDesc = _unmarshalHandler.getClassDescriptor(cls);

            // -- XXXX should remove this test once we can
            // -- XXXX come up with a better solution
            if ((!state.isDerived()) && useHandler) {

                boolean create = true;
                if (_unmarshalHandler.isReuseObjects()) {
                    state.setObject(handler.getValue(parentState.getObject()));
                    create = (state.getObject() == null);
                }
                if (create) {
                    Arguments args = _unmarshalHandler.processConstructorArgs(atts, classDesc);
                    if ((args.getValues() != null) && (args.getValues().length > 0)) {
                        if (handler instanceof ExtendedFieldHandler) {
                            ExtendedFieldHandler efh = (ExtendedFieldHandler) handler;
                            state.setObject(efh.newInstance(parentState.getObject(), args.getValues()));
                        } else {
                            String err = resourceBundle
                                    .getString("unmarshalHandler.error.constructor.arguments");
                            throw new SAXException(err);
                        }
                    } else {
                        state.setObject(handler.newInstance(parentState.getObject()));
                    }
                }
            }
            // -- reassign class in case there is a conflict
            // -- between descriptor#getFieldType and
            // -- handler#newInstance...I should hope not, but
            // -- who knows
            if (state.getObject() != null) {
                cls = state.getObject().getClass();
                if (classDesc != null) {
                    if (classDesc.getJavaClass() != cls) {
                        classDesc = null;
                    }
                }
            } else {
                try {
                    if (cls.isArray()) {
                        state.setObject(new ArrayHandler(cls.getComponentType()));
                        cls = ArrayHandler.class;
                    } else {
                        Arguments args = _unmarshalHandler.processConstructorArgs(atts, classDesc);
                        state.setObject(_unmarshalHandler.createInstance(cls, args));
                        // state.object = _class.newInstance();
                    }
                } catch (java.lang.Exception ex) {
                    String err = MessageFormat.format(
                            resourceBundle.getString("unmarshalHandler.error.unable.instantiate.exception"),
                            new Object[] { _unmarshalHandler.className(cls), ex.getMessage() });
                    throw new SAXException(err, ex);
                }
            }
        }
        state.setType(cls);
    } catch (java.lang.IllegalStateException ise) {
        LOG.error(ise.toString());
        throw new SAXException(ise);
    }

    // -- At this point we should have a new object, unless
    // -- we are dealing with a primitive type, or a special
    // -- case such as byte[]
    if (classDesc == null) {
        classDesc = _unmarshalHandler.getClassDescriptor(cls);
    }
    state.setClassDescriptor(classDesc);

    if ((state.getObject() == null) && (!state.isPrimitiveOrImmutable())) {
        String err = MessageFormat.format(resourceBundle.getString("unmarshalHandler.error.unable.unmarshal"),
                new Object[] { name, _unmarshalHandler.className(cls) });
        throw new SAXException(err);
    }

    // -- assign object, if incremental

    if (descriptor.isIncremental()) {
        if (LOG.isDebugEnabled()) {
            String debug = MessageFormat.format(
                    resourceBundle.getString("unmarshalHandler.log.debug.process.incrementally"),
                    new Object[] { name });
            LOG.debug(debug);
        }
        try {
            handler.setValue(parentState.getObject(), state.getObject());
        } catch (java.lang.IllegalStateException ise) {
            String err = MessageFormat.format(
                    resourceBundle.getString("unmarshalHandler.error.unable.add.element"),
                    new Object[] { name, parentState.getFieldDescriptor().getXMLName(), ise.getMessage() });
            throw new SAXException(err, ise);
        }
    }

    if (state.getObject() != null) {
        // --The object has just been initialized
        // --notify the listener
        Object stateObject = state.getObject();
        Object parentObject = (state.getParent() == null) ? null : state.getParent().getObject();
        _unmarshalHandler.getDelegateUnmarshalListener().initialized(stateObject, parentObject);
        _unmarshalHandler.processAttributes(atts, classDesc);
        _unmarshalHandler.getDelegateUnmarshalListener().attributesProcessed(stateObject, parentObject);
        _unmarshalHandler.getNamespaceHandling().processNamespaces(classDesc,
                _unmarshalHandler.getStateStack().getLastState().getObject());
    } else if ((state.getType() != null) && (!state.isPrimitiveOrImmutable())) {
        if (atts != null) {
            _unmarshalHandler.processWrapperAttributes(atts);
            String warn = MessageFormat.format(
                    resourceBundle.getString("unmarshalHandler.log.warn.process.attribute.as.location"),
                    new Object[] { name });
            LOG.warn(warn);
        }
    } else {
        // -- check for special attributes, such as xsi:nil
        if (atts != null) {
            String nil = atts.getValue(MarshalFramework.NIL_ATTR, MarshalFramework.XSI_NAMESPACE);
            state.setNil("true".equals(nil));
            _unmarshalHandler.processWrapperAttributes(atts);
        }
    }
}

From source file:com.clark.func.Functions.java

/**
 * <p>//from   w w  w.  ja v a2  s .co m
 * Checks if the subject type may be implicitly cast to the target generic
 * array type following the Java generics rules.
 * </p>
 * 
 * @param type
 *            the subject type to be assigned to the target type
 * @param toGenericArrayType
 *            the target generic array type
 * @return true if <code>type</code> is assignable to
 *         <code>toGenericArrayType</code>.
 */
private static boolean isAssignable(Type type, GenericArrayType toGenericArrayType,
        Map<TypeVariable<?>, Type> typeVarAssigns) {
    if (type == null) {
        return true;
    }

    // only a null type can be assigned to null type which
    // would have cause the previous to return true
    if (toGenericArrayType == null) {
        return false;
    }

    // all types are assignable to themselves
    if (toGenericArrayType.equals(type)) {
        return true;
    }

    Type toComponentType = toGenericArrayType.getGenericComponentType();

    if (type instanceof Class<?>) {
        Class<?> cls = (Class<?>) type;

        // compare the component types
        return cls.isArray() && isAssignable(cls.getComponentType(), toComponentType, typeVarAssigns);
    }

    if (type instanceof GenericArrayType) {
        // compare the component types
        return isAssignable(((GenericArrayType) type).getGenericComponentType(), toComponentType,
                typeVarAssigns);
    }

    if (type instanceof WildcardType) {
        // so long as one of the upper bounds is assignable, it's good
        for (Type bound : getImplicitUpperBounds((WildcardType) type)) {
            if (isAssignable(bound, toGenericArrayType)) {
                return true;
            }
        }

        return false;
    }

    if (type instanceof TypeVariable<?>) {
        // probably should remove the following logic and just return false.
        // type variables cannot specify arrays as bounds.
        for (Type bound : getImplicitBounds((TypeVariable<?>) type)) {
            if (isAssignable(bound, toGenericArrayType)) {
                return true;
            }
        }

        return false;
    }

    if (type instanceof ParameterizedType) {
        // the raw type of a parameterized type is never an array or
        // generic array, otherwise the declaration would look like this:
        // Collection[]< ? extends String > collection;
        return false;
    }

    throw new IllegalStateException("found an unhandled type: " + type);
}

From source file:com.clark.func.Functions.java

/**
 * <p>// w w w.  j a  v  a  2s . co m
 * Return a map of the type arguments of <code>type</code> in the context of
 * <code>toClass</code>.
 * </p>
 * 
 * @param type
 * @param toClass
 * @param subtypeVarAssigns
 * @return
 */
private static Map<TypeVariable<?>, Type> getTypeArguments(Type type, Class<?> toClass,
        Map<TypeVariable<?>, Type> subtypeVarAssigns) {
    if (type instanceof Class<?>) {
        return getTypeArguments((Class<?>) type, toClass, subtypeVarAssigns);
    }

    if (type instanceof ParameterizedType) {
        return getTypeArguments((ParameterizedType) type, toClass, subtypeVarAssigns);
    }

    if (type instanceof GenericArrayType) {
        return getTypeArguments(((GenericArrayType) type).getGenericComponentType(),
                toClass.isArray() ? toClass.getComponentType() : toClass, subtypeVarAssigns);
    }

    // since wildcard types are not assignable to classes, should this just
    // return null?
    if (type instanceof WildcardType) {
        for (Type bound : getImplicitUpperBounds((WildcardType) type)) {
            // find the first bound that is assignable to the target class
            if (isAssignable(bound, toClass)) {
                return getTypeArguments(bound, toClass, subtypeVarAssigns);
            }
        }

        return null;
    }

    // *
    if (type instanceof TypeVariable<?>) {
        for (Type bound : getImplicitBounds((TypeVariable<?>) type)) {
            // find the first bound that is assignable to the target class
            if (isAssignable(bound, toClass)) {
                return getTypeArguments(bound, toClass, subtypeVarAssigns);
            }
        }

        return null;
    }
    // */

    throw new IllegalStateException("found an unhandled type: " + type);
}

From source file:com.clark.func.Functions.java

/**
 * <p>/*w  ww. ja v a2s .c  o m*/
 * Checks if the subject type may be implicitly cast to the target class
 * following the Java generics rules.
 * </p>
 * 
 * @param type
 *            the subject type to be assigned to the target type
 * @param toClass
 *            the target class
 * @return true if <code>type</code> is assignable to <code>toClass</code>.
 */
private static boolean isAssignable(Type type, Class<?> toClass) {
    if (type == null) {
        // consistency with ClassUtils.isAssignable() behavior
        return toClass == null || !toClass.isPrimitive();
    }

    // only a null type can be assigned to null type which
    // would have cause the previous to return true
    if (toClass == null) {
        return false;
    }

    // all types are assignable to themselves
    if (toClass.equals(type)) {
        return true;
    }

    if (type instanceof Class<?>) {
        // just comparing two classes
        return isAssignable((Class<?>) type, toClass);
    }

    if (type instanceof ParameterizedType) {
        // only have to compare the raw type to the class
        return isAssignable(getRawType((ParameterizedType) type), toClass);
    }

    // *
    if (type instanceof TypeVariable<?>) {
        // if any of the bounds are assignable to the class, then the
        // type is assignable to the class.
        for (Type bound : ((TypeVariable<?>) type).getBounds()) {
            if (isAssignable(bound, toClass)) {
                return true;
            }
        }

        return false;
    }

    // the only classes to which a generic array type can be assigned
    // are class Object and array classes
    if (type instanceof GenericArrayType) {
        return toClass.equals(Object.class)
                || toClass.isArray() && isAssignable(((GenericArrayType) type).getGenericComponentType(),
                        toClass.getComponentType());
    }

    // wildcard types are not assignable to a class (though one would think
    // "? super Object" would be assignable to Object)
    if (type instanceof WildcardType) {
        return false;
    }

    throw new IllegalStateException("found an unhandled type: " + type);
}