Example usage for java.lang Class isPrimitive

List of usage examples for java.lang Class isPrimitive

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public native boolean isPrimitive();

Source Link

Document

Determines if the specified Class object represents a primitive type.

Usage

From source file:net.ceos.project.poi.annotated.core.Engine.java

/**
 * Convert the file to object with the PropagationType as
 * PROPAGATION_VERTICAL.//from  w  ww  .  jav  a  2  s .co m
 * 
 * @param configCriteria
 *            the {@link XConfigCriteria}
 * @param o
 *            the object
 * @param oC
 *            the object class
 * @param idxR
 *            the position of the row
 * @param idxC
 *            the position of the cell
 * @return in case of the object return the number of cells created,
 *         otherwise 0
 * @throws WorkbookException
 *             given when a not supported action.
 */
private int unmarshalAsPropagationVertical(final XConfigCriteria configCriteria, Object o, Class<?> oC,
        final int idxR, final int idxC, final int cL) throws WorkbookException {
    /* counter related to the number of fields (if new object) */
    int counter = -1;
    int indexRow = idxR;
    int elementPosition = idxR;

    if (!CascadeHandler.isAuthorizedCascadeLevel(configCriteria, cL, o)) {
        return counter;
    }

    /* get declared fields */
    List<Field> fL = Arrays.asList(oC.getDeclaredFields());
    for (Field f : fL) {
        /* process each field from the object */
        Class<?> fT = f.getType();

        /* Process @XlsElement */
        if (PredicateFactory.isFieldAnnotationXlsElementPresent.test(f)) {
            XlsElement xlsAnnotation = (XlsElement) f.getAnnotation(XlsElement.class);

            /* validate the position of the element */
            if (PredicateFactory.isXlsElementInvalid.test(xlsAnnotation)) {
                throw new ElementException(ExceptionMessage.ELEMENT_INVALID_POSITION.getMessage());
            }

            /* set position of the element */
            elementPosition = xlsAnnotation.position() == -99 ? elementPosition + 1 : xlsAnnotation.position();

            /*
             * increment of the counter related to the number of fields (if
             * new object)
             */
            counter++;

            /* content row */
            Row contentRow = configCriteria.getSheet().getRow(indexRow + elementPosition);
            Cell contentCell = contentRow.getCell(idxC + 2);
            if (contentCell != null) {
                if (Collection.class.isAssignableFrom(fT)) {

                    // E uma lista entao ha que crear uma sheet nova
                    try {
                        f.set(o, unmarshalTreatementToCollection(o, configCriteria));
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                } else {
                    boolean isAppliedToBaseObject = toObject(o, fT, f, contentCell, xlsAnnotation);

                    if (!isAppliedToBaseObject && !fT.isPrimitive()) {

                        try {
                            Object subObjbect = fT.newInstance();

                            Class<?> subObjbectClass = subObjbect.getClass();

                            int internalCellCounter = unmarshalAsPropagationVertical(configCriteria, subObjbect,
                                    subObjbectClass, indexRow + elementPosition - 1, idxC, cL + 1);

                            /* add the sub object to the parent object */
                            f.set(o, subObjbect);

                            /* update the index */
                            indexRow += internalCellCounter;
                        } catch (InstantiationException | IllegalAccessException e) {
                            throw new CustomizedRulesException(
                                    ExceptionMessage.ELEMENT_NO_SUCH_METHOD.getMessage(), e);
                        }
                    }
                }
            } else {
                o = null;
                counter = -5;
                break;
            }
        }

        /* Process @XlsFreeElement */
        if (PredicateFactory.isFieldAnnotationXlsFreeElementPresent.test(f)) {
            XlsFreeElement xlsFreeAnnotation = (XlsFreeElement) f.getAnnotation(XlsFreeElement.class);

            /* validate the row/cell of the element */
            if (PredicateFactory.isXlsFreeElementInvalid.test(xlsFreeAnnotation)) {
                throw new ElementException(ExceptionMessage.ELEMENT_INVALID_POSITION.getMessage());
            }

            /* content row */
            Row contentRow = configCriteria.getSheet().getRow(xlsFreeAnnotation.row());
            Cell contentCell = contentRow.getCell(xlsFreeAnnotation.cell() - 1);

            // initialize Element
            XlsElement xlsAnnotation = XlsElementFactory.build(xlsFreeAnnotation);

            boolean isAppliedToBaseObject = toObject(o, fT, f, contentCell, xlsAnnotation);

            if (!isAppliedToBaseObject && !fT.isPrimitive()) {
                throw new ElementException(ExceptionMessage.ELEMENT_COMPLEX_OBJECT.getMessage());
            }
        }
    }
    return counter;
}

From source file:net.ceos.project.poi.annotated.core.Engine.java

/**
 * Convert the file to object with the PropagationType as
 * PROPAGATION_HORIZONTAL.//from www .j a va 2 s .  c  om
 * 
 * @param configCriteria
 *            the {@link XConfigCriteria}
 * @param o
 *            the object
 * @param oC
 *            the object class
 * @param idxR
 *            the position of the row
 * @param idxC
 *            the position of the cell
 * @return in case of the object return the number of cells created,
 *         otherwise 0
 * @throws WorkbookException
 *             given when a not supported action.
 */
private int unmarshalAsPropagationHorizontal(final XConfigCriteria configCriteria, Object o, Class<?> oC,
        final int idxR, final int idxC, final int cL) throws WorkbookException {
    /* counter related to the number of fields (if new object) */
    int counter = -1;
    int indexCell = idxC;
    int elementPosition = 0;

    if (!CascadeHandler.isAuthorizedCascadeLevel(configCriteria, cL, o)) {
        return counter;
    }

    /* get declared fields */
    List<Field> fL = Arrays.asList(oC.getDeclaredFields());
    for (Field f : fL) {
        /* process each field from the object */
        Class<?> fT = f.getType();

        /* Process @XlsElement */
        if (PredicateFactory.isFieldAnnotationXlsElementPresent.test(f)) {
            XlsElement xlsAnnotation = (XlsElement) f.getAnnotation(XlsElement.class);

            /* validate the position of the element */
            if (PredicateFactory.isXlsElementInvalid.test(xlsAnnotation)) {
                throw new ElementException(ExceptionMessage.ELEMENT_INVALID_POSITION.getMessage());
            }

            /* set position of the element */
            elementPosition = xlsAnnotation.position() == -99 ? elementPosition + 1 : xlsAnnotation.position();

            /*
             * increment of the counter related to the number of fields (if
             * new object)
             */
            counter++;

            /* content row */
            // MAL - ERRO AQUI
            Row contentRow = configCriteria.getSheet().getRow(idxR + 1);
            if (contentRow != null && idxR < configCriteria.getSheet().getLastRowNum()) {
                Cell contentCell = contentRow.getCell(indexCell + elementPosition);
                if (contentCell != null) {
                    if (Collection.class.isAssignableFrom(fT)) {

                        try {
                            f.set(o, unmarshalTreatementToCollection(o, configCriteria));
                        } catch (IllegalArgumentException | IllegalAccessException e) {
                            throw new ElementException(ExceptionMessage.ELEMENT_COMPLEX_OBJECT.getMessage());
                        }
                    } else {
                        boolean isAppliedToBaseObject = toObject(o, fT, f, contentCell, xlsAnnotation);

                        if (!isAppliedToBaseObject && !fT.isPrimitive()) {
                            try {
                                Object subObjbect = fT.newInstance();

                                Class<?> subObjbectClass = subObjbect.getClass();

                                int internalCellCounter = unmarshalAsPropagationHorizontal(configCriteria,
                                        subObjbect, subObjbectClass, idxR, indexCell + elementPosition - 1,
                                        cL + 1);

                                /*
                                 * add the sub object to the parent object
                                 */
                                f.set(o, subObjbect);

                                /* update the index */
                                indexCell += internalCellCounter;
                            } catch (InstantiationException | IllegalAccessException e) {
                                throw new CustomizedRulesException(
                                        ExceptionMessage.ELEMENT_NO_SUCH_METHOD.getMessage(), e);

                            }
                        }
                    }

                }
            } else {
                counter = -5;
                o = null;
                break;

            }
        }

        /* Process @XlsFreeElement */
        if (PredicateFactory.isFieldAnnotationXlsFreeElementPresent.test(f)) {
            XlsFreeElement xlsFreeAnnotation = (XlsFreeElement) f.getAnnotation(XlsFreeElement.class);

            /* validate the row/cell of the element */
            if (PredicateFactory.isXlsFreeElementInvalid.test(xlsFreeAnnotation)) {
                throw new ElementException(ExceptionMessage.ELEMENT_INVALID_POSITION.getMessage());
            }

            /* content row */
            Row contentRow = configCriteria.getSheet().getRow(xlsFreeAnnotation.row());
            Cell contentCell = contentRow.getCell(xlsFreeAnnotation.cell() - 1);

            // initialize Element
            XlsElement xlsAnnotation = XlsElementFactory.build(xlsFreeAnnotation);

            boolean isAppliedToBaseObject = toObject(o, fT, f, contentCell, xlsAnnotation);

            if (!isAppliedToBaseObject && !fT.isPrimitive()) {
                throw new ElementException(ExceptionMessage.ELEMENT_COMPLEX_OBJECT.getMessage());
            }
        }
    }
    return counter;
}

From source file:com.netspective.commons.xdm.XmlDataModelSchema.java

private XmlDataModelSchema(final Class bean) {
    propertyNames = new HashMap();
    attributeTypes = new HashMap();
    attributeSetters = new HashMap();
    attributeSetterMethods = new HashMap();
    attributeAccessors = new HashMap();
    flagsAttributeAccessors = new HashMap();
    nestedTypes = new HashMap();
    nestedCreators = new HashMap();
    nestedAltClassNameCreators = new HashMap();
    nestedAdders = new HashMap();
    nestedStorers = new HashMap();

    this.bean = bean;

    Options customOptions = (Options) getStaticFieldValue(bean, XMLDATAMODEL_SCHEMA_OPTIONS_FIELD_NAME);
    options = customOptions != null ? customOptions : new Options();

    Method[] methods = bean.getMethods();
    for (int i = 0; i < methods.length; i++) {
        final Method m = methods[i];
        final String name = m.getName();
        Class returnType = m.getReturnType();
        Class[] args = m.getParameterTypes();

        if (name.equals(options.pcDataHandlerMethodName) && java.lang.Void.TYPE.equals(returnType)
                && args.length == 1 && java.lang.String.class.equals(args[0])) {
            addText = methods[i];//w  w w  .ja  v a 2 s.c om
        } else if (name.startsWith("get") && args.length == 0) {
            String[] propNames = getPropertyNames(name, "get");
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                AttributeAccessor aa = createAttributeAccessor(m, propNames[pn], returnType);
                if (aa != null)
                    attributeAccessors.put(propNames[pn], aa);
            }
        } else if (name.startsWith("is") && args.length == 0) {
            String[] propNames = getPropertyNames(name, "is");
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                AttributeAccessor aa = createAttributeAccessor(m, propNames[pn], returnType);
                if (aa != null)
                    attributeAccessors.put(propNames[pn], aa);
            }
        } else if (name.startsWith("set") && java.lang.Void.TYPE.equals(returnType) && args.length == 1
                && (!args[0].isArray() || java.lang.String[].class.equals(args[0]))) {
            String[] propNames = getPropertyNames(name, "set");
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                attributeSetterMethods.put(propNames[pn], m);
                AttributeSetter as = createAttributeSetter(m, propNames[pn], args[0]);
                if (as != null) {
                    attributeTypes.put(propNames[pn], args[0]);
                    attributeSetters.put(propNames[pn], as);
                }
            }
        } else if (name.startsWith("create") && !returnType.isArray() && !returnType.isPrimitive()
                && (args.length == 0)) {
            // prevent infinite recursion for nested recursive elements
            if (!returnType.getClass().equals(bean.getClass()))
                getSchema(returnType);
            String[] propNames = getPropertyNames(name, "create");
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                nestedTypes.put(propNames[pn], returnType);
                nestedCreators.put(propNames[pn], new NestedCreator() {
                    public Object create(Object parent)
                            throws InvocationTargetException, IllegalAccessException {
                        return m.invoke(parent, new Object[] {});
                    }

                    public boolean isInherited() {
                        return !m.getDeclaringClass().equals(bean);
                    }

                    public Class getDeclaringClass() {
                        return m.getDeclaringClass();
                    }
                });
            }
        } else if (name.startsWith("create") && !returnType.isArray() && !returnType.isPrimitive()
                && (args.length == 1 && args[0] == Class.class)) {
            // prevent infinite recursion for nested recursive elements
            if (!returnType.getClass().equals(bean.getClass()))
                getSchema(returnType);
            String[] propNames = getPropertyNames(name, "create");
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                nestedTypes.put(propNames[pn], returnType);
                nestedAltClassNameCreators.put(propNames[pn], new NestedAltClassCreator() {
                    public Object create(Object parent, Class cls)
                            throws InvocationTargetException, IllegalAccessException {
                        return m.invoke(parent, new Object[] { cls });
                    }

                    public boolean isInherited() {
                        return !m.getDeclaringClass().equals(bean);
                    }

                    public Class getDeclaringClass() {
                        return m.getDeclaringClass();
                    }
                });
            }
        } else if (name.startsWith("add") && java.lang.Void.TYPE.equals(returnType) && args.length == 1
                && !java.lang.String.class.equals(args[0]) && !args[0].isArray() && !args[0].isPrimitive()) {
            String[] propNames = getPropertyNames(name, "add");
            try {
                final Constructor c = args[0].getConstructor(new Class[] {});
                for (int pn = 0; pn < propNames.length; pn++) {
                    if (propNames[pn].length() == 0)
                        continue;

                    if (!nestedCreators.containsKey(propNames[pn])) {
                        nestedTypes.put(propNames[pn], args[0]);
                        nestedCreators.put(propNames[pn], new NestedCreator() {
                            public boolean allowAlternateClass() {
                                return false;
                            }

                            public Object create(Object parent) throws InvocationTargetException,
                                    IllegalAccessException, InstantiationException {
                                return c.newInstance(new Object[] {});
                            }

                            public Object create(Object parent, Class cls) throws InvocationTargetException,
                                    IllegalAccessException, InstantiationException {
                                return c.newInstance(new Object[] { cls });
                            }

                            public boolean isInherited() {
                                return !m.getDeclaringClass().equals(bean);
                            }

                            public Class getDeclaringClass() {
                                return m.getDeclaringClass();
                            }
                        });
                    }
                }
            } catch (NoSuchMethodException nse) {
                //log.warn("Unable to create nestedCreator for " + name + " " + args[0] + ", registering type only without a creator.", nse);
                for (int pn = 0; pn < propNames.length; pn++) {
                    if (propNames[pn].length() > 0)
                        nestedTypes.put(propNames[pn], args[0]);
                }
            }

            // prevent infinite recursion for nested recursive elements
            if (!args[0].getClass().equals(bean.getClass()))
                getSchema(args[0]);
            for (int pn = 0; pn < propNames.length; pn++) {
                if (propNames[pn].length() == 0)
                    continue;

                nestedStorers.put(propNames[pn], new NestedStorer() {
                    public void store(Object parent, Object child)
                            throws InvocationTargetException, IllegalAccessException {
                        m.invoke(parent, new Object[] { child });
                    }

                    public boolean isInherited() {
                        return !m.getDeclaringClass().equals(bean);
                    }

                    public Class getDeclaringClass() {
                        return m.getDeclaringClass();
                    }
                });
            }
        }
    }
}

From source file:com.bstek.dorado.view.output.ClientOutputHelper.java

protected Map<String, PropertyConfig> doGetPropertyConfigs(Class<?> beanType) throws Exception {
    beanType = ProxyBeanUtils.getProxyTargetType(beanType);
    Map<String, PropertyConfig> propertyConfigs = new HashMap<String, PropertyConfig>();

    ClientObjectInfo clientObjectInfo = getClientObjectInfo(beanType);
    if (clientObjectInfo != null) {
        for (Map.Entry<String, ClientProperty> entry : clientObjectInfo.getPropertyConfigs().entrySet()) {
            String property = entry.getKey();
            ClientProperty clientProperty = entry.getValue();

            PropertyConfig propertyConfig = new PropertyConfig();
            if (clientProperty.ignored()) {
                propertyConfig.setIgnored(true);
            } else {
                if (StringUtils.isNotEmpty(clientProperty.outputter())) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(clientProperty.outputter(),
                            Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                }//ww  w.j a v a2s.co  m

                if (clientProperty.alwaysOutput()) {
                    propertyConfig.setEscapeValue(FAKE_ESCAPE_VALUE);
                } else if (StringUtils.isNotEmpty(clientProperty.escapeValue())) {
                    propertyConfig.setEscapeValue(clientProperty.escapeValue());
                }
            }
            propertyConfigs.put(property, propertyConfig);
        }
    }

    boolean isAssembledComponent = (AssembledComponent.class.isAssignableFrom(beanType));
    Class<?> superComponentType = null;
    if (isAssembledComponent) {
        superComponentType = beanType;
        while (superComponentType != null && AssembledComponent.class.isAssignableFrom(superComponentType)) {
            superComponentType = superComponentType.getSuperclass();
            Assert.notNull(superComponentType);
        }
    }

    for (PropertyDescriptor propertyDescriptor : PropertyUtils.getPropertyDescriptors(beanType)) {
        String property = propertyDescriptor.getName();
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod.getDeclaringClass() != beanType) {
            try {
                readMethod = beanType.getMethod(readMethod.getName(), readMethod.getParameterTypes());
            } catch (NoSuchMethodException e) {
                // do nothing
            }
        }

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

        PropertyConfig propertyConfig = null;
        ClientProperty clientProperty = readMethod.getAnnotation(ClientProperty.class);
        if (clientProperty != null) {
            propertyConfig = new PropertyConfig();
            if (clientProperty.ignored()) {
                propertyConfig.setIgnored(true);
            } else {
                if (StringUtils.isNotEmpty(clientProperty.outputter())) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(clientProperty.outputter(),
                            Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (Component.class.isAssignableFrom(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(COMPONENT_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (DataControl.class.isAssignableFrom(propertyType)
                        || FloatControl.class.isAssignableFrom(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(COMPONENT_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (DataType.class.isAssignableFrom(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(DATA_TYPE_PROPERTY_OUTPUTTER,
                            Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (Object.class.equals(propertyType)) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(DATA_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                } else if (!EntityUtils.isSimpleType(propertyType) && !propertyType.isArray()) {
                    BeanWrapper beanWrapper = BeanFactoryUtils.getBean(OBJECT_OUTPUTTER, Scope.instant);
                    propertyConfig.setOutputter(beanWrapper.getBean());
                }

                if (!clientProperty.evaluateExpression()) {
                    propertyConfig.setEvaluateExpression(false);
                }

                if (clientProperty.alwaysOutput()) {
                    propertyConfig.setEscapeValue(FAKE_ESCAPE_VALUE);
                } else if (StringUtils.isNotEmpty(clientProperty.escapeValue())) {
                    propertyConfig.setEscapeValue(clientProperty.escapeValue());
                }
            }
        } else if (isAssembledComponent && readMethod.getDeclaringClass() == beanType
                && EntityUtils.isSimpleType(propertyType)) {
            if (BeanUtils.getPropertyDescriptor(superComponentType, property) == null) {
                propertyConfig = new PropertyConfig();
                propertyConfig.setIgnored(true);
            }
        }

        ComponentReference componentReference = readMethod.getAnnotation(ComponentReference.class);
        if (componentReference != null && String.class.equals(propertyType)) {
            if (propertyConfig == null) {
                propertyConfig = new PropertyConfig();
            }
            if (propertyConfig.getOutputter() == null) {
                BeanWrapper beanWrapper = BeanFactoryUtils.getBean(COMPONENT_REFERENCE_OUTPUTTER,
                        Scope.instant);
                propertyConfig.setOutputter(beanWrapper.getBean());
            }
        }

        if (!propertyType.isPrimitive() && (Number.class.isAssignableFrom(propertyType)
                || Boolean.class.isAssignableFrom(propertyType))) {
            if (propertyConfig == null) {
                propertyConfig = new PropertyConfig();
            }
            if (propertyConfig.getEscapeValue() == PropertyConfig.NONE_VALUE) {
                propertyConfig.setEscapeValue(null);
            }
        }

        if (propertyConfig != null) {
            propertyConfigs.put(property, propertyConfig);
        }
    }
    return (propertyConfigs.isEmpty()) ? null : propertyConfigs;
}

From source file:com.ms.commons.summer.web.util.json.JsonBeanUtils.java

/**
 * Creates a bean from a JSONObject, with the specific configuration.
 *///from  w  ww  .  ja v a  2 s  . c om
public static Object toBean(JSONObject jsonObject, JsonConfig jsonConfig) {
    if (jsonObject == null || jsonObject.isNullObject()) {
        return null;
    }

    Class beanClass = jsonConfig.getRootClass();
    Map classMap = jsonConfig.getClassMap();

    if (beanClass == null) {
        return toBean(jsonObject);
    }
    if (classMap == null) {
        classMap = Collections.EMPTY_MAP;
    }

    Object bean = null;
    try {
        if (beanClass.isInterface()) {
            if (!Map.class.isAssignableFrom(beanClass)) {
                throw new JSONException("beanClass is an interface. " + beanClass);
            } else {
                bean = new HashMap();
            }
        } else {
            bean = jsonConfig.getNewBeanInstanceStrategy().newInstance(beanClass, jsonObject);
        }
    } catch (JSONException jsone) {
        throw jsone;
    } catch (Exception e) {
        throw new JSONException(e);
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    for (Iterator entries = jsonObject.names().iterator(); entries.hasNext();) {
        String name = (String) entries.next();
        Class type = (Class) props.get(name);
        Object value = jsonObject.get(name);
        if (javaPropertyFilter != null && javaPropertyFilter.apply(bean, name, value)) {
            continue;
        }
        String key = Map.class.isAssignableFrom(beanClass)
                && jsonConfig.isSkipJavaIdentifierTransformationInMapKeys() ? name
                        : JSONUtils.convertToJavaIdentifier(name, jsonConfig);
        try {
            if (Map.class.isAssignableFrom(beanClass)) {
                // no type info available for conversion
                if (JSONUtils.isNull(value)) {
                    setProperty(bean, key, value, jsonConfig);
                } else if (value instanceof JSONArray) {
                    setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name,
                            classMap, List.class), jsonConfig);
                } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                        || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                        || JSONFunction.class.isAssignableFrom(type)) {
                    if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                        setProperty(bean, key, null, jsonConfig);
                    } else {
                        setProperty(bean, key, value, jsonConfig);
                    }
                } else {
                    Class targetClass = findTargetClass(key, classMap);
                    targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                    JsonConfig jsc = jsonConfig.copy();
                    jsc.setRootClass(targetClass);
                    jsc.setClassMap(classMap);
                    if (targetClass != null) {
                        setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                    } else {
                        setProperty(bean, key, toBean((JSONObject) value), jsonConfig);
                    }
                }
            } else {
                PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, key);
                if (pd != null && pd.getWriteMethod() == null) {
                    log.warn("Property '" + key + "' has no write method. SKIPPED.");
                    continue;
                }

                if (pd != null) {
                    Class targetType = pd.getPropertyType();
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            if (List.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else if (Set.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else {
                                setProperty(bean, key, convertPropertyValueToArray(key, value, targetType,
                                        jsonConfig, classMap), jsonConfig);
                            }
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (pd != null) {
                                if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                                    setProperty(bean, key, null, jsonConfig);
                                } else if (!targetType.isInstance(value)) {
                                    setProperty(bean, key, morphPropertyValue(key, value, type, targetType),
                                            jsonConfig);
                                } else {
                                    setProperty(bean, key, value, jsonConfig);
                                }
                            } else if (beanClass == null || bean instanceof Map) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                JSONArray array = new JSONArray().element(value, jsonConfig);
                                Class newTargetClass = findTargetClass(key, classMap);
                                newTargetClass = newTargetClass == null ? findTargetClass(name, classMap)
                                        : newTargetClass;
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                if (targetType.isArray()) {
                                    setProperty(bean, key, JSONArray.toArray(array, jsc), jsonConfig);
                                } else if (JSONArray.class.isAssignableFrom(targetType)) {
                                    setProperty(bean, key, array, jsonConfig);
                                } else if (List.class.isAssignableFrom(targetType)
                                        || Set.class.isAssignableFrom(targetType)) {
                                    jsc.setCollectionType(targetType);
                                    setProperty(bean, key, JSONArray.toCollection(array, jsc), jsonConfig);
                                } else {
                                    setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                                }
                            } else {
                                if (targetType == Object.class) {
                                    targetType = findTargetClass(key, classMap);
                                    targetType = targetType == null ? findTargetClass(name, classMap)
                                            : targetType;
                                }
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(targetType);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                } else {
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                    name, classMap, List.class), jsonConfig);
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (pd != null) {
                                if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                                    setProperty(bean, key, null, jsonConfig);
                                } else {
                                    setProperty(bean, key, value, jsonConfig);
                                }
                            } else if (beanClass == null || bean instanceof Map) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                Class newTargetClass = findTargetClass(key, classMap);
                                newTargetClass = newTargetClass == null ? findTargetClass(name, classMap)
                                        : newTargetClass;
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            } else {
                                setProperty(bean, key, value, jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                }
            }
        } catch (JSONException jsone) {
            throw jsone;
        } catch (Exception e) {
            throw new JSONException("Error while setting property=" + name + " type " + type, e);
        }
    }

    return bean;
}

From source file:net.sf.json.JSONObject.java

/**
 * Creates a bean from a JSONObject, with the specific configuration.
 */// w w w .  j  a va2 s.c  om
public static Object toBean(JSONObject jsonObject, JsonConfig jsonConfig) {
    if (jsonObject == null || jsonObject.isNullObject()) {
        return null;
    }

    Class beanClass = jsonConfig.getRootClass();
    Map classMap = jsonConfig.getClassMap();

    if (beanClass == null) {
        return toBean(jsonObject);
    }
    if (classMap == null) {
        classMap = Collections.EMPTY_MAP;
    }

    Object bean = null;
    try {
        if (beanClass.isInterface()) {
            if (!Map.class.isAssignableFrom(beanClass)) {
                throw new JSONException("beanClass is an interface. " + beanClass);
            } else {
                bean = new HashMap();
            }
        } else {
            bean = jsonConfig.getNewBeanInstanceStrategy().newInstance(beanClass, jsonObject);
        }
    } catch (JSONException jsone) {
        throw jsone;
    } catch (Exception e) {
        throw new JSONException(e);
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries.hasNext();) {
        String name = (String) entries.next();
        Class type = (Class) props.get(name);
        Object value = jsonObject.get(name);
        if (javaPropertyFilter != null && javaPropertyFilter.apply(bean, name, value)) {
            continue;
        }
        String key = Map.class.isAssignableFrom(beanClass)
                && jsonConfig.isSkipJavaIdentifierTransformationInMapKeys() ? name
                        : JSONUtils.convertToJavaIdentifier(name, jsonConfig);
        PropertyNameProcessor propertyNameProcessor = jsonConfig.findJavaPropertyNameProcessor(beanClass);
        if (propertyNameProcessor != null) {
            key = propertyNameProcessor.processPropertyName(beanClass, key);
        }
        try {
            if (Map.class.isAssignableFrom(beanClass)) {
                // no type info available for conversion
                if (JSONUtils.isNull(value)) {
                    setProperty(bean, key, value, jsonConfig);
                } else if (value instanceof JSONArray) {
                    setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name,
                            classMap, List.class), jsonConfig);
                } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                        || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                        || JSONFunction.class.isAssignableFrom(type)) {
                    if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                        setProperty(bean, key, null, jsonConfig);
                    } else {
                        setProperty(bean, key, value, jsonConfig);
                    }
                } else {
                    Class targetClass = resolveClass(classMap, key, name, type);
                    JsonConfig jsc = jsonConfig.copy();
                    jsc.setRootClass(targetClass);
                    jsc.setClassMap(classMap);
                    if (targetClass != null) {
                        setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                    } else {
                        setProperty(bean, key, toBean((JSONObject) value), jsonConfig);
                    }
                }
            } else {
                PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, key);
                if (pd != null && pd.getWriteMethod() == null) {
                    log.info("Property '" + key + "' of " + bean.getClass() + " has no write method. SKIPPED.");
                    continue;
                }

                if (pd != null) {
                    Class targetType = pd.getPropertyType();
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            if (List.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else if (Set.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else {
                                setProperty(bean, key, convertPropertyValueToArray(key, value, targetType,
                                        jsonConfig, classMap), jsonConfig);
                            }
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (pd != null) {
                                if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                                    setProperty(bean, key, null, jsonConfig);
                                } else if (!targetType.isInstance(value)) {
                                    setProperty(bean, key, morphPropertyValue(key, value, type, targetType),
                                            jsonConfig);
                                } else {
                                    setProperty(bean, key, value, jsonConfig);
                                }
                            } else if (beanClass == null || bean instanceof Map) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                JSONArray array = new JSONArray().element(value, jsonConfig);
                                Class newTargetClass = resolveClass(classMap, key, name, type);
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                if (targetType.isArray()) {
                                    setProperty(bean, key, JSONArray.toArray(array, jsc), jsonConfig);
                                } else if (JSONArray.class.isAssignableFrom(targetType)) {
                                    setProperty(bean, key, array, jsonConfig);
                                } else if (List.class.isAssignableFrom(targetType)
                                        || Set.class.isAssignableFrom(targetType)) {
                                    jsc.setCollectionType(targetType);
                                    setProperty(bean, key, JSONArray.toCollection(array, jsc), jsonConfig);
                                } else {
                                    setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                                }
                            } else {
                                if (targetType == Object.class || targetType.isInterface()) {
                                    Class targetTypeCopy = targetType;
                                    targetType = findTargetClass(key, classMap);
                                    targetType = targetType == null ? findTargetClass(name, classMap)
                                            : targetType;
                                    targetType = targetType == null && targetTypeCopy.isInterface()
                                            ? targetTypeCopy
                                            : targetType;
                                }
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(targetType);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                } else {
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                    name, classMap, List.class), jsonConfig);
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (beanClass == null || bean instanceof Map
                                    || jsonConfig.getPropertySetStrategy() != null
                                    || !jsonConfig.isIgnorePublicFields()) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                Class newTargetClass = resolveClass(classMap, key, name, type);
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            } else {
                                setProperty(bean, key, value, jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                }
            }
        } catch (JSONException jsone) {
            throw jsone;
        } catch (Exception e) {
            throw new JSONException("Error while setting property=" + name + " type " + type, e);
        }
    }

    return bean;
}

From source file:com.xwtec.xwserver.util.json.JSONObject.java

/**
 * Creates a bean from a JSONObject, with the specific configuration.
 *//*from  w w  w  .  j  a v  a  2  s  .com*/
public static Object toBean(JSONObject jsonObject, JsonConfig jsonConfig) {
    if (jsonObject == null || jsonObject.isNullObject()) {
        return null;
    }

    Class beanClass = jsonConfig.getRootClass();
    Map classMap = jsonConfig.getClassMap();

    if (beanClass == null) {
        return toBean(jsonObject);
    }
    if (classMap == null) {
        classMap = Collections.EMPTY_MAP;
    }

    Object bean = null;
    try {
        if (beanClass.isInterface()) {
            if (!Map.class.isAssignableFrom(beanClass)) {
                throw new JSONException("beanClass is an interface. " + beanClass);
            } else {
                bean = new HashMap();
            }
        } else {
            bean = jsonConfig.getNewBeanInstanceStrategy().newInstance(beanClass, jsonObject);
        }
    } catch (JSONException jsone) {
        throw jsone;
    } catch (Exception e) {
        throw new JSONException(e);
    }

    Map props = JSONUtils.getProperties(jsonObject);
    PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter();
    for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries.hasNext();) {
        String name = (String) entries.next();
        Class type = (Class) props.get(name);
        Object value = jsonObject.get(name);
        if (javaPropertyFilter != null && javaPropertyFilter.apply(bean, name, value)) {
            continue;
        }
        String key = Map.class.isAssignableFrom(beanClass)
                && jsonConfig.isSkipJavaIdentifierTransformationInMapKeys() ? name
                        : JSONUtils.convertToJavaIdentifier(name, jsonConfig);
        PropertyNameProcessor propertyNameProcessor = jsonConfig.findJavaPropertyNameProcessor(beanClass);
        if (propertyNameProcessor != null) {
            key = propertyNameProcessor.processPropertyName(beanClass, key);
        }
        try {
            if (Map.class.isAssignableFrom(beanClass)) {
                // no type info available for conversion
                if (JSONUtils.isNull(value)) {
                    setProperty(bean, key, value, jsonConfig);
                } else if (value instanceof JSONArray) {
                    setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name,
                            classMap, List.class), jsonConfig);
                } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                        || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                        || JSONFunction.class.isAssignableFrom(type)) {
                    if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                        setProperty(bean, key, null, jsonConfig);
                    } else {
                        setProperty(bean, key, value, jsonConfig);
                    }
                } else {
                    Class targetClass = findTargetClass(key, classMap);
                    targetClass = targetClass == null ? findTargetClass(name, classMap) : targetClass;
                    JsonConfig jsc = jsonConfig.copy();
                    jsc.setRootClass(targetClass);
                    jsc.setClassMap(classMap);
                    if (targetClass != null) {
                        setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                    } else {
                        setProperty(bean, key, toBean((JSONObject) value), jsonConfig);
                    }
                }
            } else {
                PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, key);
                if (pd != null && pd.getWriteMethod() == null) {
                    log.info("Property '" + key + "' of " + bean.getClass() + " has no write method. SKIPPED.");
                    continue;
                }

                if (pd != null) {
                    Class targetType = pd.getPropertyType();
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            if (List.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else if (Set.class.isAssignableFrom(pd.getPropertyType())) {
                                setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                        name, classMap, pd.getPropertyType()), jsonConfig);
                            } else {
                                setProperty(bean, key, convertPropertyValueToArray(key, value, targetType,
                                        jsonConfig, classMap), jsonConfig);
                            }
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (pd != null) {
                                if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) {
                                    setProperty(bean, key, null, jsonConfig);
                                } else if (!targetType.isInstance(value)) {
                                    setProperty(bean, key, morphPropertyValue(key, value, type, targetType),
                                            jsonConfig);
                                } else {
                                    setProperty(bean, key, value, jsonConfig);
                                }
                            } else if (beanClass == null || bean instanceof Map) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                JSONArray array = new JSONArray().element(value, jsonConfig);
                                Class newTargetClass = findTargetClass(key, classMap);
                                newTargetClass = newTargetClass == null ? findTargetClass(name, classMap)
                                        : newTargetClass;
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                if (targetType.isArray()) {
                                    setProperty(bean, key, JSONArray.toArray(array, jsc), jsonConfig);
                                } else if (JSONArray.class.isAssignableFrom(targetType)) {
                                    setProperty(bean, key, array, jsonConfig);
                                } else if (List.class.isAssignableFrom(targetType)
                                        || Set.class.isAssignableFrom(targetType)) {
                                    jsc.setCollectionType(targetType);
                                    setProperty(bean, key, JSONArray.toCollection(array, jsc), jsonConfig);
                                } else {
                                    setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                                }
                            } else {
                                if (targetType == Object.class || targetType.isInterface()) {
                                    Class targetTypeCopy = targetType;
                                    targetType = findTargetClass(key, classMap);
                                    targetType = targetType == null ? findTargetClass(name, classMap)
                                            : targetType;
                                    targetType = targetType == null && targetTypeCopy.isInterface()
                                            ? targetTypeCopy
                                            : targetType;
                                }
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(targetType);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                } else {
                    // pd is null
                    if (!JSONUtils.isNull(value)) {
                        if (value instanceof JSONArray) {
                            setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig,
                                    name, classMap, List.class), jsonConfig);
                        } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type)
                                || JSONUtils.isNumber(type) || JSONUtils.isString(type)
                                || JSONFunction.class.isAssignableFrom(type)) {
                            if (beanClass == null || bean instanceof Map
                                    || jsonConfig.getPropertySetStrategy() != null
                                    || !jsonConfig.isIgnorePublicFields()) {
                                setProperty(bean, key, value, jsonConfig);
                            } else {
                                log.warn("Tried to assign property " + key + ":" + type.getName()
                                        + " to bean of class " + bean.getClass().getName());
                            }
                        } else {
                            if (jsonConfig.isHandleJettisonSingleElementArray()) {
                                Class newTargetClass = findTargetClass(key, classMap);
                                newTargetClass = newTargetClass == null ? findTargetClass(name, classMap)
                                        : newTargetClass;
                                JsonConfig jsc = jsonConfig.copy();
                                jsc.setRootClass(newTargetClass);
                                jsc.setClassMap(classMap);
                                setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig);
                            } else {
                                setProperty(bean, key, value, jsonConfig);
                            }
                        }
                    } else {
                        if (type.isPrimitive()) {
                            // assume assigned default value
                            log.warn("Tried to assign null value to " + key + ":" + type.getName());
                            setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null),
                                    jsonConfig);
                        } else {
                            setProperty(bean, key, null, jsonConfig);
                        }
                    }
                }
            }
        } catch (JSONException jsone) {
            throw jsone;
        } catch (Exception e) {
            throw new JSONException("Error while setting property=" + name + " type " + type, e);
        }
    }

    return bean;
}

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

private String object2String(FieldData objectDTO) {
    Object returnedValue = objectDTO.valueToProcess;

    if (returnedValue == null) {
        return null;

    } else if (returnedValue instanceof String) {
        String str = (String) returnedValue;
        if (objectDTO.isJsonRawValue()) {
            return str;
        } else if (objectDTO.doubleQuote) {
            return StringUtil.doublequote(str, isEscapeHtml());
        } else {//w  w  w.j a  v a  2s  .com
            return str;
        }
    }

    Class type = returnedValue.getClass();

    if (type.isPrimitive()) {
        return returnedValue + "";

    } else if (Number.class.isAssignableFrom(type)) {
        return NumberUtil.toPlainString((Number) returnedValue, this.isAppendingFloatingZero());

    } else if (Enum.class.isAssignableFrom(type)) {
        return enum2Json(objectDTO);

    } else if (returnedValue instanceof Character) {
        String str = ((Character) returnedValue).toString();
        if (objectDTO.isJsonRawValue()) {
            return str;
        } else if (objectDTO.doubleQuote) {
            return StringUtil.doublequote(str, isEscapeHtml());
        } else {
            return str;
        }

    } else if (Date.class.isAssignableFrom(returnedValue.getClass())) {
        Date valueToProcess = (Date) returnedValue;

        Boolean date2Long = objectDTO.getDate2Long();

        if (date2Long != null && date2Long) {
            long longtoprocess = valueToProcess.getTime();
            return NumberUtil.toPlainString(longtoprocess);
        } else {
            String str = objectDTO.getDateFormat().format(valueToProcess);

            if (objectDTO.isJsonRawValue()) {
                return str;
            } else if (objectDTO.doubleQuote) {
                return StringUtil.doublequote(str, isEscapeHtml());
            } else {
                return str;
            }
        }

    } else if (returnedValue instanceof Boolean) {
        return ((Boolean) returnedValue).toString();

    } else {

        int oldLevel = this.getLevel();
        boolean oldPrettyPrinting = this.getPrettyPrinting();

        // now change it
        this.setLevel(5);
        this.pretty(false);

        String json = null;

        objectDTO.returnType = type;

        if (Enum.class.isAssignableFrom(type)) {
            json = enum2Json(objectDTO);

        } else if (Collection.class.isAssignableFrom(type)) {
            json = collection2Json(objectDTO);

        } else if (type.isArray()) {
            json = array2Json(objectDTO);

        } else if (Map.class.isAssignableFrom(type)) {
            json = map2Json(objectDTO);

        } else {
            objectDTO.classMapper = getGlobalizedClassMapper(type);
            json = object2Serialize(objectDTO);
            objectDTO.jsonRawValue = true;
        }

        // set it back
        this.setLevel(oldLevel);
        this.pretty(oldPrettyPrinting);

        return json;
    }
}

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

private <T> Object getParameterValue(Map<String, Object> map, Class<T> valueType, String parameterName,
        Class parameterType) {
    Object parameterValue = getMapValue(map, parameterName);

    Class fieldType = null;/*from w  ww. j a  v a2s .  com*/
    if (Map.class.isAssignableFrom(parameterType)) {
        // just give the whole map data to it
        // it can use as much of it as it likes
        parameterValue = map;

    } else {

        if (parameterType.isPrimitive() || Number.class.isAssignableFrom(parameterType)
                || parameterType == String.class || parameterType == Character.class
                || parameterType == Boolean.class || Date.class.isAssignableFrom(parameterType)
                || parameterType.isEnum() || Enum.class.isAssignableFrom(parameterType)) {
            // do nothing

        } else {
            String toGenericString = parameterType.toGenericString();
            fieldType = ObjectUtil.getComponentType(toGenericString);

            if (fieldType == null) {
                Field[] fields = getFields(valueType);
                for (Field field : fields) {
                    if (field.getName().equalsIgnoreCase(parameterName)) {
                        // private java.util.List<ca.oson.json.domain.Address> ca.oson.json.domain.Person.addressList
                        toGenericString = field.toGenericString();

                        // fieldType = field.getType(); // getClass();
                        fieldType = ObjectUtil.getComponentType(toGenericString);
                        break;
                    }
                }
            }
        }

        FieldData objectDTO = null;
        if (fieldType != null) {
            // FieldData(Object valueToProcess, Type type, boolean json2Java)
            ComponentType componentType = new ComponentType(parameterType, fieldType);
            cachedComponentTypes(componentType);

            objectDTO = new FieldData(parameterValue, parameterType, true);
            objectDTO.componentType = componentType;
        } else {
            objectDTO = new FieldData(parameterValue, parameterType, true);
        }
        objectDTO.required = true;
        parameterValue = json2Object(objectDTO);
    }

    return parameterValue;
}

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

private <E> String collection2Json(FieldData objectDTO) {
    Object value = objectDTO.valueToProcess;
    Class<?> returnType = objectDTO.returnType;

    if (value != null) {
        Collection collection = (Collection) value;
        Function function = objectDTO.getSerializer();
        String valueToReturn = null;

        if (function != null) {
            try {

                // suppose to return String, but in case not, try to process
                if (function instanceof DataMapper2JsonFunction) {
                    DataMapper classData = new DataMapper(returnType, collection, objectDTO.classMapper,
                            objectDTO.level, getPrettyIndentation());
                    return ((DataMapper2JsonFunction) function).apply(classData);

                } else if (function instanceof Collection2JsonFunction) {
                    return ((Collection2JsonFunction) function).apply(collection);

                } else {

                    Object returnedValue = null;
                    if (function instanceof FieldData2JsonFunction) {
                        FieldData2JsonFunction f = (FieldData2JsonFunction) function;
                        FieldData fieldData = objectDTO.clone();
                        returnedValue = f.apply(fieldData);
                    } else {
                        returnedValue = function.apply(value);
                    }//w  w  w.j  ava  2  s . com

                    if (returnedValue instanceof Optional) {
                        returnedValue = ObjectUtil.unwrap(returnedValue);
                    }

                    if (returnedValue == null) {
                        return null;

                    } else if (Collection.class.isAssignableFrom(returnedValue.getClass())) {
                        // keep on processing
                        collection = (Collection) returnedValue;

                    } else {
                        objectDTO.valueToProcess = returnedValue;
                        return object2String(objectDTO);
                    }
                }

            } catch (Exception ex) {
            }
        }

        String repeated = getPrettyIndentationln(objectDTO.level);
        objectDTO.incrLevel();
        String repeatedItem = getPrettyIndentationln(objectDTO.level);
        StringBuilder sbuilder = new StringBuilder();
        Class ctype = objectDTO.getComponentType(getJsonClassType());

        try {
            List<String> list = new ArrayList<>();

            for (Object s : collection) {
                String str = null;
                if (s != null) {
                    FieldData newFieldData = new FieldData(s, s.getClass(), objectDTO.json2Java,
                            objectDTO.level, objectDTO.set);
                    newFieldData.returnType = guessComponentType(newFieldData);
                    newFieldData.fieldMapper = objectDTO.fieldMapper;
                    str = object2Json(newFieldData);
                }

                if (str == null && ((ctype != null && ctype.isPrimitive())
                        || getDefaultType() == JSON_INCLUDE.DEFAULT)) {
                    str = getDefaultValue(ctype).toString();
                }

                list.add(str);
            }

            if (objectDTO.classMapper.orderArrayAndList) {
                Collections.sort(list);
            }

            for (String str : list) {
                sbuilder.append(repeatedItem + str + ",");
            }

        } catch (Exception ex) {
        }

        String str = sbuilder.toString();
        int size = str.length();
        if (size > 0) {
            return "[" + str.substring(0, size - 1) + repeated + "]";
        } else {
            switch (objectDTO.defaultType) {
            case ALWAYS:
                return "[]";
            case NON_NULL:
                return "[]";
            case NON_EMPTY:
                return null;
            case NON_DEFAULT:
                return null;
            case DEFAULT:
                return "[]";
            default:
                return "[]";
            }

        }
    }

    return collection2JsonDefault(objectDTO);
}