Search in sources :

Example 1 with FastBeanInfo

use of org.eclipse.scout.rt.platform.reflect.FastBeanInfo in project scout.rt by eclipse.

the class JsonObjectUtility method jsonValueToJava.

@SuppressWarnings("unchecked")
private static <T> T jsonValueToJava(Object jval, Class<T> type, boolean throwForMissingProperty) {
    if (jval == null || jval == JSONObject.NULL) {
        return null;
    }
    // basic types
    if (type == String.class) {
        return (T) jval;
    }
    if (type == byte[].class) {
        return (T) new JsonByteArray((String) jval).getBytes();
    }
    if (type == Date.class) {
        return (T) new JsonDate((String) jval).asJavaDate();
    }
    if (type == int.class || type == Integer.class) {
        return (T) jval;
    }
    if (type == long.class || type == Long.class) {
        return (T) jval;
    }
    if (type == boolean.class || type == Boolean.class) {
        return (T) jval;
    }
    // array
    if (jval instanceof JSONArray) {
        JSONArray jarray = (JSONArray) jval;
        int n = jarray.length();
        T array = (T) Array.newInstance(type.getComponentType(), n);
        for (int i = 0; i < n; i++) {
            Array.set(array, i, jsonArrayElementToJava(jarray, i, type.getComponentType(), throwForMissingProperty));
        }
        return array;
    }
    // bean
    JSONObject jbean = (JSONObject) jval;
    T o;
    try {
        o = (T) type.newInstance();
    } catch (Exception e) {
        throw new IllegalArgumentException("type " + type + " object " + jval, e);
    }
    try {
        HashSet<String> missingNames = new HashSet<>();
        String[] nameArray = getNames(jbean);
        if (nameArray != null) {
            for (String key : nameArray) {
                missingNames.add(key);
            }
            for (String key : nameArray) {
                try {
                    // NOSONAR
                    Field f = type.getField(key);
                    if (Modifier.isStatic(f.getModifiers())) {
                        continue;
                    }
                    Object val = jsonObjectPropertyToJava(jbean, key, f.getType(), throwForMissingProperty);
                    f.set(o, val);
                    missingNames.remove(key);
                } catch (NoSuchElementException | NoSuchFieldException e) {
                // NOSONAR
                // nop
                }
            }
        }
        if (missingNames.size() > 0) {
            FastBeanInfo beanInfo = new FastBeanInfo(type, Object.class);
            for (FastPropertyDescriptor desc : beanInfo.getPropertyDescriptors()) {
                Method m = desc.getWriteMethod();
                if (m == null) {
                    continue;
                }
                String key = desc.getName();
                Object val = jsonObjectPropertyToJava(jbean, key, m.getParameterTypes()[0], throwForMissingProperty);
                m.invoke(o, val);
                missingNames.remove(key);
            }
        }
        if (throwForMissingProperty && missingNames.size() > 0) {
            throw new IllegalArgumentException("properties " + missingNames + " do not exist in " + type);
        }
        return o;
    } catch (IllegalAccessException | InvocationTargetException | RuntimeException e) {
        throw new IllegalArgumentException(jbean + " to " + type, e);
    }
}
Also used : FastPropertyDescriptor(org.eclipse.scout.rt.platform.reflect.FastPropertyDescriptor) FastBeanInfo(org.eclipse.scout.rt.platform.reflect.FastBeanInfo) Field(java.lang.reflect.Field) HashSet(java.util.HashSet) JSONArray(org.json.JSONArray) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) JSONException(org.json.JSONException) NoSuchElementException(java.util.NoSuchElementException) InvocationTargetException(java.lang.reflect.InvocationTargetException) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) NoSuchElementException(java.util.NoSuchElementException)

Example 2 with FastBeanInfo

use of org.eclipse.scout.rt.platform.reflect.FastBeanInfo in project scout.rt by eclipse.

the class JsonBean method toJson.

@Override
public Object toJson() {
    if (m_bean == null) {
        return null;
    }
    Class<?> type = m_bean.getClass();
    // basic types
    if (type.isPrimitive() || type == String.class || type == Boolean.class || Number.class.isAssignableFrom(type)) {
        return m_bean;
    }
    // binary resource
    if (BinaryResource.class.isAssignableFrom(type)) {
        BinaryResource binaryResource = (BinaryResource) m_bean;
        m_binaryResourceMediator.addBinaryResource(binaryResource);
        return m_binaryResourceMediator.createUrl(binaryResource);
    }
    // array
    if (type.isArray()) {
        JSONArray jsonArray = new JSONArray();
        int n = Array.getLength(m_bean);
        for (int i = 0; i < n; i++) {
            IJsonObject jsonObject = createJsonObject(Array.get(m_bean, i));
            jsonArray.put(jsonObject.toJson());
        }
        return jsonArray;
    }
    // collection
    if (Collection.class.isAssignableFrom(type)) {
        JSONArray jsonArray = new JSONArray();
        Collection collection = (Collection) m_bean;
        for (Object object : collection) {
            IJsonObject jsonObject = createJsonObject(object);
            jsonArray.put(jsonObject.toJson());
        }
        return jsonArray;
    }
    // Map
    if (Map.class.isAssignableFrom(type)) {
        JSONObject jsonMap = new JSONObject();
        Map map = (Map) m_bean;
        @SuppressWarnings("unchecked") Set<Entry> entries = (Set<Entry>) map.entrySet();
        for (Entry entry : entries) {
            if (!(entry.getKey() instanceof String)) {
                throw new IllegalArgumentException("Cannot convert " + type + " to json object");
            }
            IJsonObject jsonObject = createJsonObject(entry.getValue());
            jsonMap.put((String) entry.getKey(), jsonObject.toJson());
        }
        return jsonMap;
    }
    // bean
    if (type.getName().startsWith("java.")) {
        throw new IllegalArgumentException("Cannot convert " + type + " to json object");
    }
    try {
        TreeMap<String, Object> properties = new TreeMap<>();
        for (Field f : type.getFields()) {
            if (Modifier.isStatic(f.getModifiers())) {
                continue;
            }
            String key = f.getName();
            Object val = f.get(m_bean);
            IJsonObject jsonObject = createJsonObject(val);
            properties.put(key, jsonObject.toJson());
        }
        FastBeanInfo beanInfo = new FastBeanInfo(type, Object.class);
        for (FastPropertyDescriptor desc : beanInfo.getPropertyDescriptors()) {
            Method m = desc.getReadMethod();
            if (m == null) {
                continue;
            }
            // skip ignored annotated getters with context GUI
            IgnoreProperty ignoredPropertyAnnotation = m.getAnnotation(IgnoreProperty.class);
            if (ignoredPropertyAnnotation != null && Context.GUI.equals(ignoredPropertyAnnotation.value())) {
                continue;
            }
            String key = desc.getName();
            Object val = m.invoke(m_bean);
            IJsonObject jsonObject = createJsonObject(val);
            properties.put(key, jsonObject.toJson());
        }
        JSONObject jbean = new JSONObject();
        for (Map.Entry<String, Object> e : properties.entrySet()) {
            jbean.put(e.getKey(), e.getValue());
        }
        return jbean;
    } catch (Exception e) {
        throw new IllegalArgumentException(type + " to json", e);
    }
}
Also used : Set(java.util.Set) FastPropertyDescriptor(org.eclipse.scout.rt.platform.reflect.FastPropertyDescriptor) FastBeanInfo(org.eclipse.scout.rt.platform.reflect.FastBeanInfo) Field(java.lang.reflect.Field) Entry(java.util.Map.Entry) JSONArray(org.json.JSONArray) Method(java.lang.reflect.Method) TreeMap(java.util.TreeMap) BinaryResource(org.eclipse.scout.rt.platform.resource.BinaryResource) JSONObject(org.json.JSONObject) IgnoreProperty(org.eclipse.scout.rt.platform.annotations.IgnoreProperty) Collection(java.util.Collection) JSONObject(org.json.JSONObject) TreeMap(java.util.TreeMap) Map(java.util.Map)

Example 3 with FastBeanInfo

use of org.eclipse.scout.rt.platform.reflect.FastBeanInfo in project scout.rt by eclipse.

the class AbstractMemoryPolicy method createIdForPage.

private void createIdForPage(StringBuilder b, IPage<?> page, Object o) {
    b.append("/");
    b.append(page.getClass().getName());
    if (page.getUserPreferenceContext() != null) {
        b.append("/");
        b.append(page.getUserPreferenceContext());
    }
    if (o != null) {
        b.append("/");
        b.append(o.getClass().getName());
    }
    FastBeanInfo pi = new FastBeanInfo(page.getClass(), page.getClass().getSuperclass());
    for (FastPropertyDescriptor prop : pi.getPropertyDescriptors()) {
        if (prop.getReadMethod() != null && (Date.class.isAssignableFrom(prop.getPropertyType()) || Number.class.isAssignableFrom(prop.getPropertyType()) || String.class.isAssignableFrom(prop.getPropertyType()) || long.class.isAssignableFrom(prop.getPropertyType()))) {
            // only accept Numbers, Strings or Dates
            try {
                b.append("/");
                b.append(prop.getName());
                b.append("=");
                b.append(prop.getReadMethod().invoke(page, new Object[0]));
            } catch (Exception e) {
                LOG.error("Error reading property {}", prop, e);
            // nop - ignore this property
            }
        }
    }
}
Also used : FastPropertyDescriptor(org.eclipse.scout.rt.platform.reflect.FastPropertyDescriptor) Date(java.util.Date) FastBeanInfo(org.eclipse.scout.rt.platform.reflect.FastBeanInfo)

Example 4 with FastBeanInfo

use of org.eclipse.scout.rt.platform.reflect.FastBeanInfo in project scout.rt by eclipse.

the class BeanUtility method getFastBeanInfo.

/**
 * Get all property descriptors from this class up to (and excluding) stopClazz
 * <p>
 * Getting bean properties using {@link Introspector} can be very slow and time consuming.
 * <p>
 * This hi-speed property introspector only inspects bean names, types and read/write methods.
 * <p>
 * The results are cached for further speed optimization.
 */
public static FastBeanInfo getFastBeanInfo(Class<?> beanClass, Class<?> stopClass) {
    if (beanClass == null) {
        return new FastBeanInfo(beanClass, stopClass);
    }
    synchronized (BEAN_INFO_CACHE_LOCK) {
        CompositeObject key = new CompositeObject(beanClass, stopClass);
        FastBeanInfo info = BEAN_INFO_CACHE.get(key);
        if (info == null) {
            info = new FastBeanInfo(beanClass, stopClass);
            BEAN_INFO_CACHE.put(key, info);
        }
        return info;
    }
}
Also used : FastBeanInfo(org.eclipse.scout.rt.platform.reflect.FastBeanInfo)

Example 5 with FastBeanInfo

use of org.eclipse.scout.rt.platform.reflect.FastBeanInfo in project scout.rt by eclipse.

the class BeanUtility method getFastPropertyDescriptors.

/**
 * Get all properties from this class up to (and excluding) stopClazz
 *
 * @param filter
 */
public static FastPropertyDescriptor[] getFastPropertyDescriptors(Class<?> clazz, Class<?> stopClazz, IPropertyFilter filter) {
    FastBeanInfo info = getFastBeanInfo(clazz, stopClazz);
    FastPropertyDescriptor[] a = info.getPropertyDescriptors();
    ArrayList<FastPropertyDescriptor> filteredProperties = new ArrayList<FastPropertyDescriptor>(a.length);
    for (int i = 0; i < a.length; i++) {
        FastPropertyDescriptor pd = a[i];
        if (filter != null && !(filter.accept(pd))) {
        // ignore it
        } else {
            filteredProperties.add(pd);
        }
    }
    return filteredProperties.toArray(new FastPropertyDescriptor[filteredProperties.size()]);
}
Also used : ArrayList(java.util.ArrayList) FastPropertyDescriptor(org.eclipse.scout.rt.platform.reflect.FastPropertyDescriptor) FastBeanInfo(org.eclipse.scout.rt.platform.reflect.FastBeanInfo)

Aggregations

FastBeanInfo (org.eclipse.scout.rt.platform.reflect.FastBeanInfo)6 FastPropertyDescriptor (org.eclipse.scout.rt.platform.reflect.FastPropertyDescriptor)5 Method (java.lang.reflect.Method)3 Field (java.lang.reflect.Field)2 Map (java.util.Map)2 TreeMap (java.util.TreeMap)2 JSONArray (org.json.JSONArray)2 JSONObject (org.json.JSONObject)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)1 ArrayList (java.util.ArrayList)1 Collection (java.util.Collection)1 Date (java.util.Date)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Entry (java.util.Map.Entry)1 NoSuchElementException (java.util.NoSuchElementException)1 Set (java.util.Set)1 IgnoreProperty (org.eclipse.scout.rt.platform.annotations.IgnoreProperty)1 ProcessingException (org.eclipse.scout.rt.platform.exception.ProcessingException)1 BinaryResource (org.eclipse.scout.rt.platform.resource.BinaryResource)1