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:com.ms.commons.summer.web.handler.DataBinderUtil.java

/**
 * ?//from   w  w w  .ja v  a2s  .co  m
 * 
 * @param method
 * @param model
 * @param request
 * @param response
 * @param c
 * @return
 */
@SuppressWarnings("unchecked")
public static Object[] getArgs(Method method, Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response, Class<?> c) {
    Class<?>[] paramTypes = method.getParameterTypes();
    Object[] args = new Object[paramTypes.length];
    Map<String, Object> argMap = new HashMap<String, Object>(args.length);
    Map<String, String> pathValues = null;
    PathPattern pathPattern = method.getAnnotation(PathPattern.class);
    if (pathPattern != null) {
        String path = request.getRequestURI();
        int index = path.lastIndexOf('.');
        if (index != -1) {
            path = path.substring(0, index);
            String[] patterns = pathPattern.patterns();
            pathValues = getPathValues(patterns, path);
        }
    }
    MapBindingResult errors = new MapBindingResult(argMap, "");
    ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
    for (int i = 0; i < paramTypes.length; i++) {
        Class<?> paramType = paramTypes[i];

        MethodParameter methodParam = new MethodParameter(method, i);
        methodParam.initParameterNameDiscovery(parameterNameDiscoverer);
        GenericTypeResolver.resolveParameterType(methodParam, c.getClass());

        String paramName = methodParam.getParameterName();
        // map
        if (Map.class.isAssignableFrom(paramType)) {
            args[i] = model;
        }
        // HttpServletRequest
        else if (HttpServletRequest.class.isAssignableFrom(paramType)) {
            args[i] = request;
        }
        // HttpServletResponse
        else if (HttpServletResponse.class.isAssignableFrom(paramType)) {
            args[i] = response;
        }
        // HttpSession
        else if (HttpSession.class.isAssignableFrom(paramType)) {
            args[i] = request.getSession();
        }
        // Errors
        else if (Errors.class.isAssignableFrom(paramType)) {
            args[i] = errors;
        }
        // MultipartFile
        else if (MultipartFile.class.isAssignableFrom(paramType)) {
            MultipartFile[] files = resolveMultipartFiles(request, errors, paramName);
            if (files != null && files.length > 0) {
                args[i] = files[0];
            }
        }
        // MultipartFile[]
        else if (MultipartFile[].class.isAssignableFrom(paramType)) {
            args[i] = resolveMultipartFiles(request, errors, paramName);
        } else {
            // ??
            if (BeanUtils.isSimpleProperty(paramType)) {
                SimpleTypeConverter converter = new SimpleTypeConverter();
                Object value;
                // ?
                if (paramType.isArray()) {
                    value = request.getParameterValues(paramName);
                } else {
                    Object[] parameterAnnotations = methodParam.getParameterAnnotations();
                    value = null;
                    if (parameterAnnotations != null && parameterAnnotations.length > 0) {
                        if (pathValues != null && pathValues.size() > 0) {
                            for (Object object : parameterAnnotations) {
                                if (PathVariable.class.isInstance(object)) {
                                    PathVariable pv = (PathVariable) object;
                                    if (StringUtils.isEmpty(pv.value())) {
                                        value = pathValues.get(paramName);
                                    } else {
                                        value = pathValues.get(pv.value());
                                    }
                                    break;
                                }
                            }
                        }
                    } else {
                        value = request.getParameter(paramName);
                    }
                }
                try {
                    args[i] = converter.convertIfNecessary(value, paramType, methodParam);
                    model.put(paramName, args[i]);
                } catch (TypeMismatchException e) {
                    errors.addError(new FieldError(paramName, paramName, e.getMessage()));
                }
            } else {
                // ???POJO
                if (paramType.isArray()) {
                    ObjectArrayDataBinder binder = new ObjectArrayDataBinder(paramType.getComponentType(),
                            paramName);
                    args[i] = binder.bind(request);
                    model.put(paramName, args[i]);
                } else {
                    Object bindObject = BeanUtils.instantiateClass(paramType);
                    SummerServletRequestDataBinder binder = new SummerServletRequestDataBinder(bindObject,
                            paramName);
                    binder.bind(request);
                    BindException be = new BindException(binder.getBindingResult());
                    List<FieldError> fieldErrors = be.getFieldErrors();
                    for (FieldError fieldError : fieldErrors) {
                        errors.addError(fieldError);
                    }
                    args[i] = binder.getTarget();
                    model.put(paramName, args[i]);
                }
            }
        }
    }
    return args;
}

From source file:org.j2free.admin.ReflectionMarshaller.java

/**
 * /*  w ww.j a va2 s . co m*/
 * @param entity
 * @param parameterMap
 * @param controller
 * @return
 * @throws MarshallingException
 */
public Object marshallIn(Object entity, Map<String, String[]> parameterMap, Controller controller)
        throws MarshallingException {
    Field field;
    Converter converter;
    Method setter;
    String[] newValues;

    log.debug("Marshalling in instance of " + entity.getClass().getSimpleName());

    boolean error = false, success = false, isEntity = false, isCollection = false;

    Class collectionType;
    Class fieldType;

    for (Map.Entry<Field, Converter> ent : instructions.entrySet()) {

        // reset flags
        error = success = isEntity = isCollection = false;

        field = ent.getKey();
        converter = ent.getValue();

        if (converter.isReadOnly()) {
            log.debug("Skipping read-only field " + field.getName());
            continue;
        }

        newValues = parameterMap.get(field.getName());

        if (newValues == null || newValues.length == 0) {
            log.debug("Skipping field " + field.getName() + ", no new value set.");
            continue;
        }

        isEntity = converter.isEntity();
        isCollection = converter.isCollection();

        fieldType = field.getType();
        collectionType = isCollection ? converter.getType() : null;

        log.debug("Marshalling in field " + field.getName());

        // try to get the original value
        try {
            if (!field.isAccessible()) {
                field.setAccessible(true);
            }
            if (field.isAccessible()) {
                log.debug(field.getName() + " is accessible");
                if (!isEntity && !isCollection) {

                    log.debug("!isEntity && !isCollection");

                    // if it's an array, it needs special treatment
                    if (fieldType.isArray()) {
                        log.debug(field.getName() + " is an Array");

                        Class arrayType = fieldType.getComponentType();

                        // If we can, just convert with a cast()
                        if (arrayType.isAssignableFrom(String.class)) {
                            log.debug(arrayType.getName() + " is assignable from String.class");

                            Object[] newArray = new Object[newValues.length];
                            for (int i = 0; i < newValues.length; i++) {
                                newArray[i] = arrayType.cast(newValues[i]);
                            }
                            field.set(entity, newArray);

                        } else {

                            if (isInteger(fieldType)) {

                                Integer[] newArray = new Integer[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Integer.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isFloat(fieldType)) {

                                Float[] newArray = new Float[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Float.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isDouble(fieldType)) {

                                Double[] newArray = new Double[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Double.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isShort(fieldType)) {

                                Short[] newArray = new Short[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Short.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isChar(fieldType)) {

                                field.set(entity, ServletUtils.join(newValues, "").toCharArray());

                            } else if (isLong(fieldType)) {

                                Long[] newArray = new Long[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Long.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isBoolean(fieldType)) {

                                Boolean[] newArray = new Boolean[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Boolean.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else if (isByte(fieldType)) {

                                Byte[] newArray = new Byte[newValues.length];
                                for (int i = 0; i < newValues.length; i++) {
                                    newArray[i] = Byte.valueOf(newValues[i]);
                                }
                                field.set(entity, newArray);

                            } else {
                                throw new MarshallingException(
                                        "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = "
                                                + field.getName());
                            }
                        }

                    } else {

                        // Check out if it's assignable via a straight cast,
                        // that could save time
                        if (fieldType.isAssignableFrom(String.class)) {
                            log.debug(fieldType.getName() + " is assignable from String.class");
                            // this might throw an exception, but we're going
                            // to ignore it because there are other ways of
                            // setting the value if this doesn't work.
                            try {
                                field.set(entity, fieldType.cast(newValues[0]));
                                log.debug("Assigned via cast");
                            } catch (Exception e) {
                                log.debug("Error setting field by cast", e);
                            }
                            success = true;
                        }

                        // if it wasn't assignable via a straight cast, try
                        // working around it.
                        if (!success) {
                            if (isInteger(fieldType) && !newValues[0].equals("")) {
                                field.setInt(entity, Integer.valueOf(newValues[0]));
                            } else if (isFloat(fieldType) && !newValues[0].equals("")) {
                                field.setFloat(entity, Float.valueOf(newValues[0]));
                            } else if (isDouble(fieldType) && !newValues[0].equals("")) {
                                field.setDouble(entity, Double.valueOf(newValues[0]));
                            } else if (isShort(fieldType) && !newValues[0].equals("")) {
                                field.setShort(entity, Short.valueOf(newValues[0]));
                            } else if (isChar(fieldType)) {
                                field.setChar(entity, newValues[0].charAt(0));
                            } else if (isLong(fieldType) && !newValues[0].equals("")) {
                                field.setLong(entity, Long.valueOf(newValues[0]));
                            } else if (isBoolean(fieldType) && !newValues[0].equals("")) {
                                field.setBoolean(entity, Boolean.valueOf(newValues[0]));
                            } else if (isByte(fieldType) && !newValues[0].equals("")) {
                                field.setByte(entity, Byte.valueOf(newValues[0]));
                            } else if (isDate(fieldType)) {
                                if (newValues[0].equals("")) {
                                    field.set(entity, null);
                                } else {
                                    try {
                                        field.set(entity, asDate(newValues[0]));
                                    } catch (ParseException pe) {
                                        log.warn("Error parsing date: " + newValues[0], pe);
                                    }
                                }
                            } else if (!newValues[0].equals("")) {
                                log.debug("Not sure how to set " + field.getName() + " of type "
                                        + fieldType.getName() + ", attemping cast.");
                                field.set(entity, fieldType.cast(newValues[0]));
                            } else if (newValues[0].equals("")) {
                                log.debug("Skipping field " + field.getName()
                                        + ", empty string value passed in.");
                            }
                        }
                    }

                } else if (isEntity && !isCollection) {

                    log.debug("isEntity && !isCollection");

                    ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType);
                    field.set(entity, controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0])));

                } else if (!isEntity && isCollection) {

                    log.debug("!isEntity && isCollection");

                    throw new MarshallingException("Error, collections of non-entities are not yet supported.");

                } else if (isEntity && isCollection) {

                    log.debug("isEntity && isCollection");

                    // for now, this is going to expect the parameter to be a
                    // comma-delimited string of entity ids
                    String[] idsString = newValues[0].toString().split(",");
                    Collection collection = (Collection) field.get(entity);

                    log.debug("newValues.length = " + newValues.length);
                    log.debug("newValues[0] = " + newValues[0]);
                    log.debug("idsString.length = " + idsString.length);

                    if (collection == null)
                        collection = new LinkedList();

                    collection.clear();

                    if (idsString.length > 0) {

                        ReflectionMarshaller collectionMarshaller = ReflectionMarshaller
                                .getForClass(collectionType);

                        log.debug("CollectionType = " + collectionType.getName());

                        for (String idString : idsString) {
                            if (idString.equals("")) {
                                log.debug("Skipping empty idString");
                                continue;
                            }
                            collection.add(
                                    controller.proxy(collectionType, collectionMarshaller.asIdType(idString)));
                        }

                    }

                    field.set(entity, collection);
                }
            } else {
                error = true;
            }
        } catch (IllegalAccessException iae) {
            log.error("Unable to set " + field.getName() + " directly.", iae);
            error = true;
        } catch (ClassCastException cce) {
            log.error("Error setting " + field.getName() + ".", cce);
            error = true;
        }

        // if we hit an error getting it directly, try via the getter
        if (error) {
            error = false;
            try {
                setter = converter.getSetter();
                if (setter != null) {
                    if (!setter.isAccessible()) {
                        setter.setAccessible(true);
                    }
                    if (setter.isAccessible()) {
                        if (!isEntity && !isCollection) {

                            // if it's an array, it needs special treatment
                            if (fieldType.isArray()) {
                                log.debug(field.getName() + " is an Array");

                                Class arrayType = fieldType.getComponentType();

                                // If we can, just convert with a cast()
                                if (arrayType.isAssignableFrom(String.class)) {
                                    log.debug(arrayType.getName() + " is assignable from String.class");

                                    Object[] newArray = new Object[newValues.length];
                                    for (int i = 0; i < newValues.length; i++) {
                                        newArray[i] = arrayType.cast(newValues[i]);
                                    }
                                    setter.invoke(entity, newArray);

                                } else {

                                    if (isInteger(fieldType)) {

                                        Integer[] newArray = new Integer[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Integer.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isFloat(fieldType)) {

                                        Float[] newArray = new Float[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Float.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isDouble(fieldType)) {

                                        Double[] newArray = new Double[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Double.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isShort(fieldType)) {

                                        Short[] newArray = new Short[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Short.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isChar(fieldType)) {

                                        setter.invoke(entity, ServletUtils.join(newValues, "").toCharArray());

                                    } else if (isLong(fieldType)) {

                                        Long[] newArray = new Long[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Long.valueOf(newValues[i]);
                                        }
                                        field.set(entity, (Object[]) newArray);

                                    } else if (isBoolean(fieldType)) {

                                        Boolean[] newArray = new Boolean[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Boolean.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else if (isByte(fieldType)) {

                                        Byte[] newArray = new Byte[newValues.length];
                                        for (int i = 0; i < newValues.length; i++) {
                                            newArray[i] = Byte.valueOf(newValues[i]);
                                        }
                                        setter.invoke(entity, (Object[]) newArray);

                                    } else {
                                        throw new MarshallingException(
                                                "Don't know how to marshall an array of a non-primitive, and non-assignable type! field = "
                                                        + field.getName());
                                    }
                                }

                            } else {
                                // Check out if it's assignable via a straight cast,
                                // that could save time
                                if (fieldType.isAssignableFrom(String.class)) {
                                    log.debug(fieldType.getName() + " is assignable from String.class");
                                    // this might throw an exception, but we're going
                                    // to ignore it because there are other ways of
                                    // setting the value if this doesn't work.
                                    try {
                                        setter.invoke(entity, fieldType.cast(newValues[0]));
                                    } catch (Exception e) {
                                        log.debug("Error setting field by cast", e);
                                    }
                                    success = true;
                                }

                                // if it wasn't assignable via a straight cast, try
                                // working around it.
                                if (!success) {
                                    if (isInteger(fieldType)) {
                                        setter.invoke(entity, Integer.valueOf(newValues[0]));
                                    } else if (isFloat(fieldType)) {
                                        setter.invoke(entity, Float.valueOf(newValues[0]));
                                    } else if (isDouble(fieldType)) {
                                        setter.invoke(entity, Double.valueOf(newValues[0]));
                                    } else if (isShort(fieldType)) {
                                        setter.invoke(entity, Short.valueOf(newValues[0]));
                                    } else if (isChar(fieldType)) {
                                        setter.invoke(entity, newValues[0].charAt(0));
                                    } else if (isLong(fieldType)) {
                                        setter.invoke(entity, Long.valueOf(newValues[0]));
                                    } else if (isBoolean(fieldType)) {
                                        setter.invoke(entity, Boolean.valueOf(newValues[0]));
                                    } else if (isByte(fieldType)) {
                                        setter.invoke(entity, Byte.valueOf(newValues[0]));
                                    } else if (isDate(fieldType)) {
                                        if (newValues[0].equals("")) {
                                            field.set(entity, null);
                                        } else {
                                            try {
                                                setter.invoke(entity, asDate(newValues[0]));
                                            } catch (ParseException pe) {
                                                log.warn("Error parsing date: " + newValues[0], pe);
                                            }
                                        }
                                    } else {
                                        log.debug("Not sure how to set " + field.getName() + " of type "
                                                + fieldType.getName() + ", attemping cast.");
                                        setter.invoke(entity, fieldType.cast(newValues[0]));
                                    }
                                }
                            }

                        } else if (isEntity && !isCollection) {

                            ReflectionMarshaller innerMarshaller = ReflectionMarshaller.getForClass(fieldType);
                            setter.invoke(entity,
                                    controller.proxy(fieldType, innerMarshaller.asIdType(newValues[0])));

                        } else if (!isEntity && isCollection) {

                            throw new MarshallingException(
                                    "Error, collections of non-entities are not yet supported.");

                        } else if (isEntity && isCollection) {
                            // for now, this is going to expect the parameter to be a
                            // comma-delimited string of entity ids
                            String[] idsString = newValues[0].toString().split(",");
                            Collection collection = (Collection) field.get(entity);

                            if (collection == null)
                                collection = new LinkedList();

                            if (idsString.length == 0 && collection.isEmpty())
                                continue;

                            collection.clear();

                            if (idsString.length > 0) {

                                ReflectionMarshaller collectionMarshaller = ReflectionMarshaller
                                        .getForClass(collectionType);

                                for (String idString : idsString) {
                                    if (idString.equals("")) {
                                        log.debug("Skipping empty idString");
                                        continue;
                                    }
                                    collection.add(controller.proxy(collectionType,
                                            collectionMarshaller.asIdType(idString)));
                                }
                            }

                            setter.invoke(entity, collection);
                        }
                    } else {
                        error = true;
                    }
                } else {
                    error = true;
                }
            } catch (IllegalAccessException iae) {
                log.error("Error accessing setter", iae);
                error = true;
            } catch (InvocationTargetException ite) {
                log.error("Error invoking setter", ite);
                error = true;
            }
        }

        if (error) {
            throw new MarshallingException("Unable to marshall in field " + field.getName() + ".");
        }
    }
    return entity;
}

From source file:com.bstek.dorado.config.xml.XmlParserHelper.java

protected XmlParserInfo getPropertyXmlParserInfo(Context context, Class<?> beanType, String propertyName,
        TypeInfo typeInfo, XmlProperty xmlProperty) throws Exception {
    XmlParser propertyParser = null;// w w  w  .j  ava  2 s  .  c o m

    Class<?> propertyType = (typeInfo != null) ? typeInfo.getType() : null;
    if (xmlProperty != null) {
        if (StringUtils.isNotEmpty(xmlProperty.propertyType())) {
            typeInfo = TypeInfo.parse(xmlProperty.propertyType());
            propertyType = typeInfo.getType();
        }
        if (StringUtils.isNotEmpty(xmlProperty.propertyType())) {
            propertyType = ClassUtils.forName(xmlProperty.propertyType());
        }

        if (xmlProperty.unsupported()) {
            propertyParser = beanFactory.getBean(UNSUPPORT_PARSER, XmlParser.class);
        } else if (xmlProperty.ignored()) {
            propertyParser = beanFactory.getBean(IGNORE_PARSER, XmlParser.class);
        } else if (StringUtils.isNotEmpty(xmlProperty.parser())) {
            propertyParser = (XmlParser) BeanFactoryUtils.getBean(xmlProperty.parser());
        } else {
            if (xmlProperty.composite()) {
                CompositePropertyParser compositePropertyParser = beanFactory.getBean(COMPOSITE_PROPERTY_PARSER,
                        CompositePropertyParser.class);

                compositePropertyParser.setImpl(propertyType.getName());
                compositePropertyParser.setOpen(Map.class.isAssignableFrom(propertyType));
                if (!compositePropertyParser.isOpen()) {
                    initObjectParser(compositePropertyParser);
                }

                propertyParser = compositePropertyParser;
            } else {
                ExpressionMode expressionMode = xmlProperty.expressionMode();
                if (ExpressionMode.NORMAL.equals(expressionMode)) {
                    propertyParser = beanFactory.getBean(STATIC_PROPERTY_PARSER, XmlParser.class);
                }
            }
        }
    }

    if (propertyParser == null && propertyType != null) {
        if (propertyType.equals(Class.class)) {
            propertyParser = beanFactory.getBean(CLASS_TYPE_PROPERTY_PARSER, XmlParser.class);
        } else if (propertyType.isArray() && propertyType.getComponentType().equals(String.class)) {
            propertyParser = beanFactory.getBean(STRING_ARRAY_PROPERTY_PARSER, XmlParser.class);
        } else if (propertyType.equals(Object.class)) {
            propertyParser = beanFactory.getBean(DATA_PROPERTY_PARSER, XmlParser.class);
        }
    }

    if (propertyParser != null) {
        return new XmlParserInfo(propertyName, propertyParser);
    } else {
        return null;
    }
}

From source file:org.pushio.webapp.helper.json.SerializeConfig.java

public ObjectSerializer getObjectWriter(Class<?> clazz) {
    ObjectSerializer writer = get(clazz);

    if (writer == null) {
        try {/*from w w w  .  java2 s .  c  om*/
            final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            for (Object o : ServiceLoader.load(AutowiredObjectSerializer.class, classLoader)) {
                if (!(o instanceof AutowiredObjectSerializer)) {
                    continue;
                }
                AutowiredObjectSerializer autowired = (AutowiredObjectSerializer) o;
                for (Type forType : autowired.getAutowiredFor()) {
                    put(forType, autowired);
                }
            }
        } catch (ClassCastException ex) {
            // skip
        }
        writer = get(clazz);
    }

    if (writer == null) {
        final ClassLoader classLoader = JSON.class.getClassLoader();
        if (classLoader != Thread.currentThread().getContextClassLoader()) {
            try {
                for (Object o : ServiceLoader.load(AutowiredObjectSerializer.class, classLoader)) {

                    if (!(o instanceof AutowiredObjectSerializer)) {
                        continue;
                    }

                    AutowiredObjectSerializer autowired = (AutowiredObjectSerializer) o;
                    for (Type forType : autowired.getAutowiredFor()) {
                        put(forType, autowired);
                    }
                }
            } catch (ClassCastException ex) {
                // skip
            }

            writer = get(clazz);
        }
    }

    if (writer == null) {
        if (Map.class.isAssignableFrom(clazz)) {
            put(clazz, MapSerializer.instance);
        } else if (List.class.isAssignableFrom(clazz)) {
            put(clazz, MyListSerializer.instance);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            put(clazz, MyCollectionSerializer.instance);
        } else if (Date.class.isAssignableFrom(clazz)) {
            put(clazz, DateSerializer.instance);
        } else if (JSONAware.class.isAssignableFrom(clazz)) {
            put(clazz, JSONAwareSerializer.instance);
        } else if (JSONSerializable.class.isAssignableFrom(clazz)) {
            put(clazz, JSONSerializableSerializer.instance);
        } else if (JSONStreamAware.class.isAssignableFrom(clazz)) {
            put(clazz, JSONStreamAwareSerializer.instance);
        } else if (clazz.isEnum() || (clazz.getSuperclass() != null && clazz.getSuperclass().isEnum())) {
            put(clazz, EnumSerializer.instance);
        } else if (clazz.isArray()) {
            Class<?> componentType = clazz.getComponentType();
            ObjectSerializer compObjectSerializer = getObjectWriter(componentType);
            put(clazz, new ArraySerializer(componentType, compObjectSerializer));
        } else if (Throwable.class.isAssignableFrom(clazz)) {
            put(clazz, new ExceptionSerializer(clazz));
        } else if (TimeZone.class.isAssignableFrom(clazz)) {
            put(clazz, TimeZoneCodec.instance);
        } else if (Appendable.class.isAssignableFrom(clazz)) {
            put(clazz, AppendableSerializer.instance);
        } else if (Charset.class.isAssignableFrom(clazz)) {
            put(clazz, CharsetCodec.instance);
        } else if (Enumeration.class.isAssignableFrom(clazz)) {
            put(clazz, EnumerationSeriliazer.instance);
        } else if (Calendar.class.isAssignableFrom(clazz)) {
            put(clazz, CalendarCodec.instance);
        } else if (Clob.class.isAssignableFrom(clazz)) {
            put(clazz, ClobSeriliazer.instance);
        } else {
            boolean isCglibProxy = false;
            boolean isJavassistProxy = false;
            for (Class<?> item : clazz.getInterfaces()) {
                if (item.getName().equals("net.sf.cglib.proxy.Factory")
                        || item.getName().equals("org.springframework.cglib.proxy.Factory")) {
                    isCglibProxy = true;
                    break;
                } else if (item.getName().equals("javassist.util.proxy.ProxyObject")) {
                    isJavassistProxy = true;
                    break;
                }
            }

            if (isCglibProxy || isJavassistProxy) {
                Class<?> superClazz = clazz.getSuperclass();

                ObjectSerializer superWriter = getObjectWriter(superClazz);
                put(clazz, superWriter);

                return superWriter;
            }

            if (Proxy.isProxyClass(clazz)) {
                put(clazz, createJavaBeanSerializer(clazz));
            } else {
                put(clazz, createJavaBeanSerializer(clazz));
            }

        }

        writer = get(clazz);
    }
    return writer;
}

From source file:org.apache.openjpa.persistence.AnnotationPersistenceMetaDataParser.java

/**
 * Parse @Basic. Given annotation may be null.
 *///from   www .j  a va  2 s. c  o  m
private void parseBasic(FieldMetaData fmd, Basic anno, boolean lob) {
    Class<?> type = fmd.getDeclaredType();
    if (lob && type != String.class && type != char[].class && type != Character[].class && type != byte[].class
            && type != Byte[].class)
        fmd.setSerialized(true);
    else if (!lob) {
        switch (fmd.getDeclaredTypeCode()) {
        case JavaTypes.OBJECT:
            if (Enum.class.isAssignableFrom(type))
                break;
            // else no break
        case JavaTypes.COLLECTION:
        case JavaTypes.MAP:
        case JavaTypes.PC:
        case JavaTypes.PC_UNTYPED:
            if (Serializable.class.isAssignableFrom(type))
                fmd.setSerialized(true);
            else
                throw new MetaDataException(_loc.get("bad-meta-anno", fmd, "Basic"));
            break;
        case JavaTypes.ARRAY:
            if (type == char[].class || type == Character[].class || type == byte[].class
                    || type == Byte[].class)
                break;
            if (Serializable.class.isAssignableFrom(type.getComponentType()))
                fmd.setSerialized(true);
            else
                throw new MetaDataException(_loc.get("bad-meta-anno", fmd, "Basic"));
            break;
        }
    }

    if (anno == null)
        return;
    fmd.setInDefaultFetchGroup(anno.fetch() == FetchType.EAGER);
    if (!anno.optional())
        fmd.setNullValue(FieldMetaData.NULL_EXCEPTION);
}

From source file:org.apache.axis2.wsdl.codegen.emitter.AxisServiceBasedMultiLanguageEmitter.java

private String getTypeName(Type type) {
    String typeName = null;/* www  . ja  v  a  2s.co  m*/
    if (type instanceof Class) {
        Class classType = (Class) type;
        if (classType.isArray()) {
            typeName = getTypeName(classType.getComponentType()) + "[]";
        } else {
            typeName = classType.getName();
        }
    } else if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        typeName = parameterizedType.toString();
    }

    return typeName;
}

From source file:org.apache.axis2.wsdl.codegen.emitter.AxisServiceBasedMultiLanguageEmitter.java

private String getParameterName(Type type, List existingParamNames) {
    String paramName = null;/*from   www .  j  a v  a2s .c  o m*/
    if (type instanceof Class) {
        Class classType = (Class) type;
        if (classType.isArray()) {
            paramName = getParameterName(classType.getComponentType(), existingParamNames);
        } else {
            String className = classType.getName();
            if (className.lastIndexOf(".") > 0) {
                className = className.substring(className.lastIndexOf(".") + 1);
            }
            paramName = JavaUtils.xmlNameToJavaIdentifier(className);
            if (existingParamNames.contains(paramName)) {
                paramName = paramName + existingParamNames.size();
            }
            existingParamNames.add(paramName);
        }
    } else if (type instanceof ParameterizedType) {
        ParameterizedType parameterizedType = (ParameterizedType) type;
        paramName = getParameterName(parameterizedType.getRawType(), existingParamNames);
    }
    return paramName;
}

From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java

/**
 * Convert the value to the required type (if necessary from a String), for the specified property.
 * //from   ww  w .j  av a  2  s  .  com
 * @param propertyName
 *            name of the property
 * @param oldValue
 *            the previous value, if available (may be <code>null</code>)
 * @param newValue
 *            the proposed new value
 * @param requiredType
 *            the type we must convert to (or <code>null</code> if not known, for example in case of a collection
 *            element)
 * @param typeDescriptor
 *            the descriptor for the target property or field
 * @return the new value, possibly the result of type conversion
 * @throws IllegalArgumentException
 *             if type conversion failed
 */
@SuppressWarnings("unchecked")
public <T> T convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class<T> requiredType,
        TypeDescriptor typeDescriptor) throws IllegalArgumentException {

    Object convertedValue = newValue;

    // Custom editor for this type?
    PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);

    ConversionFailedException firstAttemptEx = null;

    // No custom editor but custom ConversionService specified?
    ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
    if (editor == null && conversionService != null && convertedValue != null && typeDescriptor != null) {
        TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
        TypeDescriptor targetTypeDesc = typeDescriptor;
        if (conversionService.canConvert(sourceTypeDesc, targetTypeDesc)) {
            try {
                return (T) conversionService.convert(convertedValue, sourceTypeDesc, targetTypeDesc);
            } catch (ConversionFailedException ex) {
                // fallback to default conversion logic below
                firstAttemptEx = ex;
            }
        }
    }

    // Value not of required type?
    if (editor != null
            || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
        if (requiredType != null && Collection.class.isAssignableFrom(requiredType)
                && convertedValue instanceof String) {
            TypeDescriptor elementType = typeDescriptor.getElementTypeDescriptor();
            if (elementType != null && Enum.class.isAssignableFrom(elementType.getType())) {
                convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
            }
        }
        if (editor == null) {
            editor = findDefaultEditor(requiredType);
        }
        convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor);
    }

    boolean standardConversion = false;

    if (requiredType != null) {
        // Try to apply some standard type conversion rules if appropriate.

        if (convertedValue != null) {
            if (requiredType.isArray()) {
                // Array required -> apply appropriate conversion of elements.
                if (convertedValue instanceof String
                        && Enum.class.isAssignableFrom(requiredType.getComponentType())) {
                    convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
                }
                return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType());
            } else if (convertedValue instanceof Collection) {
                // Convert elements to target type, if determined.
                convertedValue = convertToTypedCollection((Collection) convertedValue, propertyName,
                        requiredType, typeDescriptor);
                standardConversion = true;
            } else if (convertedValue instanceof Map) {
                // Convert keys and values to respective target type, if determined.
                convertedValue = convertToTypedMap((Map) convertedValue, propertyName, requiredType,
                        typeDescriptor);
                standardConversion = true;
            }
            if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) {
                convertedValue = Array.get(convertedValue, 0);
                standardConversion = true;
            }
            if (String.class.equals(requiredType)
                    && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) {
                // We can stringify any primitive value...
                return (T) convertedValue.toString();
            } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
                if (firstAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) {
                    try {
                        Constructor strCtor = requiredType.getConstructor(String.class);
                        return (T) BeanUtils.instantiateClass(strCtor, convertedValue);
                    } catch (NoSuchMethodException ex) {
                        // proceed with field lookup
                        if (logger.isTraceEnabled()) {
                            logger.trace("No String constructor found on type [" + requiredType.getName() + "]",
                                    ex);
                        }
                    } catch (Exception ex) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "Construction via String failed for type [" + requiredType.getName() + "]",
                                    ex);
                        }
                    }
                }
                String trimmedValue = ((String) convertedValue).trim();
                if (requiredType.isEnum() && "".equals(trimmedValue)) {
                    // It's an empty enum identifier: reset the enum value to null.
                    return null;
                }
                convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue);
                standardConversion = true;
            }
        }

        if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
            if (firstAttemptEx != null) {
                throw firstAttemptEx;
            }
            // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException
            StringBuilder msg = new StringBuilder();
            msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue));
            msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]");
            if (propertyName != null) {
                msg.append(" for property '").append(propertyName).append("'");
            }
            if (editor != null) {
                msg.append(": PropertyEditor [").append(editor.getClass().getName())
                        .append("] returned inappropriate value of type [")
                        .append(ClassUtils.getDescriptiveType(convertedValue)).append("]");
                throw new IllegalArgumentException(msg.toString());
            } else {
                msg.append(": no matching editors or conversion strategy found");
                throw new IllegalStateException(msg.toString());
            }
        }
    }

    if (firstAttemptEx != null) {
        if (editor == null && !standardConversion && requiredType != null
                && !Object.class.equals(requiredType)) {
            throw firstAttemptEx;
        }
        logger.debug("Original ConversionService attempt failed - ignored since "
                + "PropertyEditor based conversion eventually succeeded", firstAttemptEx);
    }

    return (T) convertedValue;
}

From source file:org.apache.ojb.otm.core.ConcreteEditingContext.java

private void setCollectionField(Object obj, PersistentField f, List newCol) {
    Class type = f.getType();

    if (Collection.class.isAssignableFrom(type)) {
        Collection col = (Collection) f.get(obj);

        if (col == null) {
            if (type == List.class || type == Collection.class) {
                col = new ArrayList();
            } else if (type == Set.class) {
                col = new HashSet();
            } else {
                try {
                    col = (Collection) type.newInstance();
                } catch (Throwable ex) {
                    System.err.println("Cannot instantiate collection field: " + f);
                    ex.printStackTrace();
                    return;
                }/*from   w  w w.  ja va  2s  . c  om*/
            }
        } else {
            if (col instanceof CollectionProxyDefaultImpl) {
                CollectionProxyDefaultImpl cp = (CollectionProxyDefaultImpl) col;
                if (col instanceof List) {
                    col = new ListProxyDefaultImpl(_pb.getPBKey(), cp.getData().getClass(), null);
                } else if (col instanceof Set) {
                    col = new SetProxyDefaultImpl(_pb.getPBKey(), cp.getData().getClass(), null);
                } else {
                    col = new CollectionProxyDefaultImpl(_pb.getPBKey(), cp.getData().getClass(), null);
                }
                col.clear();
            } else {
                try {
                    col = (Collection) col.getClass().newInstance();
                } catch (Exception ex) {
                    System.err.println("Cannot instantiate collection field: " + f);
                    ex.printStackTrace();
                    return;
                }
            }
        }
        col.addAll(newCol);
        f.set(obj, col);
    } else if (type.isArray()) {
        int length = newCol.size();
        Object array = Array.newInstance(type.getComponentType(), length);

        for (int i = 0; i < length; i++) {
            Array.set(array, i, newCol.get(i));
        }
        f.set(obj, array);
    }
}