List of usage examples for java.beans PropertyDescriptor getWriteMethod
public synchronized Method getWriteMethod()
From source file:org.apache.usergrid.persistence.Schema.java
private <T extends Annotation> T getAnnotation(Class<? extends Entity> entityClass, PropertyDescriptor descriptor, Class<T> annotationClass) { try {/*from www .ja v a2 s . c o m*/ if ((descriptor.getReadMethod() != null) && descriptor.getReadMethod().isAnnotationPresent(annotationClass)) { return descriptor.getReadMethod().getAnnotation(annotationClass); } if ((descriptor.getWriteMethod() != null) && descriptor.getWriteMethod().isAnnotationPresent(annotationClass)) { return descriptor.getWriteMethod().getAnnotation(annotationClass); } Field field = FieldUtils.getField(entityClass, descriptor.getName(), true); if (field != null) { if (field.isAnnotationPresent(annotationClass)) { return field.getAnnotation(annotationClass); } } } catch (Exception e) { logger.error("Could not retrieve the annotations", e); } return null; }
From source file:org.apache.usergrid.persistence.Schema.java
public void setEntityProperty(Entity entity, String property, Object value) { PropertyDescriptor descriptor = getDescriptorForEntityProperty(entity.getClass(), property); if (descriptor != null) { Class<?> cls = descriptor.getPropertyType(); if (cls != null) { if ((value == null) || (cls.isAssignableFrom(value.getClass()))) { try { descriptor.getWriteMethod().invoke(entity, value); return; } catch (Exception e) { logger.error("Unable to set entity property " + property, e); }//w w w .j a va 2s .c o m } try { descriptor.getWriteMethod().invoke(entity, mapper.convertValue(value, cls)); return; } catch (Exception e) { logger.error("Unable to set entity property " + property, e); } } } entity.setDynamicProperty(property, value); }
From source file:net.sf.json.JSONObject.java
/** * Creates a bean from a JSONObject, with the specific configuration. *//*from www .j a v a 2 s. c o m*/ public static Object toBean(JSONObject jsonObject, JsonConfig jsonConfig) { if (jsonObject == null || jsonObject.isNullObject()) { return null; } Class beanClass = jsonConfig.getRootClass(); Map classMap = jsonConfig.getClassMap(); if (beanClass == null) { return toBean(jsonObject); } if (classMap == null) { classMap = Collections.EMPTY_MAP; } Object bean = null; try { if (beanClass.isInterface()) { if (!Map.class.isAssignableFrom(beanClass)) { throw new JSONException("beanClass is an interface. " + beanClass); } else { bean = new HashMap(); } } else { bean = jsonConfig.getNewBeanInstanceStrategy().newInstance(beanClass, jsonObject); } } catch (JSONException jsone) { throw jsone; } catch (Exception e) { throw new JSONException(e); } Map props = JSONUtils.getProperties(jsonObject); PropertyFilter javaPropertyFilter = jsonConfig.getJavaPropertyFilter(); for (Iterator entries = jsonObject.names(jsonConfig).iterator(); entries.hasNext();) { String name = (String) entries.next(); Class type = (Class) props.get(name); Object value = jsonObject.get(name); if (javaPropertyFilter != null && javaPropertyFilter.apply(bean, name, value)) { continue; } String key = Map.class.isAssignableFrom(beanClass) && jsonConfig.isSkipJavaIdentifierTransformationInMapKeys() ? name : JSONUtils.convertToJavaIdentifier(name, jsonConfig); PropertyNameProcessor propertyNameProcessor = jsonConfig.findJavaPropertyNameProcessor(beanClass); if (propertyNameProcessor != null) { key = propertyNameProcessor.processPropertyName(beanClass, key); } try { if (Map.class.isAssignableFrom(beanClass)) { // no type info available for conversion if (JSONUtils.isNull(value)) { setProperty(bean, key, value, jsonConfig); } else if (value instanceof JSONArray) { setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name, classMap, List.class), jsonConfig); } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type) || JSONUtils.isNumber(type) || JSONUtils.isString(type) || JSONFunction.class.isAssignableFrom(type)) { if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) { setProperty(bean, key, null, jsonConfig); } else { setProperty(bean, key, value, jsonConfig); } } else { Class targetClass = resolveClass(classMap, key, name, type); JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass(targetClass); jsc.setClassMap(classMap); if (targetClass != null) { setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig); } else { setProperty(bean, key, toBean((JSONObject) value), jsonConfig); } } } else { PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(bean, key); if (pd != null && pd.getWriteMethod() == null) { log.info("Property '" + key + "' of " + bean.getClass() + " has no write method. SKIPPED."); continue; } if (pd != null) { Class targetType = pd.getPropertyType(); if (!JSONUtils.isNull(value)) { if (value instanceof JSONArray) { if (List.class.isAssignableFrom(pd.getPropertyType())) { setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name, classMap, pd.getPropertyType()), jsonConfig); } else if (Set.class.isAssignableFrom(pd.getPropertyType())) { setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name, classMap, pd.getPropertyType()), jsonConfig); } else { setProperty(bean, key, convertPropertyValueToArray(key, value, targetType, jsonConfig, classMap), jsonConfig); } } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type) || JSONUtils.isNumber(type) || JSONUtils.isString(type) || JSONFunction.class.isAssignableFrom(type)) { if (pd != null) { if (jsonConfig.isHandleJettisonEmptyElement() && "".equals(value)) { setProperty(bean, key, null, jsonConfig); } else if (!targetType.isInstance(value)) { setProperty(bean, key, morphPropertyValue(key, value, type, targetType), jsonConfig); } else { setProperty(bean, key, value, jsonConfig); } } else if (beanClass == null || bean instanceof Map) { setProperty(bean, key, value, jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + bean.getClass().getName()); } } else { if (jsonConfig.isHandleJettisonSingleElementArray()) { JSONArray array = new JSONArray().element(value, jsonConfig); Class newTargetClass = resolveClass(classMap, key, name, type); JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass(newTargetClass); jsc.setClassMap(classMap); if (targetType.isArray()) { setProperty(bean, key, JSONArray.toArray(array, jsc), jsonConfig); } else if (JSONArray.class.isAssignableFrom(targetType)) { setProperty(bean, key, array, jsonConfig); } else if (List.class.isAssignableFrom(targetType) || Set.class.isAssignableFrom(targetType)) { jsc.setCollectionType(targetType); setProperty(bean, key, JSONArray.toCollection(array, jsc), jsonConfig); } else { setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig); } } else { if (targetType == Object.class || targetType.isInterface()) { Class targetTypeCopy = targetType; targetType = findTargetClass(key, classMap); targetType = targetType == null ? findTargetClass(name, classMap) : targetType; targetType = targetType == null && targetTypeCopy.isInterface() ? targetTypeCopy : targetType; } JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass(targetType); jsc.setClassMap(classMap); setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig); } } } else { if (type.isPrimitive()) { // assume assigned default value log.warn("Tried to assign null value to " + key + ":" + type.getName()); setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig); } else { setProperty(bean, key, null, jsonConfig); } } } else { if (!JSONUtils.isNull(value)) { if (value instanceof JSONArray) { setProperty(bean, key, convertPropertyValueToCollection(key, value, jsonConfig, name, classMap, List.class), jsonConfig); } else if (String.class.isAssignableFrom(type) || JSONUtils.isBoolean(type) || JSONUtils.isNumber(type) || JSONUtils.isString(type) || JSONFunction.class.isAssignableFrom(type)) { if (beanClass == null || bean instanceof Map || jsonConfig.getPropertySetStrategy() != null || !jsonConfig.isIgnorePublicFields()) { setProperty(bean, key, value, jsonConfig); } else { log.warn("Tried to assign property " + key + ":" + type.getName() + " to bean of class " + bean.getClass().getName()); } } else { if (jsonConfig.isHandleJettisonSingleElementArray()) { Class newTargetClass = resolveClass(classMap, key, name, type); JsonConfig jsc = jsonConfig.copy(); jsc.setRootClass(newTargetClass); jsc.setClassMap(classMap); setProperty(bean, key, toBean((JSONObject) value, jsc), jsonConfig); } else { setProperty(bean, key, value, jsonConfig); } } } else { if (type.isPrimitive()) { // assume assigned default value log.warn("Tried to assign null value to " + key + ":" + type.getName()); setProperty(bean, key, JSONUtils.getMorpherRegistry().morph(type, null), jsonConfig); } else { setProperty(bean, key, null, jsonConfig); } } } } } catch (JSONException jsone) { throw jsone; } catch (Exception e) { throw new JSONException("Error while setting property=" + name + " type " + type, e); } } return bean; }
From source file:org.eclipse.wb.tests.designer.core.util.reflect.ReflectionUtilsTest.java
/** * Test for {@link ReflectionUtils#getPropertyDescriptors(BeanInfo, Class)}.<br> * Public getter and protected setter./* w w w . ja v a2 s. c o m*/ */ public void test_getPropertyDescriptors_publicGetterProtectedSetter() throws Exception { @SuppressWarnings("unused") class MyButton extends JPanel { private static final long serialVersionUID = 0L; public String getTitle() { return null; } protected void setTitle(String s) { } } // check properties { Set<String> names = getPropertyDescriptorNames(MyButton.class).keySet(); assertThat(names).contains("title"); assertThat(names).excludes("title(java.lang.String)"); } // both getter and setter should be accessible { PropertyDescriptor descriptor = getPropertyDescriptorNames(MyButton.class).get("title"); assertNotNull(descriptor); assertNotNull(descriptor.getReadMethod()); assertNotNull(descriptor.getWriteMethod()); } }
From source file:org.eclipse.wb.tests.designer.core.util.reflect.ReflectionUtilsTest.java
/** * Test for {@link ReflectionUtils#getPropertyDescriptors(BeanInfo, Class)}.<br> * Protected getter and public setter.// w w w. ja v a2s. co m */ public void test_getPropertyDescriptors_protectedGetterPublicSetter() throws Exception { @SuppressWarnings("unused") class MyButton extends JPanel { private static final long serialVersionUID = 0L; protected String getTitle() { return null; } public void setTitle(String s) { } } // check properties { Set<String> names = getPropertyDescriptorNames(MyButton.class).keySet(); assertThat(names).contains("title"); assertThat(names).excludes("title(java.lang.String)"); } // both getter and setter should be accessible { PropertyDescriptor descriptor = getPropertyDescriptorNames(MyButton.class).get("title"); assertNotNull(descriptor); assertNotNull(descriptor.getReadMethod()); assertNotNull(descriptor.getWriteMethod()); } }
From source file:org.evergreen.web.utils.beanutils.PropertyUtilsBean.java
/** * <p>Return an accessible property setter method for this property, * if there is one; otherwise return <code>null</code>.</p> * * <p><strong>FIXME</strong> - Does not work with DynaBeans.</p> * * @param clazz The class of the read method will be invoked on * @param descriptor Property descriptor to return a setter for * @return The write method//from w w w . j a v a2 s.c om */ Method getWriteMethod(Class clazz, PropertyDescriptor descriptor) { return (MethodUtils.getAccessibleMethod(clazz, descriptor.getWriteMethod())); }
From source file:org.usergrid.persistence.Schema.java
public void setEntityProperty(Entity entity, String property, Object value) { PropertyDescriptor descriptor = getDescriptorForEntityProperty(entity.getClass(), property); if (descriptor != null) { Class<?> cls = descriptor.getPropertyType(); if (cls != null) { if ((value == null) || (cls.isAssignableFrom(value.getClass()))) { try { descriptor.getWriteMethod().invoke(entity, value); return; } catch (Exception e) { logger.error("Unable to set entity property " + property, e); }//from www .ja v a2 s.c o m } try { descriptor.getWriteMethod().invoke(entity, mapper.convertValue(value, cls)); return; } catch (Exception e) { logger.error("Unable to set entity property " + property, e); } } } entity.setDynamicProperty(property, value); }
From source file:com.datatorrent.stram.webapp.OperatorDiscoverer.java
private JSONArray getClassProperties(Class<?> clazz, int level) throws IntrospectionException { JSONArray arr = new JSONArray(); TypeDiscoverer td = new TypeDiscoverer(); try {//from w w w . j a v a 2s .c om for (PropertyDescriptor pd : Introspector.getBeanInfo(clazz).getPropertyDescriptors()) { Method readMethod = pd.getReadMethod(); if (readMethod != null) { if (readMethod.getDeclaringClass() == java.lang.Enum.class) { // skip getDeclaringClass continue; } else if ("class".equals(pd.getName())) { // skip getClass continue; } } else { // yields com.datatorrent.api.Context on JDK6 and com.datatorrent.api.Context.OperatorContext with JDK7 if ("up".equals(pd.getName()) && com.datatorrent.api.Context.class.isAssignableFrom(pd.getPropertyType())) { continue; } } //LOG.info("name: " + pd.getName() + " type: " + pd.getPropertyType()); Class<?> propertyType = pd.getPropertyType(); if (propertyType != null) { JSONObject propertyObj = new JSONObject(); propertyObj.put("name", pd.getName()); propertyObj.put("canGet", readMethod != null); propertyObj.put("canSet", pd.getWriteMethod() != null); if (readMethod != null) { for (Class<?> c = clazz; c != null; c = c.getSuperclass()) { OperatorClassInfo oci = classInfo.get(c.getName()); if (oci != null) { MethodInfo getMethodInfo = oci.getMethods.get(readMethod.getName()); if (getMethodInfo != null) { addTagsToProperties(getMethodInfo, propertyObj); break; } } } // type can be a type symbol or parameterized type td.setTypeArguments(clazz, readMethod.getGenericReturnType(), propertyObj); } else { if (pd.getWriteMethod() != null) { td.setTypeArguments(clazz, pd.getWriteMethod().getGenericParameterTypes()[0], propertyObj); } } //if (!propertyType.isPrimitive() && !propertyType.isEnum() && !propertyType.isArray() && !propertyType.getName().startsWith("java.lang") && level < MAX_PROPERTY_LEVELS) { // propertyObj.put("properties", getClassProperties(propertyType, level + 1)); //} arr.put(propertyObj); } } } catch (JSONException ex) { throw new RuntimeException(ex); } return arr; }
From source file:org.agnitas.service.impl.NewImportWizardServiceImpl.java
protected Node createNode(Object context, String name) throws Exception { Class type = null;/*from ww w. java 2s. c o m*/ // If the name represents a JavaBean property of the current context // then we derive the type from that... PropertyDescriptor propertyDescriptor = Toolkit.getPropertyDescriptor(context, name); if (propertyDescriptor != null) { type = propertyDescriptor.getPropertyType(); } else if (context != null && !classMap.containsKey(name)) { return new FieldNode(context, name); } else { // ... otherwise we look for a named type alias type = classMap.get(name); } if (type == null) { throw new IllegalArgumentException( String.format("No type mapping could be found or derived: name=%s", name)); } // If there's a format for the node's type then we go with that... if (type.isAssignableFrom(String.class) || type.isAssignableFrom(Map.class)) { return new FieldNode(context, name); } // ...otherwise we've got some sort of mutable node value. Object instance; // If the node corresponds to a JavaBean property which already has a // value then we mutate that... if (propertyDescriptor != null) { instance = propertyDescriptor.getReadMethod().invoke(context); if (instance == null) { instance = type.newInstance(); propertyDescriptor.getWriteMethod().invoke(context, instance); } } else { // ...otherwise we're just dealing with some non-property instance instance = type.newInstance(); } // Collections are handled in a special way - all properties are // basically their values if (instance instanceof Collection) { return new CollectionNode(name, (Collection) instance); } // Everything else is assumed to be a JavaBean return new JavaBeanNode(instance, name); }
From source file:com.googlecode.wicketwebbeans.model.BeanMetaData.java
private void init() { // Check if bean supports PropertyChangeListeners. hasAddPropertyChangeListenerMethod = getAddPropertyChangeListenerMethod() != null; hasRemovePropertyChangeListenerMethod = getRemovePropertyChangeListenerMethod() != null; String baseBeanClassName = getBaseClassName(beanClass); // Deduce actions from the component. List<Method> actionMethods = getActionMethods(component.getClass()); for (Method method : actionMethods) { String name = method.getName(); String prefixedName = ACTION_PROPERTY_PREFIX + name; String label = getLabelFromLocalizer(baseBeanClassName, prefixedName); if (label == null) { label = createLabel(name);/* w w w. j a v a 2 s . co m*/ } ElementMetaData actionMeta = new ElementMetaData(this, prefixedName, label, null); actionMeta.setAction(true); elements.add(actionMeta); } // Create defaults based on the bean itself. PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass); for (PropertyDescriptor descriptor : descriptors) { String name = descriptor.getName(); // Skip getClass() and methods that are not readable or hidden. if (name.equals("class") || descriptor.getReadMethod() == null || descriptor.isHidden()) { continue; } String label = getLabelFromLocalizer(baseBeanClassName, name); if (label == null) { label = descriptor.getDisplayName(); } if (label.equals(name)) { label = createLabel(name); } ElementMetaData propertyMeta = new ElementMetaData(this, name, label, descriptor.getReadMethod().getGenericReturnType()); propertyMeta.setViewOnly(isViewOnly()); elements.add(propertyMeta); if (descriptor.getWriteMethod() == null) { propertyMeta.setViewOnly(true); } deriveElementFromAnnotations(descriptor, propertyMeta); } // Collect various sources of metadata for the bean we're interested in. collectAnnotations(); collectFromBeanProps(); collectBeansAnnotation(beansMetaData, false); // Process action annotations on component. for (Method method : getActionMethods(component.getClass())) { Action action = method.getAnnotation(Action.class); processActionAnnotation(action, method.getName()); } // Determine the hierarchy of Bean contexts. I.e., the default Bean is always processed first, followed by those that // extend it, etc. This acts as a stack. List<Bean> beansHier = buildContextStack(); // Apply beans in order from highest to lowest. The default context will always be first. boolean foundSpecifiedContext = false; for (Bean bean : beansHier) { if (context != null && context.equals(bean.context())) { foundSpecifiedContext = true; } processBeanAnnotation(bean); } // Ensure that if a context was specified, that we found one in the metadata. Otherwise it might have been a typo. if (context != null && !foundSpecifiedContext) { throw new RuntimeException("Could not find specified context '" + context + "' in metadata."); } // Post-process Bean-level parameters if (!getBooleanParameter(PARAM_DISPLAYED)) { elements.clear(); tabs.clear(); } // Configure tabs if (tabs.isEmpty()) { // Create single default tab. tabs.add(new TabMetaData(this, DEFAULT_TAB_ID, getParameter(PARAM_LABEL))); } String defaultTabId = tabs.get(0).getId(); if (!getBooleanParameter(PARAM_EXPLICIT_ONLY) || defaultTabId.equals(DEFAULT_TAB_ID)) { // Post-process each property based on bean parameters for (ElementMetaData elementMeta : elements) { // If element is not on a tab, add it to the first. If it's an // action, it must have been assigned an order to // appear on a tab. Otherwise it is a global action. if (elementMeta.getTabId() == null && (!elementMeta.isAction() || (elementMeta.isAction() && elementMeta.isActionSpecifiedInProps()))) { elementMeta.setTabId(defaultTabId); } } } // Remove elements not specified in props if (getBooleanParameter(PARAM_EXPLICIT_ONLY)) { for (Iterator<ElementMetaData> iter = elements.iterator(); iter.hasNext();) { ElementMetaData element = iter.next(); if (!element.isSpecifiedInProps()) { iter.remove(); } } } Collections.sort(elements, new Comparator<ElementMetaData>() { public int compare(ElementMetaData o1, ElementMetaData o2) { return (o1.getOrder() > o2.getOrder() ? 1 : (o1.getOrder() < o2.getOrder() ? -1 : 0)); } }); }