Java Code Examples for java.beans.PropertyDescriptor

The following are top voted examples for showing how to use java.beans.PropertyDescriptor. 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: lams   File: AbstractAutowireCapableBeanFactory.java   View source code 6 votes vote down vote up
/**
 * Extract a filtered set of PropertyDescriptors from the given BeanWrapper,
 * excluding ignored dependency types or properties defined on ignored dependency interfaces.
 * @param bw the BeanWrapper the bean was created with
 * @param cache whether to cache filtered PropertyDescriptors for the given bean Class
 * @return the filtered PropertyDescriptors
 * @see #isExcludedFromDependencyCheck
 * @see #filterPropertyDescriptorsForDependencyCheck(org.springframework.beans.BeanWrapper)
 */
protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw, boolean cache) {
	PropertyDescriptor[] filtered = this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass());
	if (filtered == null) {
		if (cache) {
			synchronized (this.filteredPropertyDescriptorsCache) {
				filtered = this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass());
				if (filtered == null) {
					filtered = filterPropertyDescriptorsForDependencyCheck(bw);
					this.filteredPropertyDescriptorsCache.put(bw.getWrappedClass(), filtered);
				}
			}
		}
		else {
			filtered = filterPropertyDescriptorsForDependencyCheck(bw);
		}
	}
	return filtered;
}
 
Example 2
Project: reflection-util   File: PropertyUtils.java   View source code 6 votes vote down vote up
public static void writeDirectly(Object destination, PropertyDescriptor propertyDescriptor, Object value) {
	try {
		Field field = findField(destination, propertyDescriptor);
		boolean accessible = field.isAccessible();
		try {
			if (!accessible) {
				field.setAccessible(true);
			}
			field.set(destination, value);
		} finally {
			if (!accessible) {
				field.setAccessible(false);
			}
		}
	} catch (NoSuchFieldException | IllegalAccessException e) {
		throw new ReflectionRuntimeException("Failed to write " + getQualifiedPropertyName(destination, propertyDescriptor), e);
	}
}
 
Example 3
Project: zooadmin   File: BeanMapUtil.java   View source code 6 votes vote down vote up
public static Object convertMap2Bean(Class type, Map map)
		throws IntrospectionException, IllegalAccessException,
		InstantiationException, InvocationTargetException {
	BeanInfo beanInfo = Introspector.getBeanInfo(type);
	Object obj = type.newInstance();
	PropertyDescriptor[] propertyDescriptors = beanInfo
			.getPropertyDescriptors();
	for (PropertyDescriptor pro : propertyDescriptors) {
		String propertyName = pro.getName();
		if (pro.getPropertyType().getName().equals("java.lang.Class")) {
			continue;
		}
		if (map.containsKey(propertyName)) {
			Object value = map.get(propertyName);
			Method setter = pro.getWriteMethod();
			setter.invoke(obj, value);
		}
	}
	return obj;
}
 
Example 4
Project: xmanager   File: BeanUtils.java   View source code 6 votes vote down vote up
/**
 * 获取Bean的属性
 * @param bean bean
 * @param propertyName 属性名
 * @return 属性值
 */
public static Object getProperty(Object bean, String propertyName) {
	PropertyDescriptor pd = getPropertyDescriptor(bean.getClass(), propertyName);
	if (pd == null) {
		throw new RuntimeException("Could not read property '" + propertyName + "' from bean PropertyDescriptor is null");
	}
	Method readMethod = pd.getReadMethod();
	if (readMethod == null) {
		throw new RuntimeException("Could not read property '" + propertyName + "' from bean readMethod is null");
	}
	if (!readMethod.isAccessible()) {
		readMethod.setAccessible(true);
	}
	try {
		return readMethod.invoke(bean);
	} catch (Throwable ex) {
		throw new RuntimeException("Could not read property '" + propertyName + "' from bean", ex);
	}
}
 
Example 5
Project: convertigo-engine   File: UIStyleBeanInfo.java   View source code 6 votes vote down vote up
public UIStyleBeanInfo() {
	try {
		beanClass = UIStyle.class;
		additionalBeanClass = com.twinsoft.convertigo.beans.mobile.components.UIComponent.class;

		iconNameC16 = "/com/twinsoft/convertigo/beans/mobile/components/images/uistyle_color_16x16.png";
		iconNameC32 = "/com/twinsoft/convertigo/beans/mobile/components/images/uistyle_color_32x32.png";

		resourceBundle = getResourceBundle("res/UIStyle");

		displayName = resourceBundle.getString("display_name");
		shortDescription = resourceBundle.getString("short_description");
		
		properties = new PropertyDescriptor[1];
		
		properties[0] = new PropertyDescriptor("styleContent", beanClass, "getStyleContent", "setStyleContent");
		properties[0].setDisplayName(getExternalizedString("property.styleContent.display_name"));
		properties[0].setShortDescription(getExternalizedString("property.styleContent.short_description"));
		properties[0].setHidden(true);
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 6
Project: ureport   File: DatasourceServletAction.java   View source code 6 votes vote down vote up
public void buildClass(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String clazz=req.getParameter("clazz");
	List<Field> result=new ArrayList<Field>();
	try{
		Class<?> targetClass=Class.forName(clazz);
		PropertyDescriptor[] propertyDescriptors=PropertyUtils.getPropertyDescriptors(targetClass);
		for(PropertyDescriptor pd:propertyDescriptors){
			String name=pd.getName();
			if("class".equals(name)){
				continue;
			}
			result.add(new Field(name));
		}
		writeObjectToJson(resp, result);
	}catch(Exception ex){
		throw new ReportDesignException(ex);
	}
}
 
Example 7
Project: convertigo-engine   File: SerialStepBeanInfo.java   View source code 6 votes vote down vote up
public SerialStepBeanInfo() {
	try {
		beanClass = SerialStep.class;
		additionalBeanClass = com.twinsoft.convertigo.beans.steps.BranchStep.class;

		iconNameC16 = "/com/twinsoft/convertigo/beans/steps/images/serial_16x16.png";
		iconNameC32 = "/com/twinsoft/convertigo/beans/steps/images/serial_32x32.png";
		
		resourceBundle = getResourceBundle("res/SerialStep");
		
		displayName = resourceBundle.getString("display_name");
		shortDescription = resourceBundle.getString("short_description");
		
		PropertyDescriptor property = getPropertyDescriptor("maxNumberOfThreads");
           property.setHidden(true) ;
		
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 8
Project: incubator-netbeans   File: DefaultPropertyModelTest.java   View source code 6 votes vote down vote up
public void testUsageOfExplicitPropertyDescriptor() throws Exception {
    PropertyDescriptor pd = new PropertyDescriptor(
            "myProp", this.getClass(),
            "getterUsageOfExplicitPropertyDescriptor",
            "setterUsageOfExplicitPropertyDescriptor"
            );
    
    DefaultPropertyModel model = new DefaultPropertyModel(this, pd);
    
    assertEquals("Getter returns this", model.getValue(), this);
    
    String msgToThrow = "msgToThrow";
    try {
        model.setValue(msgToThrow);
        fail("Setter should throw an exception");
    } catch (InvocationTargetException ex) {
        // when an exception occurs it should throw InvocationTargetException
        assertEquals("The right message", msgToThrow, ex.getTargetException().getMessage());
    }
}
 
Example 9
Project: convertigo-engine   File: XMLHttpHeadersBeanInfo.java   View source code 6 votes vote down vote up
public XMLHttpHeadersBeanInfo() {
	try {
		beanClass = XMLHttpHeaders.class;
		additionalBeanClass = com.twinsoft.convertigo.beans.extractionrules.HtmlExtractionRule.class;

	    iconNameC16 = "/com/twinsoft/convertigo/beans/common/images/xmlhttpheaders_color_16x16.png";
	    iconNameC32 = "/com/twinsoft/convertigo/beans/common/images/xmlhttpheaders_color_32x32.png";

		resourceBundle = getResourceBundle("res/XMLHttpHeaders");

		displayName = getExternalizedString("display_name");
		shortDescription = getExternalizedString("short_description");
		
		PropertyDescriptor property = getPropertyDescriptor("xpath");
		property.setHidden(true);
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 10
Project: FCat   File: ObjectUtil.java   View source code 6 votes vote down vote up
/**
 * 对象到map
 * @param obj
 * @return
 */
public static Map<String, Object> objectToMap(Object obj) { 
	Map<String, Object> map = new HashMap<String, Object>();
    if(obj == null) {
        return map;      
    }
    try{
     BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());    
     PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();    
     for (PropertyDescriptor property : propertyDescriptors) {    
         String key = property.getName();    
         if (key.compareToIgnoreCase("class") == 0) {   
             continue;  
         }  
         Method getter = property.getReadMethod();  
         Object value = getter!=null ? getter.invoke(obj) : null;  
         map.put(key, value);  
     }    
    }catch(Exception e) {
    	logger.error(e.getMessage());
    }
    return map;
}
 
Example 11
Project: Dude   File: Enums.java   View source code 6 votes vote down vote up
/**
 * 获取枚举中指定属性的值
 *
 * @param enumCls 枚举类型
 * @param prop    Bean属性名
 * @return (枚举值, 指定属性的值)
 */
public static Map<Enum<?>, Object> getEnumAndValue(Class<?> enumCls, String prop) {

    Object[] enumValues = enumCls.getEnumConstants();
    if (isEmpty(enumValues)) {
        return newLinkedHashMap();
    }
    Map<Enum<?>, Object> result = newLinkedHashMapWithExpectedSize(enumValues.length * 2);
    try {
        for (Object enumValue : enumValues) {
            PropertyDescriptor pd = getPropertyDescriptor(enumValue, prop);
            if (pd == null || pd.getReadMethod() == null) {
                continue;
            }
            result.put((Enum<?>) enumValue, pd.getReadMethod().invoke(enumValue));
        }
    } catch (Exception e) {
        // ignore
    }
    return result;
}
 
Example 12
Project: lams   File: MetadataMBeanInfoAssembler.java   View source code 6 votes vote down vote up
/**
 * Retrieves the description for the supplied {@code Method} from the
 * metadata. Uses the method name is no description is present in the metadata.
 */
@Override
protected String getOperationDescription(Method method, String beanKey) {
	PropertyDescriptor pd = BeanUtils.findPropertyForMethod(method);
	if (pd != null) {
		ManagedAttribute ma = this.attributeSource.getManagedAttribute(method);
		if (ma != null && StringUtils.hasText(ma.getDescription())) {
			return ma.getDescription();
		}
		ManagedMetric metric = this.attributeSource.getManagedMetric(method);
		if (metric != null && StringUtils.hasText(metric.getDescription())) {
			return metric.getDescription();
		}
		return method.getName();
	}
	else {
		ManagedOperation mo = this.attributeSource.getManagedOperation(method);
		if (mo != null && StringUtils.hasText(mo.getDescription())) {
			return mo.getDescription();
		}
		return method.getName();
	}
}
 
Example 13
Project: spring-rest-commons-options   File: ReflectionUtils.java   View source code 6 votes vote down vote up
private static void collectParameters(Collection<Parameters> parameters, Parameter parameter, Annotation a,
		boolean isPathVariable) {
	if (a != null) {
		String typeStr = parameter.getType().getSimpleName();
		Type type = parameter.getParameterizedType();
		if (type instanceof ParameterizedType) {
			typeStr = ((Class<?>) ((ParameterizedType) type).getActualTypeArguments()[0]).getSimpleName();
		}
		parameters.add(new Parameters((boolean) AnnotationUtils.getValue(a, "required"),
				(String) (AnnotationUtils.getValue(a).equals("") ? parameter.getName()
						: AnnotationUtils.getValue(a)),
				typeStr));
	} else if (Pageable.class.isAssignableFrom(parameter.getType()) && !isPathVariable) {
		try {
			for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(parameter.getType())
					.getPropertyDescriptors()) {
				parameters.add(new Parameters(false, propertyDescriptor.getName(),
						propertyDescriptor.getPropertyType().getSimpleName()));
			}
		} catch (IntrospectionException e) {
			LOGGER.error("Problemas al obtener el Pageable: {}", parameter, e);
		}
	}
}
 
Example 14
Project: convertigo-engine   File: InjectorBeanInfo.java   View source code 6 votes vote down vote up
public InjectorBeanInfo() {
	try {
		beanClass = Injector.class;
		additionalBeanClass = com.twinsoft.convertigo.beans.extractionrules.siteclipper.BaseRule.class;

		resourceBundle = getResourceBundle("res/Injector");

		properties = new PropertyDescriptor[2];

		properties[0] = new PropertyDescriptor("location", beanClass, "getLocation", "setLocation");
        properties[0].setDisplayName(getExternalizedString("property.location.display_name"));
        properties[0].setShortDescription(getExternalizedString("property.location.short_description"));
    	properties[0].setPropertyEditorClass(HtmlLocation.class);
    	
		properties[1] = new PropertyDescriptor("customRegexp", beanClass, "getCustomRegexp", "setCustomRegexp");
        properties[1].setDisplayName(getExternalizedString("property.customRegexp.display_name"));
        properties[1].setShortDescription(getExternalizedString("property.customRegexp.short_description"));
    	properties[1].setExpert(true);
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 15
Project: spring-rest-commons-options   File: ModelStrategy.java   View source code 6 votes vote down vote up
private List<DetailField> createDetail(Class<?> c, boolean isRequest) {
	List<DetailField> detailFields = new ArrayList<>();
	ReflectionUtils.getGenericClass(c).ifPresent(clazz -> {
		try {
			for (PropertyDescriptor propertyDescriptor : Introspector.getBeanInfo(clazz, Object.class)
					.getPropertyDescriptors()) {
				if (!propertyDescriptor.getReadMethod().getDeclaringClass().equals(Object.class)) {
					Optional<Field> field = getField(clazz, propertyDescriptor);
					if (checkIfAddField(field, propertyDescriptor, isRequest)) {
						Optional<DetailField> detail = super.createDetail(propertyDescriptor, field, isRequest);
						detail.ifPresent(detailFields::add);
					}
				}
			}
		} catch (Exception e) {
			LOGGER.error("Error al inspeccionar la clase {}", clazz, e);
		}
	});
	return detailFields;
}
 
Example 16
Project: convertigo-engine   File: CriteriaWithRegexBeanInfo.java   View source code 6 votes vote down vote up
public CriteriaWithRegexBeanInfo() {
	try {
		beanClass = CriteriaWithRegex.class;
		additionalBeanClass = com.twinsoft.convertigo.beans.criteria.siteclipper.BaseCriteria.class;

		resourceBundle = getResourceBundle("res/CriteriaWithRegex");

		properties = new PropertyDescriptor[1];
		
		properties[0] = new PropertyDescriptor("regexp", beanClass, "getRegexp", "setRegexp");
        properties[0].setDisplayName(getExternalizedString("property.regexp.display_name"));
        properties[0].setShortDescription(getExternalizedString("property.regexp.short_description"));	
        			
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 17
Project: lams   File: ExtendedBeanInfo.java   View source code 6 votes vote down vote up
public static void copyNonMethodProperties(PropertyDescriptor source, PropertyDescriptor target)
		throws IntrospectionException {

	target.setExpert(source.isExpert());
	target.setHidden(source.isHidden());
	target.setPreferred(source.isPreferred());
	target.setName(source.getName());
	target.setShortDescription(source.getShortDescription());
	target.setDisplayName(source.getDisplayName());

	// Copy all attributes (emulating behavior of private FeatureDescriptor#addTable)
	Enumeration<String> keys = source.attributeNames();
	while (keys.hasMoreElements()) {
		String key = keys.nextElement();
		target.setValue(key, source.getValue(key));
	}

	// See java.beans.PropertyDescriptor#PropertyDescriptor(PropertyDescriptor)
	target.setPropertyEditorClass(source.getPropertyEditorClass());
	target.setBound(source.isBound());
	target.setConstrained(source.isConstrained());
}
 
Example 18
Project: convertigo-engine   File: UIPageEventBeanInfo.java   View source code 6 votes vote down vote up
public UIPageEventBeanInfo() {
	try {
		beanClass = UIPageEvent.class;
		additionalBeanClass = com.twinsoft.convertigo.beans.mobile.components.UIComponent.class;

		iconNameC16 = "/com/twinsoft/convertigo/beans/mobile/components/images/uipageevent_color_16x16.png";
		iconNameC32 = "/com/twinsoft/convertigo/beans/mobile/components/images/uipageevent_color_32x32.png";

		resourceBundle = getResourceBundle("res/UIPageEvent");

		displayName = resourceBundle.getString("display_name");
		shortDescription = resourceBundle.getString("short_description");
		
		properties = new PropertyDescriptor[1];
		
		properties[0] = new PropertyDescriptor("viewEvent", beanClass, "getViewEvent", "setViewEvent");
		properties[0].setDisplayName(getExternalizedString("property.viewEvent.display_name"));
		properties[0].setShortDescription(getExternalizedString("property.viewEvent.short_description"));
		properties[0].setPropertyEditorClass(getEditorClass("StringComboBoxPropertyDescriptor"));
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 19
Project: convertigo-engine   File: InputHtmlSetFileStatementBeanInfo.java   View source code 6 votes vote down vote up
public InputHtmlSetFileStatementBeanInfo() {
	try {
		beanClass = InputHtmlSetFileStatement.class;
		additionalBeanClass = com.twinsoft.convertigo.beans.statements.AbstractEventStatement.class;

		iconNameC16 = "/com/twinsoft/convertigo/beans/statements/images/inputhtmlsetfile_16x16.png";
		iconNameC32 = "/com/twinsoft/convertigo/beans/statements/images/inputhtmlsetfile_32x32.png";
		
		resourceBundle = getResourceBundle("res/InputHtmlSetFileStatement");
		
		displayName = resourceBundle.getString("display_name");
		shortDescription = resourceBundle.getString("short_description");

		properties = new PropertyDescriptor[1];

		properties[0] = new PropertyDescriptor("filename", beanClass, "getFilename", "setFilename");
		properties[0].setDisplayName(getExternalizedString("property.filename.display_name"));
		properties[0].setShortDescription(getExternalizedString("property.filename.short_description"));
           properties[0].setValue("scriptable", Boolean.TRUE);
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 20
Project: aws-sdk-java-v2   File: DefaultClientBuilderTest.java   View source code 6 votes vote down vote up
@Test
public void clientBuilderFieldsHaveBeanEquivalents() throws Exception {
    ClientBuilder<TestClientBuilder, TestClient> builder = testClientBuilder();

    BeanInfo beanInfo = Introspector.getBeanInfo(builder.getClass());
    Method[] clientBuilderMethods = ClientBuilder.class.getDeclaredMethods();

    Arrays.stream(clientBuilderMethods).filter(m -> !m.isSynthetic()).forEach(builderMethod -> {
        String propertyName = builderMethod.getName();

        Optional<PropertyDescriptor> propertyForMethod =
                Arrays.stream(beanInfo.getPropertyDescriptors())
                      .filter(property -> property.getName().equals(propertyName))
                      .findFirst();

        assertThat(propertyForMethod).as(propertyName + " property").hasValueSatisfying(property -> {
            assertThat(property.getReadMethod()).as(propertyName + " getter").isNull();
            assertThat(property.getWriteMethod()).as(propertyName + " setter").isNotNull();
        });
    });

}
 
Example 21
Project: convertigo-engine   File: AbstractComplexeEventStatementBeanInfo.java   View source code 6 votes vote down vote up
public AbstractComplexeEventStatementBeanInfo() {
	try {
		beanClass = AbstractComplexeEventStatement.class;
		additionalBeanClass = com.twinsoft.convertigo.beans.statements.AbstractEventStatement.class;

		resourceBundle = getResourceBundle("res/AbstractComplexeEventStatement");
		
		properties = new PropertyDescriptor[1];

           properties[0] = new PropertyDescriptor("uiEvent", beanClass, "getUiEvent", "setUiEvent");
           properties[0].setDisplayName(getExternalizedString("property.uievent.display_name"));
           properties[0].setShortDescription(getExternalizedString("property.uievent.short_description"));    
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 22
Project: iBase4J-Common   File: InstanceUtil.java   View source code 6 votes vote down vote up
public static <T> T transMap2Bean(Map<String, Object> map, Class<T> clazz) {
    T bean = null;
    try {
        bean = clazz.newInstance();
        BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (map.containsKey(key)) {
                Object value = map.get(key);
                // 得到property对应的setter方法
                Method setter = property.getWriteMethod();
                setter.invoke(bean, TypeParseUtil.convert(value, property.getPropertyType(), null));
            }
        }
    } catch (Exception e) {
        logger.error("transMap2Bean Error ", e);
    }
    return bean;
}
 
Example 23
Project: neoscada   File: AbstractObjectExporter.java   View source code 6 votes vote down vote up
/**
 * create data items from the properties
 */
protected void createDataItems ( final Class<?> targetClazz )
{
    try
    {
        final BeanInfo bi = Introspector.getBeanInfo ( targetClazz );
        for ( final PropertyDescriptor pd : bi.getPropertyDescriptors () )
        {
            final DataItem item = createItem ( pd, targetClazz );
            this.items.put ( pd.getName (), item );

            final Map<String, Variant> itemAttributes = new HashMap<String, Variant> ();
            fillAttributes ( pd, itemAttributes );
            this.attributes.put ( pd.getName (), itemAttributes );

            initAttribute ( pd );
        }
    }
    catch ( final IntrospectionException e )
    {
        logger.info ( "Failed to read initial item", e );
    }
}
 
Example 24
Project: jaffa-framework   File: BeanMoulder.java   View source code 6 votes vote down vote up
private static void setProperty (PropertyDescriptor pd, Object value, Object source)
throws IllegalAccessException, InvocationTargetException, MouldException {
    if(pd!=null && pd.getWriteMethod()!=null) {
        Method m = pd.getWriteMethod();
        if(!m.isAccessible()) m.setAccessible(true);
        Class tClass = m.getParameterTypes()[0];
        if(value==null || tClass.isAssignableFrom(value.getClass())) {
            m.invoke(source, new Object[] {value});
            log.debug("Set property '" + pd.getName() + "=" + value + "' on object '" + source.getClass().getName() + "'");
        } else if(DataTypeMapper.instance().isMappable(value.getClass(),tClass)) {
            // See if there is a datatype mapper for these classes
            value = DataTypeMapper.instance().map(value, tClass);
            m.invoke(source, new Object[] {value});
            log.debug("Translate+Set property '" + pd.getName() + "=" + value + "' on object '" + source.getClass().getName() + "'");
        } else {
            // Data type mismatch
            throw new MouldException(MouldException.DATATYPE_MISMATCH, source.getClass().getName() + "." + m.getName(), tClass.getName(), value.getClass().getName());
        }
    } else {
        MouldException me = new MouldException(MouldException.NO_SETTER, null,
                            pd==null?"???":pd.getName(), source.getClass().getName());
        log.error(me.getLocalizedMessage());
        throw me;
    }
}
 
Example 25
Project: convertigo-engine   File: JavaScriptBeanInfo.java   View source code 6 votes vote down vote up
public JavaScriptBeanInfo() {
	try {
		beanClass = JavaScript.class;
		additionalBeanClass = BaseRule.class;
		
		resourceBundle = getResourceBundle("res/JavaScript");

		properties = new PropertyDescriptor[1];
		
		properties[0] = new PropertyDescriptor("expression", beanClass, "getExpression", "setExpression" );
		properties[0].setDisplayName(getExternalizedString("property.expression.display_name") );
		properties[0].setShortDescription(getExternalizedString("property.expression.short_description") );
           properties[0].setPropertyEditorClass(getEditorClass("JavascriptTextEditor"));
           properties[0].setValue("scriptable", Boolean.TRUE);
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 26
Project: lams   File: MetadataMBeanInfoAssembler.java   View source code 6 votes vote down vote up
/**
 * Creates a description for the attribute corresponding to this property
 * descriptor. Attempts to create the description using metadata from either
 * the getter or setter attributes, otherwise uses the property name.
 */
@Override
protected String getAttributeDescription(PropertyDescriptor propertyDescriptor, String beanKey) {
	Method readMethod = propertyDescriptor.getReadMethod();
	Method writeMethod = propertyDescriptor.getWriteMethod();

	ManagedAttribute getter =
			(readMethod != null ? this.attributeSource.getManagedAttribute(readMethod) : null);
	ManagedAttribute setter =
			(writeMethod != null ? this.attributeSource.getManagedAttribute(writeMethod) : null);

	if (getter != null && StringUtils.hasText(getter.getDescription())) {
		return getter.getDescription();
	}
	else if (setter != null && StringUtils.hasText(setter.getDescription())) {
		return setter.getDescription();
	}

	ManagedMetric metric = (readMethod != null ? this.attributeSource.getManagedMetric(readMethod) : null);
	if (metric != null && StringUtils.hasText(metric.getDescription())) {
		return metric.getDescription();
	}

	return propertyDescriptor.getDisplayName();
}
 
Example 27
Project: lams   File: RequiredAnnotationBeanPostProcessor.java   View source code 6 votes vote down vote up
@Override
public PropertyValues postProcessPropertyValues(
		PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName)
		throws BeansException {

	if (!this.validatedBeanNames.contains(beanName)) {
		if (!shouldSkip(this.beanFactory, beanName)) {
			List<String> invalidProperties = new ArrayList<String>();
			for (PropertyDescriptor pd : pds) {
				if (isRequiredProperty(pd) && !pvs.contains(pd.getName())) {
					invalidProperties.add(pd.getName());
				}
			}
			if (!invalidProperties.isEmpty()) {
				throw new BeanInitializationException(buildExceptionMessage(invalidProperties, beanName));
			}
		}
		this.validatedBeanNames.add(beanName);
	}
	return pvs;
}
 
Example 28
Project: mycat-src-1.6.1-RELEASE   File: ParameterMapping.java   View source code 5 votes vote down vote up
/**
 * 用于导出clazz这个JavaBean的所有属性的PropertyDescriptor
 * @param clazz
 * @return
 */
private static PropertyDescriptor[] getDescriptors(Class<?> clazz) {
    //PropertyDescriptor类表示JavaBean类通过存储器导出一个属性
    PropertyDescriptor[] pds;
    List<PropertyDescriptor> list;
    PropertyDescriptor[] pds2 = descriptors.get(clazz);
    //该clazz是否第一次加载
    if (null == pds2) {
        try {
            BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
            pds = beanInfo.getPropertyDescriptors();
            list = new ArrayList<PropertyDescriptor>();
            //加载每一个类型不为空的property
            for (int i = 0; i < pds.length; i++) {
                if (null != pds[i].getPropertyType()) {
                    list.add(pds[i]);
                }
            }
            pds2 = new PropertyDescriptor[list.size()];
            list.toArray(pds2);
        } catch (IntrospectionException ie) {
            LOGGER.error("ParameterMappingError", ie);
            pds2 = new PropertyDescriptor[0];
        }
    }
    descriptors.put(clazz, pds2);
    return (pds2);
}
 
Example 29
Project: convertigo-engine   File: UrlMappingResponseBeanInfo.java   View source code 5 votes vote down vote up
public UrlMappingResponseBeanInfo() {
	try {
		beanClass = UrlMappingResponse.class;
		additionalBeanClass = com.twinsoft.convertigo.beans.core.DatabaseObject.class;

		iconNameC16 = "/com/twinsoft/convertigo/beans/core/images/urlmappingresponse_color_16x16.png";
		iconNameC32 = "/com/twinsoft/convertigo/beans/core/images/urlmappingresponse_color_32x32.png";

		resourceBundle = getResourceBundle("res/UrlMappingResponse");

		displayName = resourceBundle.getString("display_name");
		shortDescription = resourceBundle.getString("short_description");
		
		properties = new PropertyDescriptor[0];
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 30
Project: tk-mybatis   File: FieldHelper.java   View source code 5 votes vote down vote up
/**
 * 通过方法获取属性
 *
 * @param entityClass
 * @return
 */
public List<EntityField> getProperties(Class<?> entityClass) {
    Map<String, Class<?>> genericMap = _getGenericTypeMap(entityClass);
    List<EntityField> entityFields = new ArrayList<EntityField>();
    BeanInfo beanInfo;
    try {
        beanInfo = Introspector.getBeanInfo(entityClass);
    } catch (IntrospectionException e) {
        throw new MapperException(e);
    }
    PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
    for (PropertyDescriptor desc : descriptors) {
        if (desc != null && !"class".equals(desc.getName())) {
            EntityField entityField = new EntityField(null, desc);
            if (desc.getReadMethod() != null
                    && desc.getReadMethod().getGenericReturnType() != null
                    && desc.getReadMethod().getGenericReturnType() instanceof TypeVariable) {
                entityField.setJavaType(genericMap.get(((TypeVariable) desc.getReadMethod().getGenericReturnType()).getName()));
            } else if (desc.getWriteMethod() != null
                    && desc.getWriteMethod().getGenericParameterTypes() != null
                    && desc.getWriteMethod().getGenericParameterTypes().length == 1
                    && desc.getWriteMethod().getGenericParameterTypes()[0] instanceof TypeVariable) {
                entityField.setJavaType(genericMap.get(((TypeVariable) desc.getWriteMethod().getGenericParameterTypes()[0]).getName()));
            }
            entityFields.add(entityField);
        }
    }
    return entityFields;
}
 
Example 31
Project: convertigo-engine   File: DeleteDocumentAttachmentTransactionBeanInfo.java   View source code 5 votes vote down vote up
public DeleteDocumentAttachmentTransactionBeanInfo() {
	try {
		beanClass = DeleteDocumentAttachmentTransaction.class;
		additionalBeanClass = AbstractDocumentTransaction.class;

		resourceBundle = getResourceBundle("res/DeleteDocumentAttachmentTransaction");
		
		displayName = getExternalizedString("display_name");
		shortDescription = getExternalizedString("short_description");

		iconNameC16 = "/com/twinsoft/convertigo/beans/transactions/couchdb/images/deletedocumentattachment_color_16x16.png";
		iconNameC32 = "/com/twinsoft/convertigo/beans/transactions/couchdb/images/deletedocumentattachment_color_32x32.png";
		
		properties = new PropertyDescriptor[3];
		
		properties[0] = new PropertyDescriptor("q_rev", beanClass, "getQ_rev", "setQ_rev");
		properties[0].setDisplayName(getExternalizedString("property.q_rev.display_name"));
		properties[0].setShortDescription(getExternalizedString("property.q_rev.short_description"));
		
		properties[1] = new PropertyDescriptor("q_batch", beanClass, "getQ_batch", "setQ_batch");
		properties[1].setDisplayName(getExternalizedString("property.q_batch.display_name"));
		properties[1].setShortDescription(getExternalizedString("property.q_batch.short_description"));
		
		properties[2] = new PropertyDescriptor("p_attname", beanClass, "getP_attname", "setP_attname");
		properties[2].setDisplayName(getExternalizedString("property.p_attname.display_name"));
		properties[2].setShortDescription(getExternalizedString("property.p_attname.short_description"));
		
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 32
Project: convertigo-engine   File: MouseStatementBeanInfo.java   View source code 5 votes vote down vote up
public MouseStatementBeanInfo() {
	try {
		beanClass = MouseStatement.class;
		additionalBeanClass = com.twinsoft.convertigo.beans.statements.SimpleEventStatement.class;

		iconNameC16 = "/com/twinsoft/convertigo/beans/statements/images/mouse_16x16.png";
		iconNameC32 = "/com/twinsoft/convertigo/beans/statements/images/mouse_32x32.png";
		
		resourceBundle = getResourceBundle("res/MouseStatement");
		
		displayName = resourceBundle.getString("display_name");
		shortDescription = resourceBundle.getString("short_description");

		properties = new PropertyDescriptor[0];
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 33
Project: convertigo-engine   File: WriteXMLStepBeanInfo.java   View source code 5 votes vote down vote up
public WriteXMLStepBeanInfo() {
	try {
		beanClass = WriteXMLStep.class;
		additionalBeanClass = com.twinsoft.convertigo.beans.steps.WriteFileStep.class;

		iconNameC16 = "/com/twinsoft/convertigo/beans/steps/images/xmlW_16x16.png";
		iconNameC32 = "/com/twinsoft/convertigo/beans/steps/images/xmlW_32x32.png";
		
		resourceBundle = getResourceBundle("res/WriteXMLStep");
		
		displayName = resourceBundle.getString("display_name");
		shortDescription = resourceBundle.getString("short_description");	          
	
		properties = new PropertyDescriptor[1];
		
		properties[0] = new PropertyDescriptor("defaultRootTagname", beanClass, "getDefaultRootTagname", "setDefaultRootTagname");
		properties[0].setDisplayName(getExternalizedString("property.defaultroottagname.display_name"));
        properties[0].setShortDescription(getExternalizedString("property.defaultroottagname.short_description"));
        properties[0].setValue(DatabaseObject.PROPERTY_XMLNAME, Boolean.TRUE);
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 34
Project: openjdk-jdk10   File: TestMethodOrderDependence.java   View source code 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    final BeanInfo beanInfo = Introspector.getBeanInfo(Sub.class);
    final PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
    for (final PropertyDescriptor pd : pds) {
        System.err.println("pd = " + pd);
        final Class<?> type = pd.getPropertyType();
        if (type != Class.class && type != Long[].class
                && type != Integer.class && type != Enum.class) {
            throw new RuntimeException(Arrays.toString(pds));
        }
    }
}
 
Example 35
Project: convertigo-engine   File: ContextGetStatementBeanInfo.java   View source code 5 votes vote down vote up
public ContextGetStatementBeanInfo() {
	try {
		beanClass = ContextGetStatement.class;
		additionalBeanClass = com.twinsoft.convertigo.beans.core.Statement.class;

		iconNameC16 = "/com/twinsoft/convertigo/beans/statements/images/contextget_16x16.png";
		iconNameC32 = "/com/twinsoft/convertigo/beans/statements/images/contextget_32x32.png";
		
		resourceBundle = getResourceBundle("res/ContextGetStatement");
		
		displayName = resourceBundle.getString("display_name");
		shortDescription = resourceBundle.getString("short_description");

		properties = new PropertyDescriptor[2];

           properties[0] = new PropertyDescriptor("key", beanClass, "getKey", "setKey");
           properties[0].setDisplayName(getExternalizedString("property.key.display_name"));
           properties[0].setShortDescription(getExternalizedString("property.key.short_description"));
           
           properties[1] = new PropertyDescriptor("variable", beanClass, "getVariable", "setVariable");
           properties[1].setDisplayName(getExternalizedString("property.variable.display_name"));
           properties[1].setShortDescription(getExternalizedString("property.variable.short_description"));
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 36
Project: reflection-util   File: PropertyUtilsTest.java   View source code 5 votes vote down vote up
@Test
public void testReadDirectly_PropertyWithoutField() throws Exception {
	TestEntity testEntity = new TestEntity();
	PropertyDescriptor property = PropertyUtils.getPropertyDescriptor(TestEntity.class, TestEntity::getPropertyWithoutField);
	try {
		PropertyUtils.readDirectly(testEntity, property);
		fail("ReflectionRuntimeException expected");
	} catch (ReflectionRuntimeException e) {
		assertEquals("Failed to read TestEntity.propertyWithoutField", e.getMessage());
	}
}
 
Example 37
Project: convertigo-engine   File: CreateDirectoryStepBeanInfo.java   View source code 5 votes vote down vote up
public CreateDirectoryStepBeanInfo() {
	try {
		beanClass = CreateDirectoryStep.class;
		additionalBeanClass = com.twinsoft.convertigo.beans.core.Step.class;

		iconNameC16 = "/com/twinsoft/convertigo/beans/steps/images/createDirectory_16x16.png";
		iconNameC32 = "/com/twinsoft/convertigo/beans/steps/images/createDirectory_32x32.png";
		
		resourceBundle = getResourceBundle("res/CreateDirectoryStep");
		
		displayName = resourceBundle.getString("display_name");
		shortDescription = resourceBundle.getString("short_description");	          
	
		properties = new PropertyDescriptor[2];
		
        properties[0] = new PropertyDescriptor("destinationPath", beanClass, "getDestinationPath", "setDestinationPath");
		properties[0].setExpert(true);
		properties[0].setDisplayName(getExternalizedString("property.destinationPath.display_name"));
        properties[0].setShortDescription(getExternalizedString("property.destinationPath.short_description"));    
        properties[0].setValue("scriptable", Boolean.TRUE);
        
		properties[1] = new PropertyDescriptor("createNonExistentParentDirectories", beanClass, "isCreateNonExistentParentDirectories", "setCreateNonExistentParentDirectories");
		properties[1].setDisplayName(getExternalizedString("property.createNonExistentParentDirectories.display_name"));
		properties[1].setShortDescription(getExternalizedString("property.createNonExistentParentDirectories.short_description"));
		properties[1].setExpert(true);
     
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 38
Project: convertigo-engine   File: GetServerUuidsTransactionBeanInfo.java   View source code 5 votes vote down vote up
public GetServerUuidsTransactionBeanInfo() {
	try {
		beanClass = GetServerUuidsTransaction.class;
		additionalBeanClass = AbstractCouchDbTransaction.class;

		resourceBundle = getResourceBundle("res/GetServerUuidsTransaction");
		
		displayName = getExternalizedString("display_name");
		shortDescription = getExternalizedString("short_description");
		
		iconNameC16 = "/com/twinsoft/convertigo/beans/transactions/couchdb/images/getserveruuids_color_16x16.png";
		iconNameC32 = "/com/twinsoft/convertigo/beans/transactions/couchdb/images/getserveruuids_color_32x32.png";
		
		properties = new PropertyDescriptor[1];
		
		properties[0] = new PropertyDescriptor("q_count", beanClass, "getQ_count", "setQ_count");
		properties[0].setDisplayName(getExternalizedString("property.q_count.display_name"));
		properties[0].setShortDescription(getExternalizedString("property.q_count.short_description"));
	}
	catch(Exception e) {
		com.twinsoft.convertigo.engine.Engine.logBeans.error("Exception with bean info; beanClass=" + beanClass.toString(), e);
	}
}
 
Example 39
Project: GitHub   File: IncludeJsr303AnnotationsIT.java   View source code 5 votes vote down vote up
private static Object createInstanceWithPropertyValue(Class type, String propertyName, Object propertyValue) {
    try {
        Object instance = type.newInstance();
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor(propertyName, type);
        propertyDescriptor.getWriteMethod().invoke(instance, propertyValue);

        return instance;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 40
Project: jaffa-framework   File: BeanMoulder.java   View source code 5 votes vote down vote up
/** Set a value on a Bean, if its a persistent bean, try to use an update method first
 * (for v1.0 domain objects), otherwise use the setter (for v1.1 and above).
 */
private static void updateProperty (PropertyDescriptor pd, Object value, Object source)
throws IllegalAccessException, InvocationTargetException, MouldException {
    if(source instanceof Persistent) {
        if(pd!=null && pd.getWriteMethod()!=null) {
            try {
                Method m = source.getClass().getMethod("update" + StringHelper.getUpper1(pd.getName()), pd.getWriteMethod().getParameterTypes());
                if(!m.isAccessible()) m.setAccessible(true);
                Class tClass = m.getParameterTypes()[0];
                if(value==null || tClass.isAssignableFrom(value.getClass())) {
                    m.invoke(source, new Object[] {value});
                    log.debug("Update property '" + pd.getName() + "=" + value + "' on object '" + source.getClass().getName() + "'");
                // See if there is a datatype mapper for these classes
                } else if(DataTypeMapper.instance().isMappable(value.getClass(),tClass)) {
                    value = DataTypeMapper.instance().map(value, tClass);
                    m.invoke(source, new Object[] {value});
                    log.debug("Translate+Update property '" + pd.getName() + "=" + value + "' on object '" + source.getClass().getName() + "'");
                } else {
                    // Data type mismatch
                    throw new MouldException(MouldException.DATATYPE_MISMATCH, source.getClass().getName() + "." + m.getName(), tClass.getName(), value.getClass().getName());
                }
            } catch (NoSuchMethodException e) {
                log.debug("No Updator, try Setter for DO property '" + pd.getName() + "' on object '" + source.getClass().getName() + "'");
                // try to use the setter if there is no update method
                setProperty(pd,value,source);
            }
        } else {
            MouldException me = new MouldException(MouldException.NO_SETTER, null,
                                pd==null?"???":pd.getName(), source.getClass().getName());
            log.error(me.getLocalizedMessage());
            throw me;
        }
    } else
        setProperty(pd,value,source);
}