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:org.apache.flink.api.java.typeutils.TypeExtractor.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private <OUT, IN1, IN2> TypeInformation<OUT> privateGetForClass(Class<OUT> clazz, ArrayList<Type> typeHierarchy,
        ParameterizedType parameterizedType, TypeInformation<IN1> in1Type, TypeInformation<IN2> in2Type) {
    checkNotNull(clazz);/* w w  w  .  j a va 2 s . c  o m*/

    // check if type information can be produced using a factory
    final TypeInformation<OUT> typeFromFactory = createTypeInfoFromFactory(clazz, typeHierarchy, in1Type,
            in2Type);
    if (typeFromFactory != null) {
        return typeFromFactory;
    }

    // Object is handled as generic type info
    if (clazz.equals(Object.class)) {
        return new GenericTypeInfo<>(clazz);
    }

    // Class is handled as generic type info
    if (clazz.equals(Class.class)) {
        return new GenericTypeInfo<OUT>(clazz);
    }

    // recursive types are handled as generic type info
    if (countTypeInHierarchy(typeHierarchy, clazz) > 1) {
        return new GenericTypeInfo<>(clazz);
    }

    // check for arrays
    if (clazz.isArray()) {

        // primitive arrays: int[], byte[], ...
        PrimitiveArrayTypeInfo<OUT> primitiveArrayInfo = PrimitiveArrayTypeInfo.getInfoFor(clazz);
        if (primitiveArrayInfo != null) {
            return primitiveArrayInfo;
        }

        // basic type arrays: String[], Integer[], Double[]
        BasicArrayTypeInfo<OUT, ?> basicArrayInfo = BasicArrayTypeInfo.getInfoFor(clazz);
        if (basicArrayInfo != null) {
            return basicArrayInfo;
        }

        // object arrays
        else {
            TypeInformation<?> componentTypeInfo = createTypeInfoWithTypeHierarchy(typeHierarchy,
                    clazz.getComponentType(), in1Type, in2Type);

            return ObjectArrayTypeInfo.getInfoFor(clazz, componentTypeInfo);
        }
    }

    // check for writable types
    if (isHadoopWritable(clazz)) {
        return createHadoopWritableTypeInfo(clazz);
    }

    // check for basic types
    TypeInformation<OUT> basicTypeInfo = BasicTypeInfo.getInfoFor(clazz);
    if (basicTypeInfo != null) {
        return basicTypeInfo;
    }

    // check for SQL time types
    TypeInformation<OUT> timeTypeInfo = SqlTimeTypeInfo.getInfoFor(clazz);
    if (timeTypeInfo != null) {
        return timeTypeInfo;
    }

    // check for subclasses of Value
    if (Value.class.isAssignableFrom(clazz)) {
        Class<? extends Value> valueClass = clazz.asSubclass(Value.class);
        return (TypeInformation<OUT>) ValueTypeInfo.getValueTypeInfo(valueClass);
    }

    // check for subclasses of Tuple
    if (Tuple.class.isAssignableFrom(clazz)) {
        if (clazz == Tuple0.class) {
            return new TupleTypeInfo(Tuple0.class);
        }
        throw new InvalidTypesException(
                "Type information extraction for tuples (except Tuple0) cannot be done based on the class.");
    }

    // check for Enums
    if (Enum.class.isAssignableFrom(clazz)) {
        return new EnumTypeInfo(clazz);
    }

    // special case for POJOs generated by Avro.
    if (SpecificRecordBase.class.isAssignableFrom(clazz)) {
        return new AvroTypeInfo(clazz);
    }

    if (Modifier.isInterface(clazz.getModifiers())) {
        // Interface has no members and is therefore not handled as POJO
        return new GenericTypeInfo<OUT>(clazz);
    }

    try {
        TypeInformation<OUT> pojoType = analyzePojo(clazz, new ArrayList<Type>(typeHierarchy),
                parameterizedType, in1Type, in2Type);
        if (pojoType != null) {
            return pojoType;
        }
    } catch (InvalidTypesException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Unable to handle type " + clazz + " as POJO. Message: " + e.getMessage(), e);
        }
        // ignore and create generic type info
    }

    // return a generic type
    return new GenericTypeInfo<OUT>(clazz);
}

From source file:org.codehaus.enunciate.modules.rest.RESTOperation.java

/**
 * Construct a REST operation.//from   w ww.j  a v  a  2 s  .  c  o m
 *
 * @param resource The resource for this operation.
 * @param contentType The content type of the operation.
 * @param verb     The verb for the operation.
 * @param method   The method.
 * @param parameterNames The parameter names.
 */
protected RESTOperation(RESTResource resource, String contentType, VerbType verb, Method method,
        String[] parameterNames) {
    this.resource = resource;
    this.verb = verb;
    this.method = method;
    this.contentType = contentType;

    int properNounIndex = -1;
    Class properNoun = null;
    Boolean properNounOptional = null;
    int nounValueIndex = -1;
    Class nounValue = null;
    Boolean nounValueOptional = Boolean.FALSE;
    int contentTypeParameterIndex = -1;
    adjectiveTypes = new HashMap<String, Class>();
    adjectiveIndices = new HashMap<String, Integer>();
    adjectivesOptional = new HashMap<String, Boolean>();
    complexAdjectives = new ArrayList<String>();
    contextParameterTypes = new HashMap<String, Class>();
    contextParameterIndices = new HashMap<String, Integer>();
    Class[] parameterTypes = method.getParameterTypes();
    HashSet<Class> contextClasses = new HashSet<Class>();
    for (int i = 0; i < parameterTypes.length; i++) {
        Class parameterType = Collection.class.isAssignableFrom(parameterTypes[i])
                ? getCollectionTypeAsArrayType(method, i)
                : parameterTypes[i];

        boolean isAdjective = true;
        String adjectiveName = "arg" + i;
        if ((parameterNames != null) && (parameterNames.length > i) && (parameterNames[i] != null)) {
            adjectiveName = parameterNames[i];
        }
        boolean adjectiveOptional = !parameterType.isPrimitive();
        boolean adjectiveComplex = false;
        Annotation[] parameterAnnotations = method.getParameterAnnotations()[i];
        for (Annotation annotation : parameterAnnotations) {
            if (annotation instanceof ProperNoun) {
                if (parameterType.isArray()) {
                    throw new IllegalStateException(
                            "Proper nouns must be simple types, found an array or collection for parameter " + i
                                    + " of method " + method.getDeclaringClass().getName() + "."
                                    + method.getName() + ".");
                } else if (properNoun == null) {
                    ProperNoun properNounInfo = (ProperNoun) annotation;
                    if (properNounInfo.optional()) {
                        if (parameterType.isPrimitive()) {
                            throw new IllegalStateException(
                                    "An optional proper noun cannot be a primitive type for method "
                                            + method.getDeclaringClass().getName() + "." + method.getName()
                                            + ".");
                        }

                        properNounOptional = true;
                    }

                    if (!properNounInfo.converter().equals(ProperNoun.DEFAULT.class)) {
                        try {
                            ConvertUtils.register((Converter) properNounInfo.converter().newInstance(),
                                    parameterType);
                        } catch (ClassCastException e) {
                            throw new IllegalArgumentException("Illegal converter class for method "
                                    + method.getDeclaringClass().getName() + "." + method.getName()
                                    + ". Must be an instance of org.apache.commons.beanutils.Converter.");
                        } catch (Exception e) {
                            throw new IllegalArgumentException("Unable to instantiate converter class "
                                    + properNounInfo.converter().getName() + " on method "
                                    + method.getDeclaringClass().getName() + "." + method.getName() + ".", e);
                        }
                    }

                    properNoun = parameterType;
                    properNounIndex = i;
                    isAdjective = false;
                    break;
                } else {
                    throw new IllegalStateException("There are two proper nouns for method "
                            + method.getDeclaringClass().getName() + "." + method.getName() + ".");
                }
            } else if (annotation instanceof NounValue) {
                if ((!parameterType.isAnnotationPresent(XmlRootElement.class))
                        && (!parameterType.equals(DataHandler.class)) && (!(parameterType.isArray()
                                && parameterType.getComponentType().equals(DataHandler.class)))) {
                    LOG.warn(
                            "Enunciate doesn't support unmarshalling objects of type " + parameterType.getName()
                                    + ". Unless a custom content type handler is provided, this operation ("
                                    + method.getDeclaringClass() + "." + method.getName() + ") will fail.");
                }

                if (nounValue == null) {
                    if (((NounValue) annotation).optional()) {
                        if (parameterType.isPrimitive()) {
                            throw new IllegalStateException(
                                    "An optional noun value cannot be a primitive type for method "
                                            + method.getDeclaringClass().getName() + "." + method.getName()
                                            + ".");
                        }

                        nounValueOptional = true;
                    }

                    nounValue = parameterType;
                    nounValueIndex = i;
                    isAdjective = false;
                    break;
                } else {
                    throw new IllegalStateException("There are two proper nouns for method "
                            + method.getDeclaringClass().getName() + "." + method.getName() + ".");
                }
            } else if (annotation instanceof ContextParameter) {
                ContextParameter contextParameterInfo = (ContextParameter) annotation;
                String contextParameterName = contextParameterInfo.value();

                if (!contextParameterInfo.converter().equals(ContextParameter.DEFAULT.class)) {
                    try {
                        ConvertUtils.register((Converter) contextParameterInfo.converter().newInstance(),
                                parameterType);
                    } catch (ClassCastException e) {
                        throw new IllegalArgumentException("Illegal converter class for method "
                                + method.getDeclaringClass().getName() + "." + method.getName()
                                + ". Must be an instance of org.apache.commons.beanutils.Converter.");
                    } catch (Exception e) {
                        throw new IllegalArgumentException(
                                "Unable to instantiate converter class "
                                        + contextParameterInfo.converter().getName() + " on method "
                                        + method.getDeclaringClass().getName() + "." + method.getName() + ".",
                                e);
                    }
                }

                contextParameterTypes.put(contextParameterName, parameterType);
                contextParameterIndices.put(contextParameterName, i);
                isAdjective = false;
                break;
            } else if (annotation instanceof ContentTypeParameter) {
                contentTypeParameterIndex = i;
                isAdjective = false;
                break;
            } else if (annotation instanceof Adjective) {
                Adjective adjectiveInfo = (Adjective) annotation;
                adjectiveOptional = adjectiveInfo.optional();
                if (adjectiveOptional && parameterType.isPrimitive()) {
                    throw new IllegalStateException(
                            "An optional adjective cannot be a primitive type for method "
                                    + method.getDeclaringClass().getName() + "." + method.getName() + ".");
                }

                if (!"##default".equals(adjectiveInfo.name())) {
                    adjectiveName = adjectiveInfo.name();
                }

                adjectiveComplex = adjectiveInfo.complex();

                if (!adjectiveInfo.converter().equals(Adjective.DEFAULT.class)) {
                    try {
                        ConvertUtils.register((Converter) adjectiveInfo.converter().newInstance(),
                                parameterType);
                    } catch (ClassCastException e) {
                        throw new IllegalArgumentException("Illegal converter class for method "
                                + method.getDeclaringClass().getName() + "." + method.getName()
                                + ". Must be an instance of org.apache.commons.beanutils.Converter.");
                    } catch (Exception e) {
                        throw new IllegalArgumentException("Unable to instantiate converter class "
                                + adjectiveInfo.converter().getName() + " on method "
                                + method.getDeclaringClass().getName() + "." + method.getName() + ".", e);
                    }
                }

                break;
            }
        }

        if (isAdjective) {
            this.adjectiveTypes.put(adjectiveName, parameterType);
            this.adjectiveIndices.put(adjectiveName, i);
            this.adjectivesOptional.put(adjectiveName, adjectiveOptional);
            if (adjectiveComplex) {
                this.complexAdjectives.add(adjectiveName);
            }
        }

        if (parameterType.isArray()) {
            contextClasses.add(parameterType.getComponentType());
        } else {
            contextClasses.add(parameterType);
        }
    }

    Class returnType = null;
    if (!Void.TYPE.equals(method.getReturnType())) {
        returnType = method.getReturnType();

        if (!returnType.isAnnotationPresent(XmlRootElement.class)
                && (!DataHandler.class.isAssignableFrom(returnType))) {
            LOG.warn("Enunciate doesn't support marshalling objects of type " + returnType.getName()
                    + ". Unless a custom content type handler is provided, this operation ("
                    + method.getDeclaringClass() + "." + method.getName() + ") will fail.");
        }

        contextClasses.add(returnType);
    }

    for (Class exceptionClass : method.getExceptionTypes()) {
        for (Method exceptionMethod : exceptionClass.getMethods()) {
            if ((exceptionMethod.isAnnotationPresent(RESTErrorBody.class))
                    && (exceptionMethod.getReturnType() != Void.TYPE)) {
                //add the error body to the context classes.
                contextClasses.add(exceptionMethod.getReturnType());
            }
        }
    }

    //now load any additional context classes as specified by @RESTSeeAlso
    if (method.isAnnotationPresent(RESTSeeAlso.class)) {
        contextClasses.addAll(Arrays.asList(method.getAnnotation(RESTSeeAlso.class).value()));
    }
    if (method.getDeclaringClass().isAnnotationPresent(RESTSeeAlso.class)) {
        contextClasses
                .addAll(Arrays.asList(method.getDeclaringClass().getAnnotation(RESTSeeAlso.class).value()));
    }
    if ((method.getDeclaringClass().getPackage() != null)
            && (method.getDeclaringClass().getPackage().isAnnotationPresent(RESTSeeAlso.class))) {
        contextClasses.addAll(Arrays
                .asList(method.getDeclaringClass().getPackage().getAnnotation(RESTSeeAlso.class).value()));
    }

    String jsonpParameter = null;
    JSONP jsonpInfo = method.getAnnotation(JSONP.class);
    if (jsonpInfo == null) {
        jsonpInfo = method.getDeclaringClass().getAnnotation(JSONP.class);
        if (jsonpInfo == null) {
            jsonpInfo = method.getDeclaringClass().getPackage().getAnnotation(JSONP.class);
        }
    }
    if (jsonpInfo != null) {
        jsonpParameter = jsonpInfo.paramName();
    }

    String charset = "utf-8";
    org.codehaus.enunciate.rest.annotations.ContentType contentTypeInfo = method
            .getAnnotation(org.codehaus.enunciate.rest.annotations.ContentType.class);
    if (contentTypeInfo == null) {
        contentTypeInfo = method.getDeclaringClass()
                .getAnnotation(org.codehaus.enunciate.rest.annotations.ContentType.class);
        if (contentTypeInfo == null) {
            contentTypeInfo = method.getDeclaringClass().getPackage()
                    .getAnnotation(org.codehaus.enunciate.rest.annotations.ContentType.class);
        }
    }
    if (contentTypeInfo != null) {
        charset = contentTypeInfo.charset();
    }

    String defaultNamespace = "";
    if (method.getDeclaringClass().getPackage() != null
            && method.getDeclaringClass().getPackage().isAnnotationPresent(XmlSchema.class)) {
        defaultNamespace = method.getDeclaringClass().getPackage().getAnnotation(XmlSchema.class).namespace();
    }

    this.properNounType = properNoun;
    this.properNounIndex = properNounIndex;
    this.properNounOptional = properNounOptional;
    this.nounValueType = nounValue;
    this.nounValueIndex = nounValueIndex;
    this.nounValueOptional = nounValueOptional;
    this.resultType = returnType;
    this.charset = charset;
    this.JSONPParameter = jsonpParameter;
    this.contextClasses = contextClasses;
    this.contentTypeParameterIndex = contentTypeParameterIndex;
    this.defaultNamespace = defaultNamespace;
}

From source file:org.debux.webmotion.server.handler.ExecutorParametersConvertorHandler.java

protected Object convert(ParameterTree parameterTree, Class<?> type, Type genericType) throws Exception {
    Object result = null;//ww  w. j a  v a 2  s  .  com

    if (parameterTree == null) {
        return null;
    }

    if (genericType == null) {
        genericType = type.getGenericSuperclass();
    }

    Map<String, List<ParameterTree>> parameterArray = parameterTree.getArray();
    Map<String, ParameterTree> parameterObject = parameterTree.getObject();
    Object value = parameterTree.getValue();

    Converter lookup = converter.lookup(type);
    if (lookup != null) {

        // converter found, use it
        result = lookup.convert(type, value);
        return result;
    }

    // Manage enums
    if (type.isEnum()) {
        Object name = value == null ? null : ((Object[]) value)[0];
        if (name != null) {
            result = Enum.valueOf((Class<? extends Enum>) type, name.toString());
        }

        // Manage collection
    } else if (Collection.class.isAssignableFrom(type)) {

        Collection instance;
        if (type.isInterface()) {
            if (List.class.isAssignableFrom(type)) {
                instance = new ArrayList();

            } else if (Set.class.isAssignableFrom(type)) {
                instance = new HashSet();

            } else if (SortedSet.class.isAssignableFrom(type)) {
                instance = new TreeSet();

            } else {
                instance = new ArrayList();
            }
        } else {
            instance = (Collection) type.newInstance();
        }

        Class convertType = String.class;
        if (genericType != null && genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            convertType = (Class) parameterizedType.getActualTypeArguments()[0];
        }

        if (parameterObject != null) {
            for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) {
                ParameterTree object = entry.getValue();
                Object converted = convert(object, convertType, null);
                instance.add(converted);
            }
        } else {
            Object[] tab = (Object[]) value;
            for (Object object : tab) {
                Object converted = converter.convert(object, convertType);
                instance.add(converted);
            }
        }

        result = instance;

        // Manage map
    } else if (Map.class.isAssignableFrom(type)) {
        Map instance;
        if (type.isInterface()) {
            if (SortedMap.class.isAssignableFrom(type)) {
                instance = new TreeMap();

            } else {
                instance = new HashMap();
            }
        } else {
            instance = (Map) type.newInstance();
        }

        Class convertKeyType = String.class;
        Class convertValueType = String.class;
        if (genericType != null && genericType instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) genericType;
            convertKeyType = (Class) parameterizedType.getActualTypeArguments()[0];
            convertValueType = (Class) parameterizedType.getActualTypeArguments()[1];
        }

        for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) {
            String mapKey = entry.getKey();
            ParameterTree mapValue = entry.getValue();

            Object convertedKey = converter.convert(mapKey, convertKeyType);
            Object convertedValue = convert(mapValue, convertValueType, null);

            instance.put(convertedKey, convertedValue);
        }

        result = instance;

        // Manage simple object
    } else if (type.isArray()) {
        Class<?> componentType = type.getComponentType();

        if (parameterObject != null) {
            Object[] tabConverted = (Object[]) Array.newInstance(componentType, parameterObject.size());
            result = tabConverted;

            int index = 0;
            for (Map.Entry<String, ParameterTree> entry : parameterObject.entrySet()) {
                ParameterTree object = entry.getValue();
                Object objectConverted = convert(object, componentType, null);
                tabConverted[index] = objectConverted;
                index++;
            }

        } else {
            Object[] tab = (Object[]) value;
            Object[] tabConverted = (Object[]) Array.newInstance(componentType, tab.length);
            result = tabConverted;

            for (int index = 0; index < tab.length; index++) {
                Object object = tab[index];
                Object objectConverted = converter.convert(object, componentType);
                tabConverted[index] = objectConverted;
            }
        }

    } else if (value instanceof UploadFile) {
        if (File.class.isAssignableFrom(type)) {
            UploadFile uploadFile = (UploadFile) value;
            result = uploadFile.getFile();
        } else {
            result = value;
        }

        // Manage simple object
    } else {
        Object instance = type.newInstance();
        boolean one = false;

        if (parameterObject != null) {
            for (Map.Entry<String, ParameterTree> attribut : parameterObject.entrySet()) {
                String attributeName = attribut.getKey();
                ParameterTree attributeValue = attribut.getValue();

                boolean writeable = propertyUtils.isWriteable(instance, attributeName);
                if (writeable) {
                    one = true;

                    Field field = FieldUtils.getField(type, attributeName, true);
                    Class<?> attributeType = field.getType();

                    genericType = field.getGenericType();
                    Object attributeConverted = convert(attributeValue, attributeType, genericType);
                    beanUtil.setProperty(instance, attributeName, attributeConverted);
                }
            }
        }

        if (parameterArray != null) {
            for (Map.Entry<String, List<ParameterTree>> entry : parameterArray.entrySet()) {
                String attributeName = entry.getKey();
                List<ParameterTree> attributeValues = entry.getValue();

                boolean writeable = propertyUtils.isWriteable(instance, attributeName);
                if (writeable) {
                    one = true;

                    Field field = FieldUtils.getField(type, attributeName, true);
                    Class<?> attributeType = field.getType();

                    genericType = field.getGenericType();
                    Object attributeConverted = convert(attributeValues, attributeType, genericType);
                    beanUtil.setProperty(instance, attributeName, attributeConverted);
                }
            }
        }

        if (one) {
            result = instance;

        } else {
            result = null;
        }
    }

    return result;
}

From source file:com.bstek.dorado.idesupport.initializer.CommonRuleTemplateInitializer.java

protected Collection<AutoPropertyTemplate> getProperties(Class<?> type, XmlNodeInfo xmlNodeInfo,
        InitializerContext initializerContext) throws Exception {
    HashMap<String, AutoPropertyTemplate> properties = new LinkedHashMap<String, AutoPropertyTemplate>();
    RuleTemplateManager ruleTemplateManager = initializerContext.getRuleTemplateManager();

    if (xmlNodeInfo != null) {
        if (xmlNodeInfo.isInheritable()) {
            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("impl");
            propertyTemplate.setPrimitive(true);
            properties.put(propertyTemplate.getName(), propertyTemplate);

            propertyTemplate = new AutoPropertyTemplate("parent");
            propertyTemplate.setPrimitive(true);
            properties.put(propertyTemplate.getName(), propertyTemplate);
        }/*from   ww w .jav  a 2 s .  c o  m*/

        if (xmlNodeInfo.isScopable()) {
            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("scope");
            propertyTemplate.setPrimitive(true);

            Object[] ecs = Scope.class.getEnumConstants();
            String[] enumValues = new String[ecs.length];
            for (int i = 0; i < ecs.length; i++) {
                enumValues[i] = ecs[i].toString();
            }
            propertyTemplate.setEnumValues(enumValues);

            properties.put(propertyTemplate.getName(), propertyTemplate);
        }

        if (StringUtils.isNotEmpty(xmlNodeInfo.getDefinitionType())) {
            Class<?> definitionType = ClassUtils.forName(xmlNodeInfo.getDefinitionType());
            if (ListenableObjectDefinition.class.isAssignableFrom(definitionType)) {
                AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("listener");
                propertyTemplate.setPrimitive(true);
                properties.put(propertyTemplate.getName(), propertyTemplate);
            }

            if (InterceptableDefinition.class.isAssignableFrom(definitionType)) {
                AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("interceptor");
                propertyTemplate.setPrimitive(true);
                properties.put(propertyTemplate.getName(), propertyTemplate);
            }
        }

        for (Map.Entry<String, String> entry : xmlNodeInfo.getFixedProperties().entrySet()) {
            String propertyName = entry.getKey();
            String value = entry.getValue();

            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName);
            propertyTemplate.setDefaultValue(value);
            propertyTemplate.setPrimitive(true);
            propertyTemplate.setFixed(true);
            propertyTemplate.setVisible(false);
            properties.put(propertyName, propertyTemplate);
        }

        for (Map.Entry<String, XmlProperty> entry : xmlNodeInfo.getProperties().entrySet()) {
            String propertyName = entry.getKey();
            XmlProperty xmlProperty = entry.getValue();
            TypeInfo propertyTypeInfo = TypeInfo.parse(xmlProperty.propertyType());
            Class<?> propertyType = null;
            if (propertyTypeInfo != null) {
                propertyType = propertyTypeInfo.getType();
            }

            AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName, xmlProperty);
            propertyTemplate.setPrimitive(xmlProperty.attributeOnly());
            if (propertyType != null && !propertyType.equals(String.class)) {
                propertyTemplate.setType(propertyType.getName());
            }

            if (xmlProperty.composite()) {
                initCompositeProperty(propertyTemplate, propertyType, initializerContext);
            }
            propertyTemplate.setDeprecated(xmlProperty.deprecated());

            properties.put(propertyName, propertyTemplate);
        }
    }

    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod != null && propertyDescriptor.getWriteMethod() != null) {
            if (readMethod.getDeclaringClass() != type) {
                try {
                    readMethod = type.getDeclaredMethod(readMethod.getName(), readMethod.getParameterTypes());
                } catch (NoSuchMethodException e) {
                    continue;
                }
            }

            String propertyName = propertyDescriptor.getName();

            XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class);
            if (xmlSubNode != null) {
                continue;
            }

            TypeInfo propertyTypeInfo;
            Class<?> propertyType = propertyDescriptor.getPropertyType();
            if (Collection.class.isAssignableFrom(propertyType)) {
                propertyTypeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(), true);
                propertyType = propertyTypeInfo.getType();
            } else {
                propertyTypeInfo = new TypeInfo(propertyType, false);
            }

            AutoPropertyTemplate propertyTemplate = null;
            XmlProperty xmlProperty = readMethod.getAnnotation(XmlProperty.class);
            if (xmlProperty != null) {
                if (xmlProperty.unsupported()) {
                    continue;
                }

                propertyTemplate = properties.get(propertyName);
                if (propertyTemplate == null) {
                    propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty);
                    propertyTemplate.setPrimitive(xmlProperty.attributeOnly());
                }

                if (("dataSet".equals(propertyName) || "dataPath".equals(propertyName)
                        || "property".equals(propertyName)) && DataControl.class.isAssignableFrom(type)) {
                    propertyTemplate.setHighlight(1);
                }

                if (xmlProperty.composite()) {
                    initCompositeProperty(propertyTemplate, propertyType, initializerContext);
                }

                int clientTypes = ClientType.parseClientTypes(xmlProperty.clientTypes());
                if (clientTypes > 0) {
                    propertyTemplate.setClientTypes(clientTypes);
                }
                propertyTemplate.setDeprecated(xmlProperty.deprecated());
            } else if (EntityUtils.isSimpleType(propertyType) || propertyType.equals(Class.class)
                    || propertyType.isArray() && propertyType.getComponentType().equals(String.class)) {
                propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty);
            }

            if (propertyTemplate != null) {
                propertyTemplate.setType(propertyDescriptor.getPropertyType().getName());

                if (propertyType.isEnum()) {
                    Object[] ecs = propertyType.getEnumConstants();
                    String[] enumValues = new String[ecs.length];
                    for (int i = 0; i < ecs.length; i++) {
                        enumValues[i] = ecs[i].toString();
                    }
                    propertyTemplate.setEnumValues(enumValues);
                }

                ComponentReference componentReference = readMethod.getAnnotation(ComponentReference.class);
                if (componentReference != null) {
                    ReferenceTemplate referenceTemplate = new LazyReferenceTemplate(ruleTemplateManager,
                            componentReference.value(), "id");
                    propertyTemplate.setReference(referenceTemplate);
                }

                IdeProperty ideProperty = readMethod.getAnnotation(IdeProperty.class);
                if (ideProperty != null) {
                    propertyTemplate.setVisible(ideProperty.visible());
                    propertyTemplate.setEditor(ideProperty.editor());
                    propertyTemplate.setHighlight(ideProperty.highlight());
                    if (StringUtils.isNotEmpty(ideProperty.enumValues())) {
                        propertyTemplate.setEnumValues(StringUtils.split(ideProperty.enumValues(), ",;"));
                    }
                }

                ClientProperty clientProperty = readMethod.getAnnotation(ClientProperty.class);
                if (clientProperty != null) {
                    propertyTemplate.setDefaultValue(clientProperty.escapeValue());
                }

                properties.put(propertyName, propertyTemplate);
            }
        }
    }
    return properties.values();
}

From source file:javadz.beanutils.BeanUtilsBean.java

/**
 * <p>Set the specified property value, performing type conversions as
 * required to conform to the type of the destination property.</p>
 *
 * <p>If the property is read only then the method returns 
 * without throwing an exception.</p>
 *
 * <p>If <code>null</code> is passed into a property expecting a primitive value,
 * then this will be converted as if it were a <code>null</code> string.</p>
 *
 * <p><strong>WARNING</strong> - The logic of this method is customized
 * to meet the needs of <code>populate()</code>, and is probably not what
 * you want for general property copying with type conversion.  For that
 * purpose, check out the <code>copyProperty()</code> method instead.</p>
 *
 * <p><strong>WARNING</strong> - PLEASE do not modify the behavior of this
 * method without consulting with the Struts developer community.  There
 * are some subtleties to its functionality that are not documented in the
 * Javadoc description above, yet are vital to the way that Struts utilizes
 * this method.</p>//from  www  . j a  va2  s.c o  m
 *
 * @param bean Bean on which setting is to be performed
 * @param name Property name (can be nested/indexed/mapped/combo)
 * @param value Value to be set
 *
 * @exception IllegalAccessException if the caller does not have
 *  access to the property accessor method
 * @exception InvocationTargetException if the property accessor method
 *  throws an exception
 */
public void setProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {

    // Trace logging (if enabled)
    if (log.isTraceEnabled()) {
        StringBuffer sb = new StringBuffer("  setProperty(");
        sb.append(bean);
        sb.append(", ");
        sb.append(name);
        sb.append(", ");
        if (value == null) {
            sb.append("<NULL>");
        } else if (value instanceof String) {
            sb.append((String) value);
        } else if (value instanceof String[]) {
            String[] values = (String[]) value;
            sb.append('[');
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(values[i]);
            }
            sb.append(']');
        } else {
            sb.append(value.toString());
        }
        sb.append(')');
        log.trace(sb.toString());
    }

    // Resolve any nested expression to get the actual target bean
    Object target = bean;
    Resolver resolver = getPropertyUtils().getResolver();
    while (resolver.hasNested(name)) {
        try {
            target = getPropertyUtils().getProperty(target, resolver.next(name));
            name = resolver.remove(name);
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("    Target bean = " + target);
        log.trace("    Target name = " + name);
    }

    // Declare local variables we will require
    String propName = resolver.getProperty(name); // Simple name of target property
    Class type = null; // Java type of target property
    int index = resolver.getIndex(name); // Indexed subscript value (if any)
    String key = resolver.getKey(name); // Mapped key value (if any)

    // Calculate the property type
    if (target instanceof DynaBean) {
        DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return; // Skip this property setter
        }
        type = dynaProperty.getType();
    } else if (target instanceof Map) {
        type = Object.class;
    } else if (target != null && target.getClass().isArray() && index >= 0) {
        type = Array.get(target, index).getClass();
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return; // Skip this property setter
            }
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        if (descriptor instanceof MappedPropertyDescriptor) {
            if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();
        } else if (index >= 0 && descriptor instanceof IndexedPropertyDescriptor) {
            if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
        } else if (key != null) {
            if (descriptor.getReadMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = (value == null) ? Object.class : value.getClass();
        } else {
            if (descriptor.getWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
        }
    }

    // Convert the specified value to the required type
    Object newValue = null;
    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value == null) {
            String[] values = new String[1];
            values[0] = null;
            newValue = getConvertUtils().convert(values, type);
        } else if (value instanceof String) {
            newValue = getConvertUtils().convert(value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert((String[]) value, type);
        } else {
            newValue = convert(value, type);
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String || value == null) {
            newValue = getConvertUtils().convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = convert(value, type.getComponentType());
        }
    } else { // Value into scalar
        if (value instanceof String) {
            newValue = getConvertUtils().convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type);
        } else {
            newValue = convert(value, type);
        }
    }

    // Invoke the setter method
    try {
        getPropertyUtils().setProperty(target, name, newValue);
    } catch (NoSuchMethodException e) {
        throw new InvocationTargetException(e, "Cannot set " + propName);
    }

}

From source file:org.evergreen.web.utils.beanutils.BeanUtilsBean.java

/**
 * <p>Set the specified property value, performing type conversions as
 * required to conform to the type of the destination property.</p>
 *
 * <p>If the property is read only then the method returns 
 * without throwing an exception.</p>
 *
 * <p>If <code>null</code> is passed into a property expecting a primitive value,
 * then this will be converted as if it were a <code>null</code> string.</p>
 *
 * <p><strong>WARNING</strong> - The logic of this method is customized
 * to meet the needs of <code>populate()</code>, and is probably not what
 * you want for general property copying with type conversion.  For that
 * purpose, check out the <code>copyProperty()</code> method instead.</p>
 *
 * <p><strong>WARNING</strong> - PLEASE do not modify the behavior of this
 * method without consulting with the Struts developer community.  There
 * are some subtleties to its functionality that are not documented in the
 * Javadoc description above, yet are vital to the way that Struts utilizes
 * this method.</p>/*from   w  w  w  .j ava2s.  c o m*/
 *
 * @param bean Bean on which setting is to be performed
 * @param name Property name (can be nested/indexed/mapped/combo)
 * @param value Value to be set
 *
 * @exception IllegalAccessException if the caller does not have
 *  access to the property accessor method
 * @exception InvocationTargetException if the property accessor method
 *  throws an exception
 */
public void setProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {
    // Trace logging (if enabled)
    if (log.isTraceEnabled()) {
        StringBuffer sb = new StringBuffer("  setProperty(");
        sb.append(bean);
        sb.append(", ");
        sb.append(name);
        sb.append(", ");
        if (value == null) {
            sb.append("<NULL>");
        } else if (value instanceof String) {
            sb.append((String) value);
        } else if (value instanceof String[]) {
            String[] values = (String[]) value;
            sb.append('[');
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(values[i]);
            }
            sb.append(']');
        } else {
            sb.append(value.toString());
        }
        sb.append(')');
        log.trace(sb.toString());
    }

    // Resolve any nested expression to get the actual target bean
    Object target = bean;
    Resolver resolver = getPropertyUtils().getResolver();
    while (resolver.hasNested(name)) {
        try {
            target = getPropertyUtils().getProperty(target, resolver.next(name));
            name = resolver.remove(name);
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
    }
    if (log.isTraceEnabled()) {
        log.trace("    Target bean = " + target);
        log.trace("    Target name = " + name);
    }

    // Declare local variables we will require
    String propName = resolver.getProperty(name); // Simple name of target property
    Class type = null; // Java type of target property
    int index = resolver.getIndex(name); // Indexed subscript value (if any)
    String key = resolver.getKey(name); // Mapped key value (if any)

    // Calculate the property type
    if (target instanceof DynaBean) {
        DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return; // Skip this property setter
        }
        type = dynaProperty.getType();
    } else if (target instanceof Map) {
        type = Object.class;
    } else if (target != null && target.getClass().isArray() && index >= 0) {
        type = Array.get(target, index).getClass();
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return; // Skip this property setter
            }
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        if (descriptor instanceof MappedPropertyDescriptor) {
            if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();
        } else if (index >= 0 && descriptor instanceof IndexedPropertyDescriptor) {
            if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
        } else if (key != null) {
            if (descriptor.getReadMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = (value == null) ? Object.class : value.getClass();
        } else {
            if (descriptor.getWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
        }
    }

    // Convert the specified value to the required type
    Object newValue = null;
    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value == null) {
            String[] values = new String[1];
            values[0] = null;
            newValue = getConvertUtils().convert(values, type);
        } else if (value instanceof String) {
            newValue = getConvertUtils().convert(value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert((String[]) value, type);
        } else {
            newValue = convert(value, type);
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String || value == null) {
            newValue = getConvertUtils().convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = convert(value, type.getComponentType());
        }
    } else { // Value into scalar
        if (value instanceof String) {
            newValue = getConvertUtils().convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type);
        } else {
            newValue = convert(value, type);
        }
    }

    // Invoke the setter method
    try {
        getPropertyUtils().setProperty(target, name, newValue);
    } catch (NoSuchMethodException e) {
        throw new InvocationTargetException(e, "Cannot set " + propName);
    }

}

From source file:org.enerj.apache.commons.beanutils.BeanUtilsBean.java

/**
 * <p>Set the specified property value, performing type conversions as
 * required to conform to the type of the destination property.</p>
 *
 * <p>If the property is read only then the method returns 
 * without throwing an exception.</p>
 *
 * <p>If <code>null</code> is passed into a property expecting a primitive value,
 * then this will be converted as if it were a <code>null</code> string.</p>
 *
 * <p><strong>WARNING</strong> - The logic of this method is customized
 * to meet the needs of <code>populate()</code>, and is probably not what
 * you want for general property copying with type conversion.  For that
 * purpose, check out the <code>copyProperty()</code> method instead.</p>
 *
 * <p><strong>WARNING</strong> - PLEASE do not modify the behavior of this
 * method without consulting with the Struts developer community.  There
 * are some subtleties to its functionality that are not documented in the
 * Javadoc description above, yet are vital to the way that Struts utilizes
 * this method.</p>//from  w  w w  . jav a 2  s . c om
 *
 * @param bean Bean on which setting is to be performed
 * @param name Property name (can be nested/indexed/mapped/combo)
 * @param value Value to be set
 *
 * @exception IllegalAccessException if the caller does not have
 *  access to the property accessor method
 * @exception InvocationTargetException if the property accessor method
 *  throws an exception
 */
public void setProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException {

    // Trace logging (if enabled)
    if (log.isTraceEnabled()) {
        StringBuffer sb = new StringBuffer("  setProperty(");
        sb.append(bean);
        sb.append(", ");
        sb.append(name);
        sb.append(", ");
        if (value == null) {
            sb.append("<NULL>");
        } else if (value instanceof String) {
            sb.append((String) value);
        } else if (value instanceof String[]) {
            String values[] = (String[]) value;
            sb.append('[');
            for (int i = 0; i < values.length; i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(values[i]);
            }
            sb.append(']');
        } else {
            sb.append(value.toString());
        }
        sb.append(')');
        log.trace(sb.toString());
    }

    // Resolve any nested expression to get the actual target bean
    Object target = bean;
    int delim = findLastNestedIndex(name);
    if (delim >= 0) {
        try {
            target = getPropertyUtils().getProperty(bean, name.substring(0, delim));
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        name = name.substring(delim + 1);
        if (log.isTraceEnabled()) {
            log.trace("    Target bean = " + target);
            log.trace("    Target name = " + name);
        }
    }

    // Declare local variables we will require
    String propName = null; // Simple name of target property
    Class type = null; // Java type of target property
    int index = -1; // Indexed subscript value (if any)
    String key = null; // Mapped key value (if any)

    // Calculate the property name, index, and key values
    propName = name;
    int i = propName.indexOf(PropertyUtils.INDEXED_DELIM);
    if (i >= 0) {
        int k = propName.indexOf(PropertyUtils.INDEXED_DELIM2);
        try {
            index = Integer.parseInt(propName.substring(i + 1, k));
        } catch (NumberFormatException e) {
            ;
        }
        propName = propName.substring(0, i);
    }
    int j = propName.indexOf(PropertyUtils.MAPPED_DELIM);
    if (j >= 0) {
        int k = propName.indexOf(PropertyUtils.MAPPED_DELIM2);
        try {
            key = propName.substring(j + 1, k);
        } catch (IndexOutOfBoundsException e) {
            ;
        }
        propName = propName.substring(0, j);
    }

    // Calculate the property type
    if (target instanceof DynaBean) {
        DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return; // Skip this property setter
        }
        type = dynaProperty.getType();
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return; // Skip this property setter
            }
        } catch (NoSuchMethodException e) {
            return; // Skip this property setter
        }
        if (descriptor instanceof MappedPropertyDescriptor) {
            if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();
        } else if (descriptor instanceof IndexedPropertyDescriptor) {
            if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
        } else {
            if (descriptor.getWriteMethod() == null) {
                if (log.isDebugEnabled()) {
                    log.debug("Skipping read-only property");
                }
                return; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
        }
    }

    // Convert the specified value to the required type
    Object newValue = null;
    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value == null) {
            String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert((String[]) values, type);
        } else if (value instanceof String) {
            String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert((String[]) values, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert((String[]) value, type);
        } else {
            newValue = value;
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String) {
            newValue = getConvertUtils().convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = value;
        }
    } else { // Value into scalar
        if ((value instanceof String) || (value == null)) {
            newValue = getConvertUtils().convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type);
        } else if (getConvertUtils().lookup(value.getClass()) != null) {
            newValue = getConvertUtils().convert(value.toString(), type);
        } else {
            newValue = value;
        }
    }

    // Invoke the setter method
    try {
        if (index >= 0) {
            getPropertyUtils().setIndexedProperty(target, propName, index, newValue);
        } else if (key != null) {
            getPropertyUtils().setMappedProperty(target, propName, key, newValue);
        } else {
            getPropertyUtils().setProperty(target, propName, newValue);
        }
    } catch (NoSuchMethodException e) {
        throw new InvocationTargetException(e, "Cannot set " + propName);
    }

}

From source file:org.icelib.beans.ObjectMapping.java

@SuppressWarnings({ "unchecked", "restriction", "rawtypes" })
public static <V> V value(Object value, Class<V> targetClass, Object... constructorArgs) {

    Transformer<Object, V> t = (Transformer<Object, V>) objectConverters
            .get(new ClassKey(value.getClass(), targetClass));
    if (t != null) {
        return (V) (t.transform(value));
    }//  w w w  .  j  av  a2  s . co  m

    if (value instanceof Number) {
        if (targetClass.equals(Long.class) || targetClass.equals(long.class)) {
            return (V) ((Long) (((Number) value).longValue()));
        } else if (targetClass.equals(Double.class) || targetClass.equals(double.class)) {
            return (V) ((Double) (((Number) value).doubleValue()));
        } else if (targetClass.equals(Integer.class) || targetClass.equals(int.class)) {
            return (V) ((Integer) (((Number) value).intValue()));
        } else if (targetClass.equals(Short.class) || targetClass.equals(short.class)) {
            return (V) ((Short) (((Number) value).shortValue()));
        } else if (targetClass.equals(Float.class) || targetClass.equals(float.class)) {
            return (V) ((Float) (((Number) value).floatValue()));
        } else if (targetClass.equals(Byte.class) || targetClass.equals(byte.class)) {
            return (V) ((Byte) (((Number) value).byteValue()));
        } else if (targetClass.equals(Boolean.class) || targetClass.equals(boolean.class)) {
            return (V) ((Boolean) (((Number) value).intValue() != 0));
        } else if (targetClass.equals(String.class)) {
            return (V) (value.toString());
        } else {
            throw new IllegalArgumentException(
                    String.format("Cannot convert number %s to %s", value, targetClass));
        }
    } else if (value instanceof Boolean) {
        return (V) (((Boolean) value));
    } else if (value instanceof String) {
        if (targetClass.equals(Long.class)) {
            return (V) ((Long) Long.parseLong((String) value));
        } else if (targetClass.equals(Double.class)) {
            return (V) ((Double) Double.parseDouble((String) value));
        } else if (targetClass.equals(Integer.class)) {
            return (V) ((Integer) Integer.parseInt((String) value));
        } else if (targetClass.equals(Short.class)) {
            return (V) ((Short) Short.parseShort((String) value));
        } else if (targetClass.equals(Float.class)) {
            return (V) ((Float) Float.parseFloat((String) value));
        } else if (targetClass.equals(Byte.class)) {
            return (V) ((Byte) Byte.parseByte((String) value));
        } else if (targetClass.equals(Boolean.class)) {
            return (V) ((Boolean) Boolean.parseBoolean((String) value));
        } else if (targetClass.equals(String.class)) {
            return (V) (value.toString());
        } else if (targetClass.isEnum()) {
            for (V ev : targetClass.getEnumConstants()) {
                if (ev.toString().toLowerCase().equalsIgnoreCase(value.toString())) {
                    return ev;
                }
            }
            throw new IllegalArgumentException(String.format("Unknown enum %s in %s", value, targetClass));
        } else {
            // Maybe the target has a constructor that takes a string
            try {
                Constructor<V> con = targetClass.getConstructor(String.class);
                return con.newInstance((String) value);
            } catch (NoSuchMethodException nsme) {
                // That's it, give up
                throw new IllegalArgumentException(
                        String.format("Cannot convert string %s to %s", value, targetClass));
            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException e) {
                throw new RuntimeException(e);
            }

        }
    } else if (value instanceof Map) {
        /*
         * This covers ScriptObjectMirror from Nashorn which is a list AND a
         * map describing an object or an array. It also covers ordinary map
         * and lists
         */

        if (isScriptNativeArray(value)) {
            Collection<?> c = ((jdk.nashorn.api.scripting.ScriptObjectMirror) value).values();
            if (c instanceof List && MappedList.class.isAssignableFrom(targetClass)) {
                try {
                    V v = getTargetInstance(value, targetClass, constructorArgs);
                    for (Object o : ((List) c)) {
                        ((List) v).add(o);
                    }
                    return v;
                } catch (NoSuchMethodException e) {
                    throw new IllegalArgumentException(String.format(
                            "No zero-length constructor for class %s and no valid constructor args provided.",
                            targetClass));
                } catch (InstantiationException | SecurityException | IllegalAccessException
                        | IllegalArgumentException | InvocationTargetException e) {
                    throw new RuntimeException(String.format("Could not construct %s", targetClass), e);
                }
            } else if ((List.class.isAssignableFrom(targetClass) && c instanceof List)
                    || (Collection.class.isAssignableFrom(targetClass) && c instanceof Collection)) {
                return (V) c;
            } else if (Set.class.isAssignableFrom(targetClass)) {
                return (V) new LinkedHashSet<Object>(c);
            } else if (Collection.class.isAssignableFrom(targetClass)) {
                return (V) new ArrayList<Object>(c);
            } else if (targetClass.isArray()) {
                return (V) c.toArray((Object[]) Array.newInstance(targetClass.getComponentType(), c.size()));
            }
        } else if (value instanceof List && List.class.isAssignableFrom(targetClass)) {
            return (V) ((List<?>) value);
        } else if (!isScriptNativeObject(value) && Map.class.isAssignableFrom(targetClass)) {
            return (V) ((Map<?, ?>) value);
        } else {
            try {
                V v = getTargetInstance(value, targetClass, constructorArgs);
                ObjectMapper<?> m = new ObjectMapper<>(v);
                try {
                    m.map((Map<String, Object>) value);
                } catch (Exception e) {
                    throw new RuntimeException(String.format("Failed to map %s.", targetClass), e);
                }
                return v;
            } catch (NoSuchMethodException e) {
                throw new IllegalArgumentException(String.format(
                        "No zero-length constructor for class %s and no valid constructor args provided.",
                        targetClass));
            } catch (InstantiationException | SecurityException | IllegalAccessException
                    | IllegalArgumentException | InvocationTargetException e) {
                throw new RuntimeException(String.format("Could not construct %s", targetClass), e);
            }
        }
    } else if (targetClass.isAssignableFrom(value.getClass())) {
        return (V) value;
    } else if (value instanceof Collection && List.class.isAssignableFrom(targetClass)) {
        try {
            V v = getTargetInstance(value, targetClass, constructorArgs);
            ((List) v).addAll((Collection) value);
            return v;
        } catch (InstantiationException | SecurityException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException e) {
            throw new RuntimeException(String.format("Could not construct %s", targetClass), e);
        } catch (NoSuchMethodException nse) {
        }
    }
    throw new IllegalArgumentException(
            String.format("Cannot convert %s (%s) to %s", value, value.getClass(), targetClass));
}

From source file:org.apache.axis.utils.JavaUtils.java

/** Utility function to convert an Object to some desired Class.
 *
 * Right now this works for://w w w  . j  a v  a 2s.co m
 *     arrays <-> Lists,
 *     Holders <-> held values
 * @param arg the array to convert
 * @param destClass the actual class we want
 */
public static Object convert(Object arg, Class destClass) {
    if (destClass == null) {
        return arg;
    }

    Class argHeldType = null;
    if (arg != null) {
        argHeldType = getHolderValueType(arg.getClass());
    }

    if (arg != null && argHeldType == null && destClass.isAssignableFrom(arg.getClass())) {
        return arg;
    }

    if (log.isDebugEnabled()) {
        String clsName = "null";
        if (arg != null)
            clsName = arg.getClass().getName();
        log.debug(Messages.getMessage("convert00", clsName, destClass.getName()));
    }

    // See if a previously converted value is stored in the argument.
    Object destValue = null;
    if (arg instanceof ConvertCache) {
        destValue = ((ConvertCache) arg).getConvertedValue(destClass);
        if (destValue != null)
            return destValue;
    }

    // Get the destination held type or the argument held type if they exist
    Class destHeldType = getHolderValueType(destClass);

    // Convert between Axis special purpose HexBinary and byte[]
    if (arg instanceof HexBinary && destClass == byte[].class) {
        return ((HexBinary) arg).getBytes();
    } else if (arg instanceof byte[] && destClass == HexBinary.class) {
        return new HexBinary((byte[]) arg);
    }

    // Convert between Calendar and Date
    if (arg instanceof Calendar && destClass == Date.class) {
        return ((Calendar) arg).getTime();
    }
    if (arg instanceof Date && destClass == Calendar.class) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime((Date) arg);
        return calendar;
    }

    // Convert between Calendar and java.sql.Date
    if (arg instanceof Calendar && destClass == java.sql.Date.class) {
        return new java.sql.Date(((Calendar) arg).getTime().getTime());
    }

    // Convert between HashMap and Hashtable
    if (arg instanceof HashMap && destClass == Hashtable.class) {
        return new Hashtable((HashMap) arg);
    }

    // Convert an AttachmentPart to the given destination class.
    if (isAttachmentSupported()
            && (arg instanceof InputStream || arg instanceof AttachmentPart || arg instanceof DataHandler)) {
        try {
            String destName = destClass.getName();
            if (destClass == String.class || destClass == OctetStream.class || destClass == byte[].class
                    || destClass == Image.class || destClass == Source.class || destClass == DataHandler.class
                    || destName.equals("javax.mail.internet.MimeMultipart")) {
                DataHandler handler = null;
                if (arg instanceof AttachmentPart) {
                    handler = ((AttachmentPart) arg).getDataHandler();
                } else if (arg instanceof DataHandler) {
                    handler = (DataHandler) arg;
                }
                if (destClass == Image.class) {
                    // Note:  An ImageIO component is required to process an Image
                    // attachment, but if the image would be null
                    // (is.available == 0) then ImageIO component isn't needed
                    // and we can return null.
                    InputStream is = handler.getInputStream();
                    if (is.available() == 0) {
                        return null;
                    } else {
                        ImageIO imageIO = ImageIOFactory.getImageIO();
                        if (imageIO != null) {
                            return getImageFromStream(is);
                        } else {
                            log.info(Messages.getMessage("needImageIO"));
                            return arg;
                        }
                    }
                } else if (destClass == javax.xml.transform.Source.class) {
                    // For a reason unknown to me, the handler's
                    // content is a String.  Convert it to a
                    // StreamSource.
                    return new StreamSource(handler.getInputStream());
                } else if (destClass == OctetStream.class || destClass == byte[].class) {
                    InputStream in = null;
                    if (arg instanceof InputStream) {
                        in = (InputStream) arg;
                    } else {
                        in = handler.getInputStream();
                    }
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int byte1 = -1;
                    while ((byte1 = in.read()) != -1)
                        baos.write(byte1);
                    return new OctetStream(baos.toByteArray());
                } else if (destClass == DataHandler.class) {
                    return handler;
                } else {
                    return handler.getContent();
                }
            }
        } catch (IOException ioe) {
        } catch (SOAPException se) {
        }
    }

    // If the destination is an array and the source
    // is a suitable component, return an array with 
    // the single item.
    if (arg != null && destClass.isArray() && !destClass.getComponentType().equals(Object.class)
            && destClass.getComponentType().isAssignableFrom(arg.getClass())) {
        Object array = Array.newInstance(destClass.getComponentType(), 1);
        Array.set(array, 0, arg);
        return array;
    }

    // in case destClass is array and arg is ArrayOfT class. (ArrayOfT -> T[])
    if (arg != null && destClass.isArray()) {
        Object newArg = ArrayUtil.convertObjectToArray(arg, destClass);
        if (newArg == null || (newArg != ArrayUtil.NON_CONVERTABLE && newArg != arg)) {
            return newArg;
        }
    }

    // in case arg is ArrayOfT and destClass is an array. (T[] -> ArrayOfT)
    if (arg != null && arg.getClass().isArray()) {
        Object newArg = ArrayUtil.convertArrayToObject(arg, destClass);
        if (newArg != null)
            return newArg;
    }

    // Return if no conversion is available
    if (!(arg instanceof Collection || (arg != null && arg.getClass().isArray()))
            && ((destHeldType == null && argHeldType == null)
                    || (destHeldType != null && argHeldType != null))) {
        return arg;
    }

    // Take care of Holder conversion
    if (destHeldType != null) {
        // Convert arg into Holder holding arg.
        Object newArg = convert(arg, destHeldType);
        Object argHolder = null;
        try {
            argHolder = destClass.newInstance();
            setHolderValue(argHolder, newArg);
            return argHolder;
        } catch (Exception e) {
            return arg;
        }
    } else if (argHeldType != null) {
        // Convert arg into the held type
        try {
            Object newArg = getHolderValue(arg);
            return convert(newArg, destClass);
        } catch (HolderException e) {
            return arg;
        }
    }

    // Flow to here indicates that neither arg or destClass is a Holder

    // Check to see if the argument has a prefered destination class.
    if (arg instanceof ConvertCache && ((ConvertCache) arg).getDestClass() != destClass) {
        Class hintClass = ((ConvertCache) arg).getDestClass();
        if (hintClass != null && hintClass.isArray() && destClass.isArray()
                && destClass.isAssignableFrom(hintClass)) {
            destClass = hintClass;
            destValue = ((ConvertCache) arg).getConvertedValue(destClass);
            if (destValue != null)
                return destValue;
        }
    }

    if (arg == null) {
        return arg;
    }

    // The arg may be an array or List 
    int length = 0;
    if (arg.getClass().isArray()) {
        length = Array.getLength(arg);
    } else {
        length = ((Collection) arg).size();
    }
    if (destClass.isArray()) {
        if (destClass.getComponentType().isPrimitive()) {

            Object array = Array.newInstance(destClass.getComponentType(), length);
            // Assign array elements
            if (arg.getClass().isArray()) {
                for (int i = 0; i < length; i++) {
                    Array.set(array, i, Array.get(arg, i));
                }
            } else {
                int idx = 0;
                for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) {
                    Array.set(array, idx++, i.next());
                }
            }
            destValue = array;

        } else {
            Object[] array;
            try {
                array = (Object[]) Array.newInstance(destClass.getComponentType(), length);
            } catch (Exception e) {
                return arg;
            }

            // Use convert to assign array elements.
            if (arg.getClass().isArray()) {
                for (int i = 0; i < length; i++) {
                    array[i] = convert(Array.get(arg, i), destClass.getComponentType());
                }
            } else {
                int idx = 0;
                for (Iterator i = ((Collection) arg).iterator(); i.hasNext();) {
                    array[idx++] = convert(i.next(), destClass.getComponentType());
                }
            }
            destValue = array;
        }
    } else if (Collection.class.isAssignableFrom(destClass)) {
        Collection newList = null;
        try {
            // if we are trying to create an interface, build something
            // that implements the interface
            if (destClass == Collection.class || destClass == List.class) {
                newList = new ArrayList();
            } else if (destClass == Set.class) {
                newList = new HashSet();
            } else {
                newList = (Collection) destClass.newInstance();
            }
        } catch (Exception e) {
            // Couldn't build one for some reason... so forget it.
            return arg;
        }

        if (arg.getClass().isArray()) {
            for (int j = 0; j < length; j++) {
                newList.add(Array.get(arg, j));
            }
        } else {
            for (Iterator j = ((Collection) arg).iterator(); j.hasNext();) {
                newList.add(j.next());
            }
        }
        destValue = newList;
    } else {
        destValue = arg;
    }

    // Store the converted value in the argument if possible.
    if (arg instanceof ConvertCache) {
        ((ConvertCache) arg).setConvertedValue(destClass, destValue);
    }
    return destValue;
}

From source file:nl.strohalm.cyclos.utils.binding.CustomBeanUtilsBean.java

@Override
public void setProperty(final Object bean, String name, final Object value)
        throws IllegalAccessException, InvocationTargetException {

    // Resolve any nested expression to get the actual target bean
    Object target = bean;//from w  w w .j  a  va  2  s  .  c o  m
    final int delim = findLastNestedIndex(name);
    if (delim >= 0) {
        try {
            target = getPropertyUtils().getProperty(bean, name.substring(0, delim));
        } catch (final NoSuchMethodException e) {
            return; // Skip this property setter
        }
        name = name.substring(delim + 1);
    }

    // Declare local variables we will require
    String propName = null; // Simple name of target property
    Class<?> type = null; // Java type of target property
    int index = -1; // Indexed subscript value (if any)
    String key = null; // Mapped key value (if any)

    // Calculate the property name, index, and key values
    propName = name;
    final int i = propName.indexOf(PropertyUtils.INDEXED_DELIM);
    if (i >= 0) {
        final int k = propName.indexOf(PropertyUtils.INDEXED_DELIM2);
        try {
            index = Integer.parseInt(propName.substring(i + 1, k));
        } catch (final NumberFormatException e) {
            // Ignore
        }
        propName = propName.substring(0, i);
    }
    final int j = propName.indexOf(PropertyUtils.MAPPED_DELIM);
    if (j >= 0) {
        final int k = propName.indexOf(PropertyUtils.MAPPED_DELIM2);
        try {
            key = propName.substring(j + 1, k);
        } catch (final IndexOutOfBoundsException e) {
            // Ignore
        }
        propName = propName.substring(0, j);
    }

    // Calculate the property type
    if (target instanceof DynaBean) {
        final DynaClass dynaClass = ((DynaBean) target).getDynaClass();
        final DynaProperty dynaProperty = dynaClass.getDynaProperty(propName);
        if (dynaProperty == null) {
            return; // Skip this property setter
        }
        type = dynaProperty.getType();
        if (type.isArray() || Collection.class.isAssignableFrom(type)) {
            type = Object[].class;
        }
    } else {
        PropertyDescriptor descriptor = null;
        try {
            descriptor = getPropertyUtils().getPropertyDescriptor(target, name);
            if (descriptor == null) {
                return; // Skip this property setter
            }
        } catch (final NoSuchMethodException e) {
            return; // Skip this property setter
        }
        if (descriptor instanceof MappedPropertyDescriptor) {
            if (((MappedPropertyDescriptor) descriptor).getMappedWriteMethod() == null) {
                return; // Read-only, skip this property setter
            }
            type = ((MappedPropertyDescriptor) descriptor).getMappedPropertyType();

            /**
             * Overriden behaviour ------------------- When a type is Object on a mapped property, retrieve the value to check if it's an array
             */
            if (Object.class.equals(type)) {
                try {
                    final Object retrieved = getPropertyUtils().getMappedProperty(target, propName, key);
                    if (retrieved != null) {
                        final Class<?> retrievedType = retrieved.getClass();
                        if (retrievedType.isArray() || Collection.class.isAssignableFrom(retrievedType)) {
                            type = Object[].class;
                        }
                    }
                } catch (final NoSuchMethodException e) {
                    throw new PropertyException(target, propName + "(" + key + ")");
                }
            }
        } else if (descriptor instanceof IndexedPropertyDescriptor) {
            if (((IndexedPropertyDescriptor) descriptor).getIndexedWriteMethod() == null) {
                return; // Read-only, skip this property setter
            }
            type = ((IndexedPropertyDescriptor) descriptor).getIndexedPropertyType();
        } else {
            if (descriptor.getWriteMethod() == null) {
                return; // Read-only, skip this property setter
            }
            type = descriptor.getPropertyType();
        }
    }

    /**
     * Overriden behaviour ------------------- When a type is Map on a mapped property, retrieve the value to check if it's an array
     */
    if (Map.class.isAssignableFrom(type) && StringUtils.isNotEmpty(key)) {
        try {
            final Map<?, ?> map = (Map<?, ?>) getPropertyUtils().getProperty(target, propName);
            final Object retrieved = map.get(key);
            if (retrieved != null) {
                final Class<?> retrievedType = retrieved.getClass();
                if (retrievedType.isArray() || Collection.class.isAssignableFrom(retrievedType)) {
                    type = Object[].class;
                }
            }
        } catch (final NoSuchMethodException e) {
            throw new PropertyException(target, propName + "(" + key + ")");
        }
    }

    // Convert the specified value to the required type
    Object newValue = null;
    if (type.isArray() && (index < 0)) { // Scalar value into array
        if (value == null) {
            final String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert(values, type);
        } else if (value instanceof String) {
            final String values[] = new String[1];
            values[0] = (String) value;
            newValue = getConvertUtils().convert(values, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert((String[]) value, type);
        } else {
            newValue = value;
        }
    } else if (type.isArray()) { // Indexed value into array
        if (value instanceof String) {
            newValue = getConvertUtils().convert((String) value, type.getComponentType());
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type.getComponentType());
        } else {
            newValue = value;
        }
    } else { // Value into scalar
        if ((value instanceof String) || (value == null)) {
            newValue = getConvertUtils().convert((String) value, type);
        } else if (value instanceof String[]) {
            newValue = getConvertUtils().convert(((String[]) value)[0], type);
        } else if (getConvertUtils().lookup(value.getClass()) != null) {
            newValue = getConvertUtils().convert(value.toString(), type);
        } else {
            newValue = value;
        }
    }

    // Invoke the setter method
    try {
        if (index >= 0) {
            getPropertyUtils().setIndexedProperty(target, propName, index, newValue);
        } else if (key != null) {
            getPropertyUtils().setMappedProperty(target, propName, key, newValue);
        } else {
            getPropertyUtils().setProperty(target, propName, newValue);
        }
    } catch (final NoSuchMethodException e) {
        throw new InvocationTargetException(e, "Cannot set " + propName);
    }

}