Search in sources :

Example 46 with PropertyDescriptor

use of java.beans.PropertyDescriptor in project jdk8u_jdk by JetBrains.

the class Test4682386 method testSwingProperties.

/**
     * Should be exectuted with $JAVA_HOME/lib/dt.jar in the classpath
     * so that there will be a lot more bound properties.
     * <p/>
     * This test isn't really appropriate for automated testing.
     */
private static void testSwingProperties() {
    long start = System.currentTimeMillis();
    for (Class type : TYPES) {
        try {
            Object bean = Beans.instantiate(type.getClassLoader(), type.getName());
            JComponent comp = (JComponent) bean;
            for (int k = 0; k < NUM_LISTENERS; k++) {
                comp.addPropertyChangeListener(new PropertyListener());
            }
            for (PropertyDescriptor pd : getPropertyDescriptors(type)) {
                if (pd.isBound()) {
                    if (DEBUG) {
                        System.out.println("Bound property found: " + pd.getName());
                    }
                    Method read = pd.getReadMethod();
                    Method write = pd.getWriteMethod();
                    try {
                        write.invoke(bean, getValue(pd.getPropertyType(), read.invoke(bean)));
                    } catch (Exception ex) {
                        // do nothing - just move on.
                        if (DEBUG) {
                            System.out.println("Reflective method invocation Exception for " + type + " : " + ex.getMessage());
                        }
                    }
                }
            }
        } catch (Exception ex) {
            // do nothing - just move on.
            if (DEBUG) {
                System.out.println("Exception for " + type.getName() + " : " + ex.getMessage());
            }
        }
    }
    System.out.println("Exec time (ms): " + (System.currentTimeMillis() - start));
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) JComponent(javax.swing.JComponent) Method(java.lang.reflect.Method) IntrospectionException(java.beans.IntrospectionException)

Example 47 with PropertyDescriptor

use of java.beans.PropertyDescriptor in project jdk8u_jdk by JetBrains.

the class BeanValidator method validate.

public void validate(Object object1, Object object2) {
    // compare references
    if (object1 == object2) {
        return;
    }
    // check for null
    if ((object1 == null) || (object2 == null)) {
        throw new IllegalStateException("could not compare object with null");
    }
    // resolve self references
    if (isCyclic(object1, object2)) {
        return;
    }
    // resolve cross references
    if (isCyclic(object2, object1)) {
        return;
    }
    Class type = object1.getClass();
    if (!type.equals(object2.getClass())) {
        // resolve different implementations of the Map.Entry interface
        if ((object1 instanceof Map.Entry) && (object2 instanceof Map.Entry)) {
            log("!!! special case", "Map.Entry");
            Map.Entry entry1 = (Map.Entry) object1;
            Map.Entry entry2 = (Map.Entry) object2;
            validate(entry1.getKey(), entry2.getKey());
            validate(entry1.getValue(), entry2.getValue());
            return;
        }
        throw new IllegalStateException("could not compare objects with different types");
    }
    // validate elements of arrays
    if (type.isArray()) {
        int length = Array.getLength(object1);
        if (length != Array.getLength(object2)) {
            throw new IllegalStateException("could not compare arrays with different lengths");
        }
        try {
            this.cache.put(object1, object2);
            for (int i = 0; i < length; i++) {
                log("validate array element", Integer.valueOf(i));
                validate(Array.get(object1, i), Array.get(object2, i));
            }
        } finally {
            this.cache.remove(object1);
        }
        return;
    }
    // special case for collections: do not use equals
    boolean ignore = Collection.class.isAssignableFrom(type) || Map.Entry.class.isAssignableFrom(type) || Map.class.isAssignableFrom(type);
    // if the class declares such method
    if (!ignore && isDefined(type, "equals", Object.class)) {
        if (object1.equals(object2)) {
            return;
        }
        throw new IllegalStateException("the first object is not equal to the second one");
    }
    // if the class declares such method and implements interface Comparable
    if (Comparable.class.isAssignableFrom(type) && isDefined(type, "compareTo", Object.class)) {
        Comparable cmp = (Comparable) object1;
        if (0 == cmp.compareTo(object2)) {
            return;
        }
        throw new IllegalStateException("the first comparable object is not equal to the second one");
    }
    try {
        this.cache.put(object1, object2);
        // validate values of public fields
        for (Field field : getFields(type)) {
            int mod = field.getModifiers();
            if (!Modifier.isStatic(mod)) {
                log("validate field", field.getName());
                validate(object1, object2, field);
            }
        }
        // validate values of properties
        for (PropertyDescriptor pd : getDescriptors(type)) {
            Method method = pd.getReadMethod();
            if (method != null) {
                log("validate property", pd.getName());
                validate(object1, object2, method);
            }
        }
        // validate contents of maps
        if (SortedMap.class.isAssignableFrom(type)) {
            validate((Map) object1, (Map) object2, true);
        } else if (Map.class.isAssignableFrom(type)) {
            validate((Map) object1, (Map) object2, false);
        }
        // validate contents of collections
        if (SortedSet.class.isAssignableFrom(type)) {
            validate((Collection) object1, (Collection) object2, true);
        } else if (List.class.isAssignableFrom(type)) {
            validate((Collection) object1, (Collection) object2, true);
        } else if (Queue.class.isAssignableFrom(type)) {
            validate((Collection) object1, (Collection) object2, true);
        } else if (Collection.class.isAssignableFrom(type)) {
            validate((Collection) object1, (Collection) object2, false);
        }
    } finally {
        this.cache.remove(object1);
    }
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) Method(java.lang.reflect.Method) Field(java.lang.reflect.Field) Collection(java.util.Collection) ArrayList(java.util.ArrayList) List(java.util.List) IdentityHashMap(java.util.IdentityHashMap) Map(java.util.Map) SortedMap(java.util.SortedMap)

Example 48 with PropertyDescriptor

use of java.beans.PropertyDescriptor in project opennms by OpenNMS.

the class AbstractXmlCollectionHandler method parseString.

/**
 * Parses the string.
 *
 * <p>Valid placeholders are:</p>
 * <ul>
 * <li><b>ipAddr|ipAddress</b>, The Node IP Address</li>
 * <li><b>step</b>, The Collection Step in seconds</li>
 * <li><b>nodeId</b>, The Node ID</li>
 * <li><b>nodeLabel</b>, The Node Label</li>
 * <li><b>foreignId</b>, The Node Foreign ID</li>
 * <li><b>foreignSource</b>, The Node Foreign Source</li>
 * <li>Any asset property defined on the node.</li>
 * </ul>
 *
 * @param reference the reference
 * @param unformattedString the unformatted string
 * @param node the node
 * @param ipAddress the IP address
 * @param collectionStep the collection step
 * @param parameters the service parameters
 * @return the string
 * @throws IllegalArgumentException the illegal argument exception
 */
protected static String parseString(final String reference, final String unformattedString, final OnmsNode node, final String ipAddress, final Integer collectionStep, final Map<String, String> parameters) throws IllegalArgumentException {
    if (unformattedString == null || node == null)
        return null;
    String formattedString = unformattedString.replaceAll("[{](?i)(ipAddr|ipAddress)[}]", ipAddress);
    formattedString = formattedString.replaceAll("[{](?i)step[}]", collectionStep.toString());
    formattedString = formattedString.replaceAll("[{](?i)nodeId[}]", node.getNodeId());
    if (node.getLabel() != null)
        formattedString = formattedString.replaceAll("[{](?i)nodeLabel[}]", node.getLabel());
    if (node.getForeignId() != null)
        formattedString = formattedString.replaceAll("[{](?i)foreignId[}]", node.getForeignId());
    if (node.getForeignSource() != null)
        formattedString = formattedString.replaceAll("[{](?i)foreignSource[}]", node.getForeignSource());
    for (Map.Entry<String, String> entry : parameters.entrySet()) {
        formattedString = formattedString.replaceAll("[{]parameter:" + entry.getKey() + "[}]", entry.getValue());
    }
    if (node.getAssetRecord() != null) {
        BeanWrapper wrapper = new BeanWrapperImpl(node.getAssetRecord());
        for (PropertyDescriptor p : wrapper.getPropertyDescriptors()) {
            Object obj = wrapper.getPropertyValue(p.getName());
            if (obj != null) {
                String objStr = obj.toString();
                try {
                    // NMS-7381 - if pulling from asset info you'd expect to not have to encode reserved words yourself.
                    objStr = URLEncoder.encode(obj.toString(), StandardCharsets.UTF_8.name());
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                formattedString = formattedString.replaceAll("[{](?i)" + p.getName() + "[}]", objStr);
            }
        }
    }
    if (formattedString.matches(".*[{].+[}].*"))
        throw new IllegalArgumentException("The " + reference + " " + formattedString + " contains unknown placeholders.");
    return formattedString;
}
Also used : BeanWrapper(org.springframework.beans.BeanWrapper) BeanWrapperImpl(org.springframework.beans.BeanWrapperImpl) PropertyDescriptor(java.beans.PropertyDescriptor) UnsupportedEncodingException(java.io.UnsupportedEncodingException) XmlObject(org.opennms.protocols.xml.config.XmlObject) Map(java.util.Map)

Example 49 with PropertyDescriptor

use of java.beans.PropertyDescriptor in project rabbitmq-java-client by rabbitmq.

the class JSONWriter method writeLimited.

/**
 * Write only a certain subset of the object's properties and fields.
 * @param klass the class to look up properties etc in
 * @param object the object
 * @param properties explicit list of property/field names to include - may be null for "all"
 */
public void writeLimited(Class<?> klass, Object object, String[] properties) {
    Set<String> propertiesSet = null;
    if (properties != null) {
        propertiesSet = new HashSet<String>();
        for (String p : properties) {
            propertiesSet.add(p);
        }
    }
    add('{');
    indentLevel += 2;
    newline();
    boolean needComma = false;
    BeanInfo info;
    try {
        info = Introspector.getBeanInfo(klass);
    } catch (IntrospectionException ie) {
        info = null;
    }
    if (info != null) {
        PropertyDescriptor[] props = info.getPropertyDescriptors();
        for (int i = 0; i < props.length; ++i) {
            PropertyDescriptor prop = props[i];
            String name = prop.getName();
            if (propertiesSet == null && name.equals("class")) {
                // We usually don't want the class in there.
                continue;
            }
            if (propertiesSet == null || propertiesSet.contains(name)) {
                Method accessor = prop.getReadMethod();
                if (accessor != null && !Modifier.isStatic(accessor.getModifiers())) {
                    try {
                        Object value = accessor.invoke(object, (Object[]) null);
                        if (needComma) {
                            add(',');
                            newline();
                        }
                        needComma = true;
                        add(name, value);
                    } catch (Exception e) {
                    // Ignore it.
                    }
                }
            }
        }
    }
    Field[] ff = object.getClass().getDeclaredFields();
    for (int i = 0; i < ff.length; ++i) {
        Field field = ff[i];
        int fieldMod = field.getModifiers();
        String name = field.getName();
        if (propertiesSet == null || propertiesSet.contains(name)) {
            if (!Modifier.isStatic(fieldMod)) {
                try {
                    Object v = field.get(object);
                    if (needComma) {
                        add(',');
                        newline();
                    }
                    needComma = true;
                    add(name, v);
                } catch (Exception e) {
                // Ignore it.
                }
            }
        }
    }
    indentLevel -= 2;
    newline();
    add('}');
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) BeanInfo(java.beans.BeanInfo) IntrospectionException(java.beans.IntrospectionException) Method(java.lang.reflect.Method) IntrospectionException(java.beans.IntrospectionException) Field(java.lang.reflect.Field)

Example 50 with PropertyDescriptor

use of java.beans.PropertyDescriptor in project flowml by beautifulNow1992.

the class BeanToMapUtil method convertBean.

/**
 * 将一个 JavaBean 对象转化为一个  Map
 *
 * @param bean 要转化的JavaBean 对象
 * @return 转化出来的  Map 对象
 * @throws IntrospectionException    如果分析类属性失败
 * @throws IllegalAccessException    如果实例化 JavaBean 失败
 * @throws InvocationTargetException 如果调用属性的 setter 方法失败
 */
public static Map<String, Object> convertBean(Object bean) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
    Class type = bean.getClass();
    Map<String, Object> returnMap = new HashMap<String, Object>();
    BeanInfo beanInfo = Introspector.getBeanInfo(type);
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    for (int i = 0; i < propertyDescriptors.length; i++) {
        PropertyDescriptor descriptor = propertyDescriptors[i];
        String propertyName = descriptor.getName();
        if (!propertyName.equals("class")) {
            Method readMethod = descriptor.getReadMethod();
            Object result = readMethod.invoke(bean);
            if (result != null) {
                returnMap.put(propertyName, result);
            } else {
                returnMap.put(propertyName, "");
            }
        }
    }
    return returnMap;
}
Also used : PropertyDescriptor(java.beans.PropertyDescriptor) HashMap(java.util.HashMap) BeanInfo(java.beans.BeanInfo) Method(java.lang.reflect.Method)

Aggregations

PropertyDescriptor (java.beans.PropertyDescriptor)836 Method (java.lang.reflect.Method)396 BeanInfo (java.beans.BeanInfo)339 IntrospectionException (java.beans.IntrospectionException)188 IndexedPropertyDescriptor (java.beans.IndexedPropertyDescriptor)171 SimpleBeanInfo (java.beans.SimpleBeanInfo)142 FakeFox01BeanInfo (org.apache.harmony.beans.tests.support.mock.FakeFox01BeanInfo)141 InvocationTargetException (java.lang.reflect.InvocationTargetException)108 ArrayList (java.util.ArrayList)90 HashMap (java.util.HashMap)66 Field (java.lang.reflect.Field)59 Map (java.util.Map)52 Test (org.junit.Test)39 IOException (java.io.IOException)34 MockJavaBean (org.apache.harmony.beans.tests.support.mock.MockJavaBean)34 List (java.util.List)33 HashSet (java.util.HashSet)21 Type (java.lang.reflect.Type)20 Set (java.util.Set)20 LinkedHashMap (java.util.LinkedHashMap)19