List of usage examples for java.beans PropertyDescriptor getPropertyType
public synchronized Class<?> getPropertyType()
From source file:eu.squadd.reflections.mapper.ServiceModelTranslator.java
private static boolean assignPropertyValue(PropertyDescriptor sourceProp, Object sourceValue, PropertyDescriptor destProp, Object destInstance) { if (sourceValue == null) { System.out.println("Null value found, assignment skipped"); return true; }/*w w w . j a v a 2 s . com*/ boolean result = false; Class<?> sourceType = sourceProp.getPropertyType(); Method getter = sourceProp.getReadMethod(); Class<?> destType = destProp.getPropertyType(); Method setter = destProp.getWriteMethod(); try { if (destType.isInterface() || destType.isArray() || destType.isEnum()) { if (Collection.class.isAssignableFrom(sourceType) && Collection.class.isAssignableFrom(destType)) assignCollectionValue(getter, sourceValue, destType, setter, destInstance); else if (Map.class.isAssignableFrom(sourceType) && Map.class.isAssignableFrom(destType)) assignMapValue(getter, sourceValue, setter, destInstance); else assignMixedTypesValue(sourceType, getter, sourceValue, destType, setter, destInstance); } else if (destType.isInstance(sourceValue) || destType.isPrimitive()) setter.invoke(destInstance, sourceValue); else if (destType.isMemberClass()) setter.invoke(destInstance, sourceValue); else if (destType.isAssignableFrom(sourceType)) setter.invoke(destInstance, destType.cast(sourceValue)); else { //if (ClassUtils.isInnerClass(destType)) { Object member = transposeModel(sourceType, destType, sourceValue); member = destType.cast(member); setter.invoke(destInstance, member); } result = true; } catch (IllegalArgumentException ex) { System.out.println("Looks like type mismatch, source type: " + sourceType + ", dest type: " + destType); Logger.getLogger(ServiceModelTranslator.class.getName()).log(Level.SEVERE, null, ex); } catch (InvocationTargetException | IllegalAccessException ex) { Logger.getLogger(ServiceModelTranslator.class.getName()).log(Level.SEVERE, null, ex); } return result; }
From source file:net.authorize.api.controller.test.ApiCoreTestBase.java
public static void showProperties(Object bean) { if (null == bean) { return;/* www .ja v a 2 s.co m*/ } try { BeanInfo info = Introspector.getBeanInfo(bean.getClass(), Object.class); PropertyDescriptor[] props = info.getPropertyDescriptors(); for (PropertyDescriptor pd : props) { String name = pd.getName(); Method getter = pd.getReadMethod(); Class<?> type = pd.getPropertyType(); if (null != getter && !"class".equals(name)) { Object value = getter.invoke(bean); logger.info(String.format("Type: '%s', Name:'%s', Value:'%s'", type, name, value)); processCollections(type, name, value); //process compositions of custom classes if (null != value && 0 <= type.toString().indexOf("net.authorize.")) { showProperties(value); } } } } catch (Exception e) { logger.error(String.format("Exception during navigating properties: Message: %s, StackTrace: %s", e.getMessage(), e.getStackTrace())); } }
From source file:com.nortal.petit.beanmapper.BeanMappingUtils.java
/** * Returns the initialized property.//from ww w . ja v a2 s.com * In case of Embedded property the root property is returned for reference. Embedde properties themselves are expanded * in the props variable. * * Null is returned if the property is not valid (either not readable/writable or Transient) * * @param props * @param name * @param type */ public static <B> Property<B, Object> initProperty(Map<String, Property<B, Object>> props, String name, Class<B> type) { PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(type, name); if (!isPropertyReadableAndWritable(pd)) { return null; } List<Annotation> ans = BeanMappingReflectionUtils.readAnnotations(type, pd.getName()); if (BeanMappingReflectionUtils.getAnnotation(ans, Transient.class) != null) { return null; } Column column = BeanMappingReflectionUtils.getAnnotation(ans, Column.class); ReflectionProperty<B, Object> prop = new ReflectionProperty<B, Object>(name, (Class<Object>) pd.getPropertyType(), inferColumn(name, column), pd.getWriteMethod(), pd.getReadMethod()); if (column != null) { prop.readOnly(!column.insertable()); } if (BeanMappingReflectionUtils.getAnnotation(ans, Id.class) != null) { prop.setIdProperty(true); } if (useAdditionalConfiguration()) { prop.getConfiguration().setAnnotations(ans); if (Collection.class.isAssignableFrom(pd.getPropertyType())) { prop.getConfiguration().setCollectionTypeArguments( ((ParameterizedType) pd.getReadMethod().getGenericReturnType()).getActualTypeArguments()); } } if (BeanMappingReflectionUtils.getAnnotation(ans, Embedded.class) != null) { props.putAll(getCompositeProperties(prop, ans)); } else { props.put(prop.name(), prop); } return prop; }
From source file:com.emc.ecs.sync.config.ConfigUtil.java
/** * convert an annotated getter into a commons-cli Option */// w w w . ja v a 2s . co m public static org.apache.commons.cli.Option cliOptionFromAnnotation(PropertyDescriptor descriptor, Option _option, String prefix) { org.apache.commons.cli.Option option = new org.apache.commons.cli.Option(null, _option.description()); // required if (_option.required()) option.setRequired(true); // long name String longName; if (_option.cliName().length() > 0) { longName = _option.cliName(); } else { longName = hyphenate(descriptor.getName()); if ((Boolean.class == descriptor.getPropertyType() || "boolean".equals(descriptor.getPropertyType().getName())) && _option.cliInverted()) longName = "no-" + longName; } if (prefix != null) longName = prefix + longName; option.setLongOpt(longName); // parameter[s] if (descriptor.getPropertyType().isArray()) { option.setArgs(org.apache.commons.cli.Option.UNLIMITED_VALUES); } else if (Boolean.class != descriptor.getPropertyType() && !"boolean".equals(descriptor.getPropertyType().getName())) { // non-booleans *must* have an argument option.setArgs(1); } if (option.hasArg()) { if (_option.valueHint().length() > 0) option.setArgName(_option.valueHint()); else option.setArgName(option.getLongOpt()); } return option; }
From source file:org.apache.cocoon.transformation.TagTransformer.java
private static Map getWriteMethodMap(Class beanClass) throws IntrospectionException { Map map = (Map) TAG_PROPERTIES_MAP.get(beanClass); if (map != null) { return map; }/*from w w w. ja v a 2s.co m*/ BeanInfo info = Introspector.getBeanInfo(beanClass); if (info != null) { PropertyDescriptor pds[] = info.getPropertyDescriptors(); map = new HashMap(pds.length * 4 / 3, 1); for (int i = 0; i < pds.length; i++) { PropertyDescriptor pd = pds[i]; String name = pd.getName(); Method method = pd.getWriteMethod(); Class type = pd.getPropertyType(); if (type != String.class) // only String properties continue; map.put(name, method); } } TAG_PROPERTIES_MAP.put(beanClass, map); return map; }
From source file:gr.interamerican.bo2.utils.JavaBeanUtils.java
/** * Finds the property descriptor that describes a property. * /*from w ww . j a v a 2 s . c om*/ * @param type * The bean class. * @param name * The name of the property searched. This may be a composite property, * e.g. "nestedBean.property1". * * @return Returns the property descriptor that describes the property with * the specified name. If there is no property with ths name, then * the method returns null. */ public static PropertyDescriptor getPropertyDescriptor(Class<?> type, String name) { if (RESOLVER.hasNested(name)) { String next = RESOLVER.next(name); PropertyDescriptor pd = getPropertyDescriptor(type, next); return getPropertyDescriptor(pd.getPropertyType(), RESOLVER.remove(name)); } Map<String, PropertyDescriptor> descriptors = getBeansPropertiesMap(type); return descriptors.get(name); }
From source file:gr.interamerican.bo2.utils.JavaBeanUtils.java
/** * Checks if value is a valid value for a property. * /* www. j a v a2 s . com*/ * @param pd * @param value * * @return Returns true if the specified value is valid for * the specified property. */ static boolean isValidValue(PropertyDescriptor pd, Object value) { if (value == null) { return true; } return pd.getPropertyType().isAssignableFrom(value.getClass()); }
From source file:com.ocs.dynamo.utils.ClassUtils.java
/** * Returns the property descriptor for a nested property * //ww w .j a va 2 s . c om * @param clazz * the class * @param property * the name of the property * @return */ public static PropertyDescriptor getPropertyDescriptorForNestedProperty(Class<?> clazz, String property) { PropertyDescriptor pd = null; if (clazz != null && !StringUtils.isEmpty(property)) { String[] props = property.split("\\.", 2); pd = org.springframework.beans.BeanUtils.getPropertyDescriptor(clazz, props[0]); if (props.length > 1) { pd = getPropertyDescriptorForNestedProperty(pd.getPropertyType(), props[1]); } } return pd; }
From source file:org.openmrs.util.ReportingcompatibilityUtil.java
/** * Uses reflection to translate a PatientSearch into a PatientFilter *//*from ww w . j a va 2s. c o m*/ @SuppressWarnings("unchecked") public static PatientFilter toPatientFilter(PatientSearch search, CohortSearchHistory history, EvaluationContext evalContext) { if (search.isSavedSearchReference()) { PatientSearch ps = ((PatientSearchReportObject) Context.getService(ReportObjectService.class) .getReportObject(search.getSavedSearchId())).getPatientSearch(); return toPatientFilter(ps, history, evalContext); } else if (search.isSavedFilterReference()) { return Context.getService(ReportObjectService.class).getPatientFilterById(search.getSavedFilterId()); } else if (search.isSavedCohortReference()) { Cohort c = Context.getCohortService().getCohort(search.getSavedCohortId()); // to prevent lazy loading exceptions, cache the member ids here if (c != null) { c.getMemberIds().size(); } return new CohortFilter(c); } else if (search.isComposition()) { if (history == null && search.requiresHistory()) { throw new IllegalArgumentException("You can't evaluate this search without a history"); } else { return search.cloneCompositionAsFilter(history, evalContext); } } else { Class clz = search.getFilterClass(); if (clz == null) { throw new IllegalArgumentException( "search must be saved, composition, or must have a class specified"); } log.debug("About to instantiate " + clz); PatientFilter pf = null; try { pf = (PatientFilter) clz.newInstance(); } catch (Exception ex) { log.error("Couldn't instantiate a " + search.getFilterClass(), ex); return null; } Class[] stringSingleton = { String.class }; if (search.getArguments() != null) { for (SearchArgument sa : search.getArguments()) { if (log.isDebugEnabled()) { log.debug("Looking at (" + sa.getPropertyClass() + ") " + sa.getName() + " -> " + sa.getValue()); } PropertyDescriptor pd = null; try { pd = new PropertyDescriptor(sa.getName(), clz); } catch (IntrospectionException ex) { log.error("Error while examining property " + sa.getName(), ex); continue; } Class<?> realPropertyType = pd.getPropertyType(); // instantiate the value of the search argument String valueAsString = sa.getValue(); String testForExpression = search.getArgumentValue(sa.getName()); if (testForExpression != null) { log.debug("Setting " + sa.getName() + " to: " + testForExpression); if (evalContext != null && EvaluationContext.isExpression(testForExpression)) { Object evaluated = evalContext.evaluateExpression(testForExpression); if (evaluated != null) { if (evaluated instanceof Date) { valueAsString = Context.getDateFormat().format((Date) evaluated); } else { valueAsString = evaluated.toString(); } } log.debug("Evaluated " + sa.getName() + " to: " + valueAsString); } } Object value = null; Class<?> valueClass = sa.getPropertyClass(); try { // If there's a valueOf(String) method, just use that // (will cover at least String, Integer, Double, // Boolean) Method valueOfMethod = null; try { valueOfMethod = valueClass.getMethod("valueOf", stringSingleton); } catch (NoSuchMethodException ex) { } if (valueOfMethod != null) { Object[] holder = { valueAsString }; value = valueOfMethod.invoke(pf, holder); } else if (realPropertyType.isEnum()) { // Special-case for enum types List<Enum> constants = Arrays.asList((Enum[]) realPropertyType.getEnumConstants()); for (Enum e : constants) { if (e.toString().equals(valueAsString)) { value = e; break; } } } else if (String.class.equals(valueClass)) { value = valueAsString; } else if (Location.class.equals(valueClass)) { LocationEditor ed = new LocationEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Concept.class.equals(valueClass)) { ConceptEditor ed = new ConceptEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Program.class.equals(valueClass)) { ProgramEditor ed = new ProgramEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (ProgramWorkflowState.class.equals(valueClass)) { ProgramWorkflowStateEditor ed = new ProgramWorkflowStateEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (EncounterType.class.equals(valueClass)) { EncounterTypeEditor ed = new EncounterTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Form.class.equals(valueClass)) { FormEditor ed = new FormEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Drug.class.equals(valueClass)) { DrugEditor ed = new DrugEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (PersonAttributeType.class.equals(valueClass)) { PersonAttributeTypeEditor ed = new PersonAttributeTypeEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Cohort.class.equals(valueClass)) { CohortEditor ed = new CohortEditor(); ed.setAsText(valueAsString); value = ed.getValue(); } else if (Date.class.equals(valueClass)) { // TODO: this uses the date format from the current // session, which could cause problems if the user // changes it after searching. DateFormat df = Context.getDateFormat(); // new // SimpleDateFormat(OpenmrsConstants.OPENMRS_LOCALE_DATE_PATTERNS().get(Context.getLocale().toString().toLowerCase()), // Context.getLocale()); CustomDateEditor ed = new CustomDateEditor(df, true, 10); ed.setAsText(valueAsString); value = ed.getValue(); } else if (LogicCriteria.class.equals(valueClass)) { value = Context.getLogicService().parseString(valueAsString); } else { // TODO: Decide whether this is a hack. Currently // setting Object arguments with a String value = valueAsString; } } catch (Exception ex) { log.error("error converting \"" + valueAsString + "\" to " + valueClass, ex); continue; } if (value != null) { if (realPropertyType.isAssignableFrom(valueClass)) { log.debug("setting value of " + sa.getName() + " to " + value); try { pd.getWriteMethod().invoke(pf, value); } catch (Exception ex) { log.error("Error setting value of " + sa.getName() + " to " + sa.getValue() + " -> " + value, ex); continue; } } else if (Collection.class.isAssignableFrom(realPropertyType)) { log.debug(sa.getName() + " is a Collection property"); // if realPropertyType is a collection, add this // value to it (possibly after instantiating) try { Collection collection = (Collection) pd.getReadMethod().invoke(pf, (Object[]) null); if (collection == null) { // we need to instantiate this collection. // I'm going with the following rules, which // should be rethought: // SortedSet -> TreeSet // Set -> HashSet // Otherwise -> ArrayList if (SortedSet.class.isAssignableFrom(realPropertyType)) { collection = new TreeSet(); log.debug("instantiated a TreeSet"); pd.getWriteMethod().invoke(pf, collection); } else if (Set.class.isAssignableFrom(realPropertyType)) { collection = new HashSet(); log.debug("instantiated a HashSet"); pd.getWriteMethod().invoke(pf, collection); } else { collection = new ArrayList(); log.debug("instantiated an ArrayList"); pd.getWriteMethod().invoke(pf, collection); } } collection.add(value); } catch (Exception ex) { log.error("Error instantiating collection for property " + sa.getName() + " whose class is " + realPropertyType, ex); continue; } } else { log.error(pf.getClass() + " . " + sa.getName() + " should be " + realPropertyType + " but is given as " + valueClass); } } } } log.debug("Returning " + pf); return pf; } }
From source file:org.kuali.rice.krad.datadictionary.DataDictionaryPropertyUtils.java
/** * This method gets the property type of the given attributeName when the bo class is an interface * This method will also work if the bo class is not an interface, * but that case requires special handling, hence a separate method getAttributeClassWhenBOIsClass * *//*w w w.j a v a2 s.com*/ private static Class<?> getAttributeClassWhenBOIsInterface(Class<?> boClass, String attributeName) { if (boClass == null) { throw new IllegalArgumentException("invalid (null) boClass"); } if (StringUtils.isBlank(attributeName)) { throw new IllegalArgumentException("invalid (blank) attributeName"); } PropertyDescriptor propertyDescriptor; String[] intermediateProperties = attributeName.split("\\."); int lastLevel = intermediateProperties.length - 1; Class currentClass = boClass; for (int i = 0; i <= lastLevel; ++i) { String currentPropertyName = intermediateProperties[i]; propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName); if (propertyDescriptor != null) { Class propertyType = propertyDescriptor.getPropertyType(); if (getLegacyDataAdapter().isExtensionAttribute(currentClass, currentPropertyName, propertyType)) { propertyType = getLegacyDataAdapter().getExtensionAttributeClass(currentClass, currentPropertyName); } if (Collection.class.isAssignableFrom(propertyType)) { // TODO: determine property type using generics type definition throw new AttributeValidationException( "Can't determine the Class of Collection elements because when the business object is an (possibly ExternalizableBusinessObject) interface."); } else { currentClass = propertyType; } } else { throw new AttributeValidationException( "Can't find getter method of " + boClass.getName() + " for property " + attributeName); } } return currentClass; }