List of usage examples for java.beans PropertyDescriptor getReadMethod
public synchronized Method getReadMethod()
From source file:com.twinsoft.convertigo.beans.CheckBeans.java
private static void analyzeJavaClass(String javaClassName) { try {//from w w w . j a v a 2 s . c o m Class<?> javaClass = Class.forName(javaClassName); String javaClassSimpleName = javaClass.getSimpleName(); if (!DatabaseObject.class.isAssignableFrom(javaClass)) { //Error.NON_DATABASE_OBJECT.add(javaClassName); return; } nBeanClass++; String dboBeanInfoClassName = javaClassName + "BeanInfo"; MySimpleBeanInfo dboBeanInfo = null; try { dboBeanInfo = (MySimpleBeanInfo) (Class.forName(dboBeanInfoClassName)).newInstance(); } catch (ClassNotFoundException e) { if (!Modifier.isAbstract(javaClass.getModifiers())) { Error.MISSING_BEAN_INFO .add(javaClassName + " (expected bean info: " + dboBeanInfoClassName + ")"); } return; } catch (Exception e) { e.printStackTrace(); return; } BeanDescriptor beanDescriptor = dboBeanInfo.getBeanDescriptor(); // Check abstract class if (Modifier.isAbstract(javaClass.getModifiers())) { // Check icon (16x16) String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_16x16); if (declaredIconName != null) { Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName); } // Check icon (32x32) declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32); if (declaredIconName != null) { Error.ABSTRACT_CLASS_WITH_ICON.add(javaClassName); } // Check display name if (!beanDescriptor.getDisplayName().equals("?")) { Error.ABSTRACT_CLASS_WITH_DISPLAY_NAME.add(javaClassName); } // Check description if (!beanDescriptor.getShortDescription().equals("?")) { Error.ABSTRACT_CLASS_WITH_DESCRIPTION.add(javaClassName); } } else { nBeanClassNotAbstract++; // Check bean declaration in database_objects.xml if (!dboXmlDeclaredDatabaseObjects.contains(javaClassName)) { Error.BEAN_DEFINED_BUT_NOT_USED.add(javaClassName); } // Check icon name policy (16x16) String declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_16x16); String expectedIconName = javaClassName.replace(javaClassSimpleName, "images/" + javaClassSimpleName); expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_16x16"; expectedIconName = expectedIconName.toLowerCase() + ".png"; if (declaredIconName != null) { if (!declaredIconName.equals(expectedIconName)) { Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + " Declared: " + declaredIconName + "\n" + " Expected: " + expectedIconName); } } // Check icon file (16x16) File iconFile = new File(srcBase + declaredIconName); if (!iconFile.exists()) { Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName); } else { icons.remove(declaredIconName); } // Check icon name policy (32x32) declaredIconName = MySimpleBeanInfo.getIconName(dboBeanInfo, MySimpleBeanInfo.ICON_COLOR_32x32); expectedIconName = javaClassName.replace(javaClassSimpleName, "images/" + javaClassSimpleName); expectedIconName = "/" + expectedIconName.replace('.', '/') + "_color_32x32"; expectedIconName = expectedIconName.toLowerCase() + ".png"; if (declaredIconName != null) { if (!declaredIconName.equals(expectedIconName)) { Error.BEAN_ICON_NAMING_POLICY.add(javaClassName + "\n" + " Declared: " + declaredIconName + "\n" + " Expected: " + expectedIconName); } } // Check icon file (32x32) iconFile = new File(srcBase + declaredIconName); if (!iconFile.exists()) { Error.BEAN_MISSING_ICON.add(javaClassName + " - icon missing: " + declaredIconName); } else { icons.remove(declaredIconName); } // Check display name if (beanDescriptor.getDisplayName().equals("?")) { Error.BEAN_MISSING_DISPLAY_NAME.add(javaClassName); } // Check description if (beanDescriptor.getShortDescription().equals("?")) { Error.BEAN_MISSING_DESCRIPTION.add(javaClassName); } } // Check declared bean properties PropertyDescriptor[] propertyDescriptors = dboBeanInfo.getLocalPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { String propertyName = propertyDescriptor.getName(); try { javaClass.getDeclaredField(propertyName); } catch (SecurityException e) { e.printStackTrace(); } catch (NoSuchFieldException e) { try { // Try to find it in the upper classes javaClass.getField(propertyName); } catch (SecurityException e1) { // printStackTrace(); } catch (NoSuchFieldException e1) { Error.PROPERTY_DECLARED_BUT_NOT_FOUND.add(javaClassName + ": " + propertyName); } } } Method[] methods = javaClass.getDeclaredMethods(); List<Method> listMethods = Arrays.asList(methods); List<String> listMethodNames = new ArrayList<String>(); for (Method method : listMethods) { listMethodNames.add(method.getName()); } Field[] fields = javaClass.getDeclaredFields(); for (Field field : fields) { int fieldModifiers = field.getModifiers(); // Ignore static fields (constants) if (Modifier.isStatic(fieldModifiers)) continue; String fieldName = field.getName(); String errorMessage = javaClassName + ": " + field.getName(); // Check bean info PropertyDescriptor propertyDescriptor = isBeanProperty(fieldName, dboBeanInfo); if (propertyDescriptor != null) { // Check bean property name policy if (!propertyDescriptor.getName().equals(fieldName)) { Error.PROPERTY_NAMING_POLICY.add(errorMessage); } String declaredGetter = propertyDescriptor.getReadMethod().getName(); String declaredSetter = propertyDescriptor.getWriteMethod().getName(); String formattedFieldName = Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1); String expectedGetter = "get" + formattedFieldName; String expectedSetter = "set" + formattedFieldName; // Check getter name policy if (!declaredGetter.equals(expectedGetter)) { Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH .add(errorMessage + "\n" + " Declared getter: " + declaredGetter + "\n" + " Expected getter: " + expectedGetter); } // Check setter name policy if (!declaredSetter.equals(expectedSetter)) { Error.GETTER_SETTER_DECLARED_EXPECTED_NAMES_MISMATCH .add(errorMessage + "\n" + " Declared setter: " + declaredSetter + "\n" + " Expected setter: " + expectedSetter); } // Check required private modifiers for bean property if (!Modifier.isPrivate(fieldModifiers)) { Error.PROPERTY_NOT_PRIVATE.add(errorMessage); } // Check getter if (!listMethodNames.contains(declaredGetter)) { Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND .add(errorMessage + " - Declared getter not found: " + declaredGetter); } // Check setter if (!listMethodNames.contains(declaredSetter)) { Error.GETTER_SETTER_DECLARED_BUT_NOT_FOUND .add(errorMessage + " - Declared setter not found: " + declaredGetter); } // Check non transient modifier if (Modifier.isTransient(fieldModifiers)) { Error.PROPERTY_TRANSIENT.add(errorMessage); } } else if (!Modifier.isTransient(fieldModifiers)) { Error.FIELD_NOT_TRANSIENT.add(errorMessage); } } } catch (ClassNotFoundException e) { System.out.println("ERROR on " + javaClassName); e.printStackTrace(); } }
From source file:com.complexible.pinto.RDFMapper.java
private Class pinpointClass(final Model theGraph, final Resource theResource, final PropertyDescriptor theDescriptor) { Class aClass = theDescriptor.getPropertyType(); if (Collection.class.isAssignableFrom(aClass)) { // if the field we're assigning from is a collection, try and figure out the type of the thing // we're creating from the collection Type[] aTypes = null;// w w w . j a v a 2s .co m if (theDescriptor.getReadMethod().getGenericParameterTypes().length > 0) { // should this be the return type? eg new Type[] { theDescriptor.getReadMethod().getGenericReturnType() }; aTypes = theDescriptor.getReadMethod().getGenericParameterTypes(); } else if (theDescriptor.getWriteMethod().getGenericParameterTypes().length > 0) { aTypes = theDescriptor.getWriteMethod().getGenericParameterTypes(); } if (aTypes != null && aTypes.length >= 1) { // first type argument to a collection is usually the one we care most about if (aTypes[0] instanceof ParameterizedType && ((ParameterizedType) aTypes[0]).getActualTypeArguments().length > 0) { Type aType = ((ParameterizedType) aTypes[0]).getActualTypeArguments()[0]; if (aType instanceof Class) { aClass = (Class) aType; } else if (aType instanceof WildcardTypeImpl) { WildcardTypeImpl aWildcard = (WildcardTypeImpl) aType; // trying to suss out super v extends w/o resorting to string munging. if (aWildcard.getLowerBounds().length == 0 && aWildcard.getUpperBounds().length > 0) { // no lower bounds afaik indicates ? extends Foo aClass = ((Class) aWildcard.getUpperBounds()[0]); } else if (aWildcard.getLowerBounds().length > 0) { // lower & upper bounds I believe indicates something of the form Foo super Bar aClass = ((Class) aWildcard.getLowerBounds()[0]); } else { // shoot, we'll try the string hack that Adrian posted on the mailing list. try { aClass = Class.forName(aType.toString().split(" ")[2].substring(0, aTypes[0].toString().split(" ")[2].length() - 1)); } catch (Exception e) { // everything has failed, let aClass be the default (theClass) and hope for the best } } } else { // punt? wtf else could it be? try { aClass = Class.forName(aType.toString()); } catch (ClassNotFoundException e) { // oh well, we did the best we can } } } else if (aTypes[0] instanceof Class) { aClass = (Class) aTypes[0]; } } else { LOGGER.info("Could not find type for collection %s", aClass); } } else if (!Classes.isInstantiable(aClass) || !Classes.hasDefaultConstructor(aClass)) { Class<?> aCurr = null; final Iterable<Resource> aRdfTypes = Models2.getTypes(theGraph, theResource); for (Resource aType : aRdfTypes) { Class<?> aMappedClass = mMappings.get(aType); if (aMappedClass != null) { if (aCurr == null) { aCurr = aMappedClass; } else if (aCurr.isAssignableFrom(aMappedClass)) { // we want the most specific class, that's likely to be what's instantiable aCurr = aMappedClass; } } } if (aCurr != null) { aClass = aCurr; } } return aClass; }
From source file:de.hybris.platform.webservices.AbstractWebServicesTest.java
/** * Checks if the given properties of the model and dto are equal <br/> * The properties must have the same getters <br/> * if at least one is not equal or not found, than {@link AssertionError} is thrown <br/> * /*from w w w. j av a 2 s. c om*/ * @param expectedModel * model object * @param actualDto * expected dto object * @param properties * a list of properties which have to be checked */ protected void assertEqual(final ItemModel expectedModel, final Object actualDto, final String... properties) { //0. check if null assertNotNull("No " + actualDto.getClass().getSimpleName() + " within body ", actualDto); assertNotNull("No " + expectedModel.getClass().getSimpleName() + " model ", expectedModel); //1. get the properties descriptors from model and dto separately because there are different classes final Map<String, PropertyDescriptor> pdModelMap = getPropertyDescriptors(expectedModel.getClass()); final Map<String, PropertyDescriptor> pdDtoMap = getPropertyDescriptors(actualDto.getClass()); //2. loop on given properties list for (final String property : properties) { //a) check if properties exist in model and dto final PropertyDescriptor pdModel = pdModelMap.get(property); final PropertyDescriptor pdDto = pdDtoMap.get(property); if ((pdModel == null) || (pdDto == null)) { Assert.fail("Property '" + property + "' not available"); } Object expectedModelProp = null; Object actualDtoProp = null; //b) get the property values from model and dto try { expectedModelProp = pdModel.getReadMethod().invoke(expectedModel, (Object[]) null); actualDtoProp = pdDto.getReadMethod().invoke(actualDto, (Object[]) null); } catch (final Exception e) { e.printStackTrace(); Assert.fail(); } //c) compare: error if at least one is not equal or not found final String msg = expectedModel.getClass().getSimpleName() + "," + actualDto.getClass().getSimpleName() + ": value of '" + property + "' does not match expected value (actual: '" + actualDtoProp + "' expected: '" + expectedModelProp + "')"; Assert.assertEquals(msg, expectedModelProp, actualDtoProp); } }
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 ava2 s . c om } 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)); } }); }
From source file:org.enerj.apache.commons.beanutils.PropertyUtilsBean.java
/** * <p>Return an accessible property getter 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 descriptor Property descriptor to return a getter for *///ww w. j av a2 s.c o m public Method getReadMethod(PropertyDescriptor descriptor) { return (MethodUtils.getAccessibleMethod(descriptor.getReadMethod())); }
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 {/* www . jav a 2 s . com*/ 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:BeanArrayList.java
/** * This method returns the sum of all values of a numerical * property.//from ww w. ja v a2s . co m * @param propertyName String value of the property name to calculate. * @throws java.lang.IllegalAccessException reflection exception * @throws java.beans.IntrospectionException reflection exception * @throws java.lang.reflect.InvocationTargetException reflection exception * @return sum of a numerical property */ public Number getSumOfProperty(String propertyName) throws java.lang.IllegalAccessException, java.beans.IntrospectionException, java.lang.reflect.InvocationTargetException { double d = 0.0; String currentClass = ""; PropertyDescriptor pd = null; for (int i = 0; i < this.size(); i++) { T o = this.get(i); if (!currentClass.equals(o.getClass().getName())) { PropertyDescriptor[] pds = Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors(); boolean foundProperty = false; for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) { if (pds[pdi].getName().equals(propertyName)) { pd = pds[pdi]; foundProperty = true; } } } if (o != null) { Number n = (Number) pd.getReadMethod().invoke(o); d += n.doubleValue(); } } return new Double(d); }
From source file:com.xwtec.xwserver.util.json.JSONArray.java
/** * Get the collection type from a getter or setter, or null if no type was * found.<br/>/*from www .j a v a 2 s . c om*/ * Contributed by [Matt Small @ WaveMaker]. */ public static Class[] getCollectionType(PropertyDescriptor pd, boolean useGetter) throws JSONException { Type type; if (useGetter) { Method m = pd.getReadMethod(); type = m.getGenericReturnType(); } else { Method m = pd.getWriteMethod(); Type[] gpts = m.getGenericParameterTypes(); if (1 != gpts.length) { throw new JSONException("method " + m + " is not a standard setter"); } type = gpts[0]; } if (!(type instanceof ParameterizedType)) { return null; // throw new JSONException("type not instanceof ParameterizedType: // "+type.getClass()); } ParameterizedType pType = (ParameterizedType) type; Type[] actualTypes = pType.getActualTypeArguments(); Class[] ret = new Class[actualTypes.length]; for (int i = 0; i < ret.length; i++) { ret[i] = (Class) actualTypes[i]; } return ret; }
From source file:BeanVector.java
/** * This method returns the sum of all values of a numerical * property./*from w w w . ja v a 2 s . c o m*/ * @param propertyName String value of the property name to calculate. * @throws java.lang.IllegalAccessException reflection exception * @throws java.beans.IntrospectionException reflection exception * @throws java.lang.reflect.InvocationTargetException reflection exception * @return sum of a numerical property */ public Number getSumOfProperty(String propertyName) throws java.lang.IllegalAccessException, java.beans.IntrospectionException, java.lang.reflect.InvocationTargetException { double d = 0.0; String currentClass = ""; PropertyDescriptor pd = null; for (int i = 0; i < this.size(); i++) { T o = this.elementAt(i); if (!currentClass.equals(o.getClass().getName())) { PropertyDescriptor[] pds = Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors(); boolean foundProperty = false; for (int pdi = 0; (pdi < pds.length) && !foundProperty; pdi++) { if (pds[pdi].getName().equals(propertyName)) { pd = pds[pdi]; foundProperty = true; } } } if (o != null) { Number n = (Number) pd.getReadMethod().invoke(o); d += n.doubleValue(); } } return new Double(d); }
From source file:org.apache.usergrid.persistence.Schema.java
public Map<String, Object> getEntityProperties(Entity entity) { Map<String, Object> properties = new LinkedHashMap<String, Object>(); Map<String, PropertyDescriptor> propertyDescriptors = entityClassPropertyToDescriptor .get(entity.getClass());// w w w . ja v a2 s . c o m if (propertyDescriptors == null) { registerEntity(entity.getClass()); propertyDescriptors = entityClassPropertyToDescriptor.get(entity.getClass()); } for (Entry<String, PropertyDescriptor> propertyEntry : propertyDescriptors.entrySet()) { String property = propertyEntry.getKey(); PropertyDescriptor descriptor = propertyEntry.getValue(); if (descriptor != null) { try { Object value = descriptor.getReadMethod().invoke(entity); if (value != null) { properties.put(property, value); } } catch (Exception e) { logger.error("Unable to get entity property " + property, e); } } } Map<String, Object> dynamicProperties = entity.getDynamicProperties(); if (dynamicProperties != null) { properties.putAll(dynamicProperties); } return properties; }