Java Code Examples for java.beans.IntrospectionException

The following are top voted examples for showing how to use java.beans.IntrospectionException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ares   File: ReflectionManager.java   View source code 7 votes vote down vote up
/**
 * Maps object attributes.
 * @param type the class to reflect.
 * @param object the instance to address.
 * @param <T> the class to reflect.
 * @return the attributes mapping.
 * @throws IntrospectionException when errors in reflection.
 * @throws InvocationTargetException when errors in reflection.
 * @throws IllegalAccessException when errors in reflection.
 */
public static <T> Map<String,Object> getAttributes(Class<T> type, T object)
    throws IntrospectionException, InvocationTargetException, IllegalAccessException {
  Map<String,Object> propsmap = new HashMap<>();
  final BeanInfo beanInfo = Introspector.getBeanInfo(type);
  final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
  for (PropertyDescriptor pd : propertyDescriptors) {
    if (pd.getName().equals("class")) continue;
    final Method getter = pd.getReadMethod();
    if (getter != null) {
      final String attrname = pd.getName();
      final Object attrvalue = getter.invoke(object);
      propsmap.put(attrname, attrvalue);
    }
  }
  return propsmap;
}
 
Example 2
Project: openjdk-jdk10   File: Test4520754.java   View source code 7 votes vote down vote up
private static BeanInfo getBeanInfo(Boolean mark, Class type) {
    System.out.println("test=" + mark + " for " + type);
    BeanInfo info;
    try {
        info = Introspector.getBeanInfo(type);
    } catch (IntrospectionException exception) {
        throw new Error("unexpected exception", exception);
    }
    if (info == null) {
        throw new Error("could not find BeanInfo for " + type);
    }
    if (mark != info.getBeanDescriptor().getValue("test")) {
        throw new Error("could not find marked BeanInfo for " + type);
    }
    return info;
}
 
Example 3
Project: GitHub   File: ExcludedFromEqualsAndHashCodeIT.java   View source code 6 votes vote down vote up
@Test
public void exludedByPropertyTest() throws IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
    Object instanceOne = clazz.newInstance();
    Object instanceTwo = clazz.newInstance();

    setProperty(instanceOne, "excludedByProperty", "one");
    setProperty(instanceOne, "excludedByArray", "two");
    setProperty(instanceOne, "notExcluded", "three");
    setProperty(instanceOne, "notExcludedByProperty", "four");

    setProperty(instanceTwo, "excludedByProperty", "differentValue");
    setProperty(instanceTwo, "excludedByArray", "two");
    setProperty(instanceTwo, "notExcluded", "three");
    setProperty(instanceTwo, "notExcludedByProperty", "four");

    assertThat(instanceOne.equals(instanceTwo), is(true));
}
 
Example 4
Project: GitHub   File: ExcludedFromEqualsAndHashCodeIT.java   View source code 6 votes vote down vote up
@Test
public void notExludedByPropertyTest() throws IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
    Object instanceOne = clazz.newInstance();
    Object instanceTwo = clazz.newInstance();

    setProperty(instanceOne, "excludedByProperty", "one");
    setProperty(instanceOne, "excludedByArray", "two");
    setProperty(instanceOne, "notExcluded", "three");
    setProperty(instanceOne, "notExcludedByProperty", "four");

    setProperty(instanceTwo, "excludedByProperty", "one");
    setProperty(instanceTwo, "excludedByArray", "two");
    setProperty(instanceTwo, "notExcluded", "three");
    setProperty(instanceTwo, "notExcludedByProperty", "differentValue");

    assertThat(instanceOne.equals(instanceTwo), is(false));
}
 
Example 5
Project: bubichain-sdk-java   File: PojoPropertiesConverter.java   View source code 6 votes vote down vote up
private void resolveParamProperties() throws IntrospectionException{
    List<ArgDefEntry<RequestParamDefinition>> reqParamDefs = new LinkedList<>();

    BeanInfo beanInfo = Introspector.getBeanInfo(argType);
    PropertyDescriptor[] propDescs = beanInfo.getPropertyDescriptors();

    for (PropertyDescriptor propDesc : propDescs) {
        //            TypeDescriptor propTypeDesc;
        //            propTypeDesc = beanWrapper.getPropertyTypeDescriptor(propDesc.getName());


        //            RequestParam reqParamAnno = propTypeDesc.getAnnotation(RequestParam.class);
        RequestParam reqParamAnno = propDesc.getPropertyType().getAnnotation(RequestParam.class);
        if (reqParamAnno == null) {
            // 忽略未标注 RequestParam 的属性;
            continue;
        }
        RequestParamDefinition reqParamDef = RequestParamDefinition.resolveDefinition(reqParamAnno);
        ArgDefEntry<RequestParamDefinition> defEntry = new ArgDefEntry<>(reqParamDefs.size(), propDesc.getPropertyType(),
                reqParamDef);
        reqParamDefs.add(defEntry);
        propNames.add(propDesc.getName());
    }
    paramResolver = RequestParamResolvers.createParamResolver(reqParamDefs);
}
 
Example 6
Project: jdk8u-jdk   File: Test4508780.java   View source code 6 votes vote down vote up
private static PropertyDescriptor[] getPropertyDescriptors(Object object) {
    Class type = object.getClass();
    synchronized (System.out) {
        System.out.println(type);
        ClassLoader loader = type.getClassLoader();
        while (loader != null) {
            System.out.println(" - loader: " + loader);
            loader = loader.getParent();
        }
    }
    try {
        return Introspector.getBeanInfo(type).getPropertyDescriptors();
    } catch (IntrospectionException exception) {
        throw new Error("unexpected exception", exception);
    }
}
 
Example 7
Project: jdk8u-jdk   File: Test4619792.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws IntrospectionException {
    Class[] types = {
            Component.class,
            Container.class,
            JComponent.class,
            AbstractButton.class,
            JButton.class,
            JToggleButton.class,
    };
    // Control set. "enabled" and "name" has the same pattern and can be found
    String[] names = {
            "enabled",
            "name",
            "focusable",
    };
    for (String name : names) {
        for (Class type : types) {
            BeanUtils.getPropertyDescriptor(type, name);
        }
    }
}
 
Example 8
Project: jdk8u-jdk   File: Test6447751.java   View source code 6 votes vote down vote up
private static void test(Class<?> type, Class<?> expected) {
    Class<?> actual;
    try {
        actual = Introspector.getBeanInfo(type).getBeanDescriptor().getCustomizerClass();
    }
    catch (IntrospectionException exception) {
        throw new Error("unexpected error", exception);
    }
    if (actual != expected) {
        StringBuilder sb = new StringBuilder();
        sb.append("bean ").append(type).append(": ");
        if (expected != null) {
            sb.append("expected ").append(expected);
            if (actual != null) {
                sb.append(", but ");
            }
        }
        if (actual != null) {
            sb.append("found ").append(actual);
        }
        throw new Error(sb.toString());
    }
}
 
Example 9
Project: incubator-netbeans   File: AnnotationTypesNode.java   View source code 6 votes vote down vote up
/** Initialize the collection with results of parsing of "Editors/AnnotationTypes" directory */
protected java.util.Collection initCollection() {
    
    AnnotationTypesFolder folder = AnnotationTypesFolder.getAnnotationTypesFolder();

    Iterator types = AnnotationTypes.getTypes().getAnnotationTypeNames();

    java.util.List list = new java.util.LinkedList();

    for( ; types.hasNext(); ) {
        String name = (String)types.next();
        AnnotationType type = AnnotationTypes.getTypes().getType(name);
        if (type == null || !type.isVisible())
            continue;
        try {
            list.add(new AnnotationTypesSubnode(type));
        } catch (IntrospectionException e) {
            Exceptions.printStackTrace(e);
            continue;
        }
    }

    return list;
}
 
Example 10
Project: lams   File: PropertyDictionary.java   View source code 6 votes vote down vote up
private Map<String, PropertyDescriptor> buildMap(final Class<?> type) {
    Map<String, PropertyDescriptor> nameMap = propertyNameCache.get(type);
    if (nameMap == null) {
        BeanInfo beanInfo;
        try {
            beanInfo = Introspector.getBeanInfo(type, Object.class);
        } catch (final IntrospectionException e) {
            throw new ObjectAccessException("Cannot get BeanInfo of type " + type.getName(), e);
        }
        nameMap = new LinkedHashMap<String, PropertyDescriptor>();
        final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (final PropertyDescriptor descriptor : propertyDescriptors) {
            nameMap.put(descriptor.getName(), descriptor);
        }
        nameMap = sorter.sort(type, nameMap);
        propertyNameCache.put(type, nameMap);
    }
    return nameMap;
}
 
Example 11
Project: GitHub   File: PropertiesIT.java   View source code 6 votes vote down vote up
@Test
@SuppressWarnings("rawtypes")
public void propertiesAreSerializedInCorrectOrder() throws ClassNotFoundException, IntrospectionException, InstantiationException, IllegalAccessException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/properties/orderedProperties.json", "com.example");

    Class generatedType = resultsClassLoader.loadClass("com.example.OrderedProperties");
    Object instance = generatedType.newInstance();

    new PropertyDescriptor("type", generatedType).getWriteMethod().invoke(instance, "1");
    new PropertyDescriptor("id", generatedType).getWriteMethod().invoke(instance, "2");
    new PropertyDescriptor("name", generatedType).getWriteMethod().invoke(instance, "3");
    new PropertyDescriptor("hastickets", generatedType).getWriteMethod().invoke(instance, true);
    new PropertyDescriptor("starttime", generatedType).getWriteMethod().invoke(instance, "4");

    String serialized = mapper.valueToTree(instance).toString();

    assertThat("Properties are not in expected order", serialized.indexOf("type"), is(lessThan(serialized.indexOf("id"))));
    assertThat("Properties are not in expected order", serialized.indexOf("id"), is(lessThan(serialized.indexOf("name"))));
    assertThat("Properties are not in expected order", serialized.indexOf("name"), is(lessThan(serialized.indexOf("hastickets"))));
    assertThat("Properties are not in expected order", serialized.indexOf("hastickets"), is(lessThan(serialized.indexOf("starttime"))));

}
 
Example 12
Project: openjdk-jdk10   File: OverrideUserDefPropertyInfoTest.java   View source code 6 votes vote down vote up
@Override
public PropertyDescriptor[] getPropertyDescriptors() {
    PropertyDescriptor[] p = new PropertyDescriptor[1];

    try {
        p[0] = new PropertyDescriptor ("x", Base.class, "getX", null);
        p[0].setShortDescription("BASEPROPERTY");
        p[0].setBound (baseFlag);
        p[0].setExpert(baseFlag);
        p[0].setHidden(baseFlag);
        p[0].setPreferred(baseFlag);
        p[0].setValue("required", baseFlag);
        p[0].setValue("visualUpdate", baseFlag);
        p[0].setValue("enumerationValues",
            new Object[]{"TOP", 1, "javax.swing.SwingConstants.TOP"});
    } catch(IntrospectionException e) { e.printStackTrace(); }

    return p;
}
 
Example 13
Project: spring-data-jdbc   File: ReflectionRowUnmapper.java   View source code 6 votes vote down vote up
private void createMethodsMap() {
    methodsMap = new LinkedHashMap<String, Method>();
    Method method;
    try {
        for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(entityClass)
                                                                 .getPropertyDescriptors()) {
            if (propertyDescriptor.getWriteMethod() != null && (method = propertyDescriptor.getReadMethod()) != null) {
                if (JdbcPersistable.class.isAssignableFrom(entityClass) && method.getName().equals(PERSISTABLE_IS_NEW_METHOD)) {
                    continue;
                }
                methodsMap.put(
                        SQLJavaNamingUtils.geColumnNameFromAttributeName(propertyDescriptor.getDisplayName()),
                        propertyDescriptor.getReadMethod());
            }
        }
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }
}
 
Example 14
Project: openjdk-jdk10   File: TestIntrospector.java   View source code 6 votes vote down vote up
private static void test(StringBuilder sb) throws IntrospectionException {
    long time = 0L;
    if (sb != null) {
        sb.append("Time\t#Props\t#Events\t#Methods\tClass\n");
        sb.append("----------------------------------------");
        time = -System.currentTimeMillis();
    }
    for (Class type : TYPES) {
        test(sb, type);
    }
    if (sb != null) {
        time += System.currentTimeMillis();
        sb.append("\nTime: ").append(time).append(" ms\n");
        System.out.println(sb);
        sb.setLength(0);
    }
}
 
Example 15
Project: bskyblock   File: FlatFileDatabaseHandler.java   View source code 6 votes vote down vote up
@Override
public void deleteObject(T instance) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, IntrospectionException {
    // The file name of the Yaml file.
    PropertyDescriptor propertyDescriptor = new PropertyDescriptor("uniqueId", type);
    Method method = propertyDescriptor.getReadMethod();
    String fileName = (String) method.invoke(instance);
    if (!fileName.endsWith(".yml")) {
        fileName = fileName + ".yml";
    }
    File dataFolder = new File(plugin.getDataFolder(), DATABASE_FOLDER_NAME);
    File tableFolder = new File(dataFolder, type.getSimpleName());
    if (tableFolder.exists()) {
        File file = new File(tableFolder, fileName);
        file.delete();
    }
}
 
Example 16
Project: openjdk-jdk10   File: TestIntrospector.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws IntrospectionException {
    StringBuilder sb = null;
    if (args.length > 0) {
        if (args[0].equals("show")) {
            sb = new StringBuilder(65536);
        }
    }
    Introspector.flushCaches();
    int count = (sb != null) ? 10 : 100;
    long time = -System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
        test(sb);
        test(sb);
        Introspector.flushCaches();
    }
    time += System.currentTimeMillis();
    System.out.println("Time (average): " + time / count);
}
 
Example 17
Project: jdk8u-jdk   File: Test4634390.java   View source code 6 votes vote down vote up
private static PropertyDescriptor create(PropertyDescriptor pd) {
    try {
        if (pd instanceof IndexedPropertyDescriptor) {
            IndexedPropertyDescriptor ipd = (IndexedPropertyDescriptor) pd;
            return new IndexedPropertyDescriptor(
                    ipd.getName(),
                    ipd.getReadMethod(),
                    ipd.getWriteMethod(),
                    ipd.getIndexedReadMethod(),
                    ipd.getIndexedWriteMethod());
        } else {
            return new PropertyDescriptor(
                    pd.getName(),
                    pd.getReadMethod(),
                    pd.getWriteMethod());
        }
    }
    catch (IntrospectionException exception) {
        exception.printStackTrace();
        return null;
    }
}
 
Example 18
Project: OutsourcedProject   File: CommonTools.java   View source code 6 votes vote down vote up
/***
 * Map转Bean
 * @param tClass {@link Class<T>}
 * @param map {@link Map}
 * @param <T> {@link T}
 * @return {@link T}
 */
public static <T> T mapToBean(Class<T> tClass, Map<String, Object> map) throws IntrospectionException, IllegalAccessException, InstantiationException, InvocationTargetException {
    BeanInfo beanInfo = Introspector.getBeanInfo(tClass);
    T bean = tClass.newInstance();
    PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    if (propertyDescriptors != null && propertyDescriptors.length > 0) {
        String propertyName; // javaBean属性名
        Object propertyValue; // javaBean属性值
        for (PropertyDescriptor pd : propertyDescriptors) {
            propertyName = pd.getName();
            if (map.containsKey(propertyName)) {
                propertyValue = map.get(propertyName);
                pd.getWriteMethod().invoke(bean, propertyValue);
            }
        }
        return bean;
    }

    return null;
}
 
Example 19
Project: jdk8u-jdk   File: Test7192955.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws IntrospectionException {
    if (!BeanUtils.findPropertyDescriptor(MyBean.class, "test").isBound()) {
        throw new Error("a simple property is not bound");
    }
    if (!BeanUtils.findPropertyDescriptor(MyBean.class, "list").isBound()) {
        throw new Error("a generic property is not bound");
    }
    if (!BeanUtils.findPropertyDescriptor(MyBean.class, "readOnly").isBound()) {
        throw new Error("a read-only property is not bound");
    }
    PropertyDescriptor[] pds = Introspector.getBeanInfo(MyBean.class, BaseBean.class).getPropertyDescriptors();
    for (PropertyDescriptor pd : pds) {
        if (pd.getName().equals("test") && pd.isBound()) {
            throw new Error("a simple property is bound without superclass");
        }
    }
}
 
Example 20
Project: incubator-netbeans   File: HelpCtx.java   View source code 6 votes vote down vote up
/** Finds help context for a generic object. Right now checks
 * for HelpCtx.Provider and handles java.awt.Component in a
 * special way compatible with JavaHelp.
 * Also {@link BeanDescriptor}'s are checked for a string-valued attribute
 * <code>helpID</code>, as per the JavaHelp specification (but no help sets
 * will be loaded).
 *
 * @param instance to search help for
 * @return the help for the object or <code>HelpCtx.DEFAULT_HELP</code> if HelpCtx cannot be found
 *
 * @since 4.3
 */
public static HelpCtx findHelp(Object instance) {
    if (instance instanceof java.awt.Component) {
        return findHelp((java.awt.Component) instance);
    }

    if (instance instanceof HelpCtx.Provider) {
        return ((HelpCtx.Provider) instance).getHelpCtx();
    }

    try {
        BeanDescriptor d = Introspector.getBeanInfo(instance.getClass()).getBeanDescriptor();
        String v = (String) d.getValue("helpID"); // NOI18N

        if (v != null) {
            return new HelpCtx(v);
        }
    } catch (IntrospectionException e) {
        err.log(Level.FINE, "findHelp on {0}: {1}", new Object[]{instance, e});
    }

    return HelpCtx.DEFAULT_HELP;
}
 
Example 21
Project: incubator-netbeans   File: J2EEPropertyModifier.java   View source code 6 votes vote down vote up
/**
 * Creates <code>FlushModeProperty</code> for the given component.
 *
 * @param comp component representing entity manager.
 */
FlushModeProperty(RADComponent comp) throws IntrospectionException {
    super(comp, new FakePropertyDescriptor("flushModeType", Object.class) { // NOI18N
        @Override
        public java.lang.reflect.Method getWriteMethod() {
            java.lang.reflect.Method m = null;
            try {
                m = FlushModeProperty.class.getMethod("setFlushMode", Object.class); // NOI18N
            } catch (Exception ex) {
                Logger.getLogger(getClass().getName()).log(Level.INFO, ex.getMessage(), ex);
            }
            return m;
        }
    });
    setAccessType(DETACHED_READ | DETACHED_WRITE);
    setShortDescription(NbBundle.getMessage(FlushModeProperty.class, "HINT_FlushMode")); // NOI18N
}
 
Example 22
Project: j-excel   File: GenObjectFields.java   View source code 6 votes vote down vote up
public static List<SortableField> init(Class aClass)throws IntrospectionException{
    List<SortableField> sortableFields = new ArrayList<>();
    //获取所有的属性
    Field[] fields = aClass.getDeclaredFields();
    for (Field field:fields){
        //获取类属性的注解
        ExcelDesc excelDesc = field.getAnnotation(ExcelDesc.class);
        if (excelDesc != null && !excelDesc.ignoreField()){
            //根据类属性获取属性对应的get方法,用户通过反射机制获取元素的值
            PropertyDescriptor pd = new PropertyDescriptor(field.getName(),
                    aClass);
            Method method = pd.getReadMethod();
            SortableField sortableField = new SortableField(excelDesc, field, method);
            sortableFields.add(sortableField);
        }
    }
    //对获取到的属性进行排序
    Collections.sort(sortableFields, new Comparator<SortableField>() {
        public int compare(SortableField o1, SortableField o2) {
            return o1.getExcelDesc().order()-o2.getExcelDesc().order();
        }
    });
    return sortableFields;
}
 
Example 23
Project: parabuild-ci   File: H2BeanConverter.java   View source code 6 votes vote down vote up
/**
 * Cache the method if possible, using the classname and property name to
 * allow for similar named methods.
 * @param data The bean to introspect
 * @param property The property to get the accessor for
 * @return The getter method
 * @throws IntrospectionException
 */
protected Method findGetter(Object data, String property) throws IntrospectionException
{
    String key = data.getClass().getName() + ":" + property;

    Method method = (Method) methods.get(key);
    if (method == null)
    {
        PropertyDescriptor[] props = Introspector.getBeanInfo(data.getClass()).getPropertyDescriptors();
        for (int i = 0; i < props.length; i++)
        {
            if (props[i].getName().equalsIgnoreCase(property))
            {
                method = props[i].getReadMethod();
            }
        }

        methods.put(key, method);
    }

    return method;
}
 
Example 24
Project: convertigo-eclipse   File: ComponentInfoWizardPage.java   View source code 6 votes vote down vote up
@Override
public void setVisible(boolean visible) {
	// TODO Auto-generated method stub
	super.setVisible(visible);
	
	if (visible) {
		ComponentExplorerWizardPage objectExplorerWizardPage = (ComponentExplorerWizardPage) this.getPreviousPage(); 
		
		try {
			Object o = objectExplorerWizardPage.getCreatedBean();
			if (o instanceof AbstractCouchDbTransaction) {
				AbstractCouchDbTransaction dbo = (AbstractCouchDbTransaction) objectExplorerWizardPage.getCreatedBean();
				if (dbo != null && couchVariablesComposite != null){
					couchVariablesComposite.setPropertyDescriptor(dbo, CachedIntrospector.getBeanInfo(dbo).getPropertyDescriptors(), 
							(DatabaseObject) parentObject);
				}
			}
		} catch (IntrospectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
 
Example 25
Project: myfaces-trinidad   File: ModelUtils.java   View source code 6 votes vote down vote up
/**
 * Converts an instance into a MenuModel
 */
public static MenuModel toMenuModel(Object value)
{
  if (value instanceof MenuModel)
    return (MenuModel) value;
  else
  {
    try
    {
      return new ViewIdPropertyMenuModel(value, null);
    }
    catch (IntrospectionException e)
    {
      IllegalArgumentException re =
        new IllegalArgumentException(_LOG.getMessage(
          "CANNOT_CONVERT_INTO_MENUMODEL",value));
      re.initCause(e);
      throw re;
    }
  }
}
 
Example 26
Project: incubator-netbeans   File: PropertyPattern.java   View source code 6 votes vote down vote up
/** Creates new PropertyPattern one of the methods may be null.
 * @param patternAnalyser patternAnalyser which creates this Property.
 * @param getterMethod getterMethod of the property or <CODE>null</CODE>.
 * @param setterMethod setterMethod of the property or <CODE>null</CODE>.
 * @throws IntrospectionException If specified methods do not follow beans Property rules.
 */
public PropertyPattern( PatternAnalyser patternAnalyser,
                        ExecutableElement getterMethod, 
                        ExecutableElement setterMethod,
                        VariableElement estimatedField,
                        TypeMirror type,
                        String name)
throws IntrospectionException {

    super( patternAnalyser, Pattern.Kind.PROPERTY, name, TypeMirrorHandle.create(type) );

    this.getterMethod = getterMethod == null ? null : ElementHandle.create(getterMethod);
    this.setterMethod = setterMethod == null ? null : ElementHandle.create(setterMethod);
    this.estimatedField = estimatedField == null ? null : ElementHandle.create(estimatedField);
    this.typeName = typeAsString(type);
    
}
 
Example 27
Project: etomica   File: ObjectWrapper.java   View source code 6 votes vote down vote up
public ObjectWrapper(T wrapped, SimulationModel simModel, boolean doSerialize) {
    super(wrapped, simModel, doSerialize);
    List<Property> properties = new ArrayList<>();
    try {
        Arrays.stream(Introspector.getBeanInfo(wrappedClass).getPropertyDescriptors())
                .filter(propertyDescriptor -> !propertyDescriptor.getName().equalsIgnoreCase("class"))
                .filter(propertyDescriptor -> propertyDescriptorMethod(propertyDescriptor) != null)
                .filter(propertyDescriptor -> !hasAnnotation(propertyDescriptorMethod(propertyDescriptor), IgnoreProperty.class))
                .filter(propertyDescriptor -> !hasAnnotation(propertyDescriptorMethod(propertyDescriptor), JsonIgnore.class))
                .filter(propertyDescriptor -> !propertyDescriptor.getName().toLowerCase().endsWith("dimension"))
                .forEach(propertyDescriptor -> properties.add(makeProperty(wrapped, propertyDescriptor)));

        for (Property p : properties) {
            if (p.isValueProperty()) {
                valueProps.add(p);
            } else {
                childProps.add(p);
            }
        }
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }
}
 
Example 28
Project: openjdk-jdk10   File: Test7192955.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws IntrospectionException {
    if (!BeanUtils.findPropertyDescriptor(MyBean.class, "test").isBound()) {
        throw new Error("a simple property is not bound");
    }
    if (!BeanUtils.findPropertyDescriptor(MyBean.class, "list").isBound()) {
        throw new Error("a generic property is not bound");
    }
    if (!BeanUtils.findPropertyDescriptor(MyBean.class, "readOnly").isBound()) {
        throw new Error("a read-only property is not bound");
    }
    PropertyDescriptor[] pds = Introspector.getBeanInfo(MyBean.class, BaseBean.class).getPropertyDescriptors();
    for (PropertyDescriptor pd : pds) {
        if (pd.getName().equals("test") && pd.isBound()) {
            throw new Error("a simple property is bound without superclass");
        }
    }
}
 
Example 29
Project: Equella   File: CachedPropertyInfo.java   View source code 6 votes vote down vote up
private CachedPropertyInfo(Class<?> clazz) throws IntrospectionException
{
	Class<?> thisClass = clazz;
	while( thisClass != null )
	{
		for( Field field : thisClass.getDeclaredFields() )
		{
			final Class<?> type = field.getType();
			final String name = field.getName();
			final String capsField = Character.toUpperCase(name.charAt(0)) + name.substring(1);
			final Method readMethod = getMethodOrNot(thisClass, (type == Boolean.class || type == boolean.class
				? "is" : "get") + capsField);
			final Method writeMethod = getMethodOrNot(thisClass, "set" + capsField, type);

			final PropertyDescriptor pd = new PropertyDescriptor(name, readMethod, writeMethod);
			propertyMap.put(pd.getName(), pd);
		}
		thisClass = thisClass.getSuperclass();
	}
}
 
Example 30
Project: myfaces-trinidad   File: RowKeySetTreeImplTest.java   View source code 6 votes vote down vote up
public void testSize() throws IntrospectionException
{
  RowKeySet set = new TestPathSet();
  assertEquals("size", 0, set.size());
  _add(set, _2, _20, _0, _011);
  assertEquals("size", 4, set.size());

  set = new RowKeySetTreeImpl(true);
  TreeModel model = ChildPropertyTreeModelTest.createModel();
  set.setCollectionModel(model);
  assertEquals("addAll:size", 14, set.size());

  set.remove(_011);
  assertEquals("addAll:size", 13, set.size());

  model.setRowKey(_011);
  set.removeAll();
  assertEquals("addAll:size", 10, set.size());

}
 
Example 31
Project: myfaces-trinidad   File: JavaIntrospector.java   View source code 6 votes vote down vote up
BeanDescriptor __getTargetBeanDescriptor()
  throws IntrospectionException
{
  // Use explicit info, if available,
  if (_informant != null)
  {
    BeanDescriptor bd = _informant.getBeanDescriptor();

    if (bd != null)
    {
      return bd;
    }
  }

  // OK, fabricate a default BeanDescriptor.
  return (new BeanDescriptor(_beanClass));
}
 
Example 32
Project: jdk8u-jdk   File: Test4274639.java   View source code 5 votes vote down vote up
public PropertyDescriptor[] getPropertyDescriptors() {
    PropertyDescriptor[] pds = new PropertyDescriptor[2];
    try {
        pds[0] = new PropertyDescriptor(STRING_PROPERTY, TestBean.class);
        pds[0].setPropertyEditorClass(StringEditor.class);

        pds[1] = new PropertyDescriptor(INTEGER_PROPERTY, TestBean.class);
        pds[1].setPropertyEditorClass(IntegerEditor.class);

    }
    catch (IntrospectionException exception) {
        throw new Error("unexpected error", exception);
    }
    return pds;
}
 
Example 33
Project: openjdk-jdk10   File: Test4274639.java   View source code 5 votes vote down vote up
public PropertyDescriptor[] getPropertyDescriptors() {
    PropertyDescriptor[] pds = new PropertyDescriptor[2];
    try {
        pds[0] = new PropertyDescriptor(STRING_PROPERTY, TestBean.class);
        pds[0].setPropertyEditorClass(StringEditor.class);

        pds[1] = new PropertyDescriptor(INTEGER_PROPERTY, TestBean.class);
        pds[1].setPropertyEditorClass(IntegerEditor.class);

    }
    catch (IntrospectionException exception) {
        throw new Error("unexpected error", exception);
    }
    return pds;
}
 
Example 34
Project: azeroth   File: BeanCopyUtils.java   View source code 5 votes vote down vote up
private static List<String> getClassFields(Class<?> clazz) throws IntrospectionException {
    String canonicalName = clazz.getCanonicalName();

    if (!fieldCache.containsKey(canonicalName)) {
        doCacheClass(clazz, canonicalName);
    }
    return fieldCache.get(canonicalName);
}
 
Example 35
Project: GitHub   File: ExcludedFromEqualsAndHashCodeIT.java   View source code 5 votes vote down vote up
@Test
public void hashCodeTest() throws IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {

    Object instance = clazz.newInstance();

    setProperty(instance, "excludedByProperty", "one");
    setProperty(instance, "excludedByArray", "two");
    setProperty(instance, "notExcluded", "three");
    setProperty(instance, "notExcludedByProperty", "four");

    int hashCodeBefore;
    int hashCodeAfter;

    hashCodeBefore = instance.hashCode();
    setProperty(instance, "excludedByProperty", "five");
    hashCodeAfter = instance.hashCode();

    assertThat(hashCodeBefore, is(equalTo(hashCodeAfter)));

    hashCodeBefore = hashCodeAfter;
    setProperty(instance, "excludedByArray", "six");
    hashCodeAfter = instance.hashCode();

    assertThat(hashCodeBefore, is(equalTo(hashCodeAfter)));

    hashCodeBefore = hashCodeAfter;
    setProperty(instance, "notExcluded", "seven");
    hashCodeAfter = instance.hashCode();

    assertThat(hashCodeBefore, is(not(equalTo(hashCodeAfter))));

    hashCodeBefore = hashCodeAfter;
    setProperty(instance, "notExcludedByProperty", "eight");
    hashCodeAfter = instance.hashCode();

    assertThat(hashCodeBefore, is(not(equalTo(hashCodeAfter))));
}
 
Example 36
Project: incubator-netbeans   File: J2EEPropertyModifier.java   View source code 5 votes vote down vote up
/**
 * Creates <code>QueryProperty</code> for the given component.
 *
 * @param comp component representing query result list.
 */
QueryProperty(RADComponent comp) throws IntrospectionException {
    super(comp, new FakePropertyDescriptor("query", String.class)); // NOI18N
    setAccessType(DETACHED_READ | DETACHED_WRITE);
    try {
        setValue(""); // NOI18N "default value"
    } catch (Exception ex) {
        Logger.getLogger(getClass().getName()).log(Level.INFO, ex.getMessage(), ex);
    }
    setShortDescription(NbBundle.getMessage(QueryProperty.class, "HINT_QueryProperty")); // NOI18N
}
 
Example 37
Project: openjdk-jdk10   File: ComponentBeanInfo.java   View source code 5 votes vote down vote up
public PropertyDescriptor[] getPropertyDescriptors() {
    try {
        return new PropertyDescriptor[] {
                new PropertyDescriptor("name", Component.class)
        };
    } catch (IntrospectionException exception) {
        throw new Error("unexpected exception", exception);
    }
}
 
Example 38
Project: neoscada   File: AbstractObjectExporter.java   View source code 5 votes vote down vote up
protected void updateItemsFromTarget ()
{
    final Set<String> updatedAttributes = new HashSet<String> ();
    try
    {
        final Object target = getTarget ();
        if ( target != null )
        {
            final BeanInfo bi = Introspector.getBeanInfo ( target.getClass () );
            for ( final PropertyDescriptor pd : bi.getPropertyDescriptors () )
            {
                updatedAttributes.add ( pd.getName () );
                initAttribute ( pd );
            }
        }
    }
    catch ( final IntrospectionException e )
    {
        logger.info ( "Failed to read item", e );
    }

    for ( final String key : this.items.keySet () )
    {
        if ( !updatedAttributes.contains ( key ) )
        {
            updateAttribute ( key, null, null, getAdditionalAttributes () );
        }
    }
}
 
Example 39
Project: fluvius   File: MutableState.java   View source code 5 votes vote down vote up
private static PropertyDescriptor[] safeGetPropertyDescriptors(Object object)  {
  try {
    return Introspector.getBeanInfo(object.getClass()).getPropertyDescriptors();
  } catch (IntrospectionException e) {
    throw new RuntimeException(e);
  }
}
 
Example 40
Project: openjdk-jdk10   File: Test7193977.java   View source code 5 votes vote down vote up
public AbstractBeanInfo() throws IntrospectionException {
    super(Abstract.class);
    for (PropertyDescriptor pd : getPropertyDescriptors()) {
        if (names.contains(pd.getName())) {
            pd.setValue("transient", Boolean.TRUE);
        }
    }
}