List of usage examples for java.beans PropertyDescriptor getName
public String getName()
From source file:com.emc.ecs.sync.config.ConfigUtil.java
/** * convert an annotated getter into a commons-cli Option */// w w w. j av a 2 s .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:com.github.dozermapper.core.util.ReflectionUtils.java
static PropertyDescriptor[] getInterfacePropertyDescriptors(Class<?> interfaceClass) { List<PropertyDescriptor> propDescriptors = new ArrayList<>(); // Add prop descriptors for interface passed in propDescriptors.addAll(Arrays.asList(PropertyUtils.getPropertyDescriptors(interfaceClass))); // Look for interface inheritance. If super interfaces are found, recurse up the hierarchy tree and add prop // descriptors for each interface found. // PropertyUtils.getPropertyDescriptors() does not correctly walk the inheritance hierarchy for interfaces. Class<?>[] interfaces = interfaceClass.getInterfaces(); if (interfaces != null) { for (Class<?> superInterfaceClass : interfaces) { List<PropertyDescriptor> superInterfacePropertyDescriptors = Arrays .asList(getInterfacePropertyDescriptors(superInterfaceClass)); /*/*from w ww.ja v a 2 s. c om*/ * #1814758 * Check for existing descriptor with the same name to prevent 2 property descriptors with the same name being added * to the result list. This caused issues when getter and setter of an attribute on different interfaces in * an inheritance hierarchy */ for (PropertyDescriptor superPropDescriptor : superInterfacePropertyDescriptors) { PropertyDescriptor existingPropDescriptor = findPropDescriptorByName(propDescriptors, superPropDescriptor.getName()); if (existingPropDescriptor == null) { propDescriptors.add(superPropDescriptor); } else { try { if (existingPropDescriptor.getReadMethod() == null) { existingPropDescriptor.setReadMethod(superPropDescriptor.getReadMethod()); } if (existingPropDescriptor.getWriteMethod() == null) { existingPropDescriptor.setWriteMethod(superPropDescriptor.getWriteMethod()); } } catch (IntrospectionException e) { throw new MappingException(e); } } } } } return propDescriptors.toArray(new PropertyDescriptor[propDescriptors.size()]); }
From source file:org.paxml.util.ReflectUtils.java
/** * Get a specific type of property descriptors, except the "class" property. * //from w w w . j a v a 2 s . c om * @param clazz * the class * @param type * the type filter, null means no filtering * @return the list of property descriptors. */ public static List<PropertyDescriptor> getPropertyDescriptors(Class clazz, PropertyDescriptorType type) { List<PropertyDescriptor> list = new ArrayList<PropertyDescriptor>(); for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(clazz)) { if ("class".equals(pd.getName())) { continue; } switch (type) { case GETTER: if (pd.getReadMethod() != null) { list.add(pd); } break; case SETTER: if (pd.getWriteMethod() != null) { list.add(pd); } break; default: list.add(pd); } } return list; }
From source file:com.unboundid.scim2.common.utils.SchemaUtils.java
/** * Gets SCIM schema attributes for a class. * * @param classesProcessed a stack containing the classes processed prior * to this class. This is used for cycle detection. * @param cls the class to get the attributes for. * @return a collection of SCIM schema attributes for the class. * @throws IntrospectionException thrown if an error occurs during * Introspection.//from ww w.j av a2 s .com */ private static Collection<AttributeDefinition> getAttributes(final Stack<String> classesProcessed, final Class<?> cls) throws IntrospectionException { String className = cls.getCanonicalName(); if (!cls.isAssignableFrom(AttributeDefinition.class) && classesProcessed.contains(className)) { throw new RuntimeException("Cycles detected in Schema"); } Collection<PropertyDescriptor> propertyDescriptors = getPropertyDescriptors(cls); Collection<AttributeDefinition> attributes = new ArrayList<AttributeDefinition>(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { if (propertyDescriptor.getName().equals("subAttributes") && cls.isAssignableFrom(AttributeDefinition.class) && classesProcessed.contains(className)) { // Skip second nesting of subAttributes the second time around // since there is no subAttributes of subAttributes in SCIM. continue; } AttributeDefinition.Builder attributeBuilder = new AttributeDefinition.Builder(); Field field = findField(cls, propertyDescriptor.getName()); if (field == null) { continue; } Attribute schemaProperty = null; JsonProperty jsonProperty = null; if (field.isAnnotationPresent(Attribute.class)) { schemaProperty = field.getAnnotation(Attribute.class); } if (field.isAnnotationPresent(JsonProperty.class)) { jsonProperty = field.getAnnotation(JsonProperty.class); } // Only generate schema for annotated fields. if (schemaProperty == null) { continue; } addName(attributeBuilder, propertyDescriptor, jsonProperty); addDescription(attributeBuilder, schemaProperty); addCaseExact(attributeBuilder, schemaProperty); addRequired(attributeBuilder, schemaProperty); addReturned(attributeBuilder, schemaProperty); addUniqueness(attributeBuilder, schemaProperty); addReferenceTypes(attributeBuilder, schemaProperty); addMutability(attributeBuilder, schemaProperty); addMultiValued(attributeBuilder, propertyDescriptor, schemaProperty); addCanonicalValues(attributeBuilder, schemaProperty); Class propertyCls = propertyDescriptor.getPropertyType(); // if this is a multivalued attribute the real sub attribute class is the // the one specified in the annotation, not the list, set, array, etc. if ((schemaProperty.multiValueClass() != NullType.class)) { propertyCls = schemaProperty.multiValueClass(); } AttributeDefinition.Type type = getAttributeType(propertyCls); attributeBuilder.setType(type); if (type == AttributeDefinition.Type.COMPLEX) { // Add this class to the list to allow cycle detection classesProcessed.push(cls.getCanonicalName()); Collection<AttributeDefinition> subAttributes = getAttributes(classesProcessed, propertyCls); attributeBuilder .addSubAttributes(subAttributes.toArray(new AttributeDefinition[subAttributes.size()])); classesProcessed.pop(); } attributes.add(attributeBuilder.build()); } return attributes; }
From source file:de.micromata.genome.jpa.PropertyEntityCopier.java
/** * Write property./*from ww w. j a v a 2s . c om*/ * * @param entity the entity * @param pd the pd * @param value the value * @return true when writing the property was a success */ public static boolean writeProperty(Object entity, PropertyDescriptor pd, Object value) { try { PropertyDescriptorUtils.writeProperty(entity, pd, value); return true; } catch (PropertyAccessException ex) { /** * @logging * @reason Das interne Schreiben einer Objekteigenschaft ist nicht mglich. * @action Interner Fehler. Entwickler / Support kontaktieren. */ GLog.warn(GenomeLogCategory.Jpa, "Cannot write bean property: " + entity.getClass().getSimpleName() + DOT + pd.getName() + SEMICOLON_SPACE + ex.getMessage(), new LogExceptionAttribute(ex)); return false; } }
From source file:de.escalon.hypermedia.spring.uber.UberUtils.java
/** * Renders input fields for bean properties of bean to add or update or patch. * * @param uberFields// w w w.java2 s. c o m * to add to * @param beanType * to render * @param annotatedParameters * which describes the method * @param annotatedParameter * which requires the bean * @param currentCallValue * sample call value */ private static void recurseBeanCreationParams(List<UberField> uberFields, Class<?> beanType, ActionDescriptor annotatedParameters, ActionInputParameter annotatedParameter, Object currentCallValue, String parentParamName, Set<String> knownFields) { // TODO collection, map and object node creation are only describable by an annotation, not via type reflection if (ObjectNode.class.isAssignableFrom(beanType) || Map.class.isAssignableFrom(beanType) || Collection.class.isAssignableFrom(beanType) || beanType.isArray()) { return; // use @Input(include) to list parameter names, at least? Or mix with hdiv's form builder? } try { Constructor[] constructors = beanType.getConstructors(); // find default ctor Constructor constructor = PropertyUtils.findDefaultCtor(constructors); // find ctor with JsonCreator ann if (constructor == null) { constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class); } Assert.notNull(constructor, "no default constructor or JsonCreator found for type " + beanType.getName()); int parameterCount = constructor.getParameterTypes().length; if (parameterCount > 0) { Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations(); Class[] parameters = constructor.getParameterTypes(); int paramIndex = 0; for (Annotation[] annotationsOnParameter : annotationsOnParameters) { for (Annotation annotation : annotationsOnParameter) { if (JsonProperty.class == annotation.annotationType()) { JsonProperty jsonProperty = (JsonProperty) annotation; // TODO use required attribute of JsonProperty for required fields String paramName = jsonProperty.value(); Class parameterType = parameters[paramIndex]; Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, paramName); MethodParameter methodParameter = new MethodParameter(constructor, paramIndex); addUberFieldsForMethodParameter(uberFields, methodParameter, annotatedParameter, annotatedParameters, parentParamName, paramName, parameterType, propertyValue, knownFields); paramIndex++; // increase for each @JsonProperty } } } Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator " + constructor.getName() + " are annotated with @JsonProperty"); } Set<String> knownConstructorFields = new HashSet<String>(uberFields.size()); for (UberField sirenField : uberFields) { knownConstructorFields.add(sirenField.getName()); } // TODO support Option provider by other method args? Map<String, PropertyDescriptor> propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanType); // add input field for every setter for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) { final Method writeMethod = propertyDescriptor.getWriteMethod(); String propertyName = propertyDescriptor.getName(); if (writeMethod == null || knownFields.contains(parentParamName + propertyName)) { continue; } final Class<?> propertyType = propertyDescriptor.getPropertyType(); Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, propertyName); MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0); addUberFieldsForMethodParameter(uberFields, methodParameter, annotatedParameter, annotatedParameters, parentParamName, propertyName, propertyType, propertyValue, knownConstructorFields); } } catch (Exception e) { throw new RuntimeException("Failed to write input fields for constructor", e); } }
From source file:cn.teamlab.wg.framework.util.csv.CsvWriter.java
/** * Bean?CSV?//from ww w . j a va2s . com * Bean@CsvPropAnno(index = ?) * @param objList * @return * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ public static String bean2Csv(List<?> objList) throws Exception { if (objList == null || objList.size() == 0) { return ""; } TreeMap<Integer, CsvFieldBean> map = new TreeMap<Integer, CsvFieldBean>(); Object bean0 = objList.get(0); Class<?> clazz = bean0.getClass(); PropertyDescriptor[] arr = org.springframework.beans.BeanUtils.getPropertyDescriptors(clazz); for (PropertyDescriptor p : arr) { String fieldName = p.getName(); Field field = FieldUtils.getDeclaredField(clazz, fieldName, true); if (field == null) { continue; } boolean isAnno = field.isAnnotationPresent(CsvFieldAnno.class); if (isAnno) { CsvFieldAnno anno = field.getAnnotation(CsvFieldAnno.class); int idx = anno.index(); map.put(idx, new CsvFieldBean(idx, anno.title(), fieldName)); } } // CSVBuffer StringBuffer buff = new StringBuffer(); // ??? boolean withTitle = clazz.isAnnotationPresent(CsvTitleAnno.class); // ??csv if (withTitle) { StringBuffer titleBuff = new StringBuffer(); for (int key : map.keySet()) { CsvFieldBean fieldBean = map.get(key); titleBuff.append(Letters.QUOTE).append(fieldBean.getTitle()).append(Letters.QUOTE); titleBuff.append(Letters.COMMA); } buff.append(StringUtils.chop(titleBuff.toString())); buff.append(Letters.LF); titleBuff.setLength(0); } for (Object o : objList) { StringBuffer tmpBuff = new StringBuffer(); for (int key : map.keySet()) { CsvFieldBean fieldBean = map.get(key); Object val = BeanUtils.getProperty(o, fieldBean.getFieldName()); if (val != null) { tmpBuff.append(Letters.QUOTE).append(val).append(Letters.QUOTE); } else { tmpBuff.append(StringUtils.EMPTY); } tmpBuff.append(Letters.COMMA); } buff.append(StringUtils.chop(tmpBuff.toString())); buff.append(Letters.LF); tmpBuff.setLength(0); } return buff.toString(); }
From source file:jp.terasoluna.fw.web.struts.actions.FileDownloadUtil.java
/** * uEU_E??[h?B//from w w w . j av a2 s .c o m * * @param result _E??[hf?[^?CX^X?B * @param request NGXg?B * @param response X|X?B */ @SuppressWarnings("unchecked") public static void download(Object result, HttpServletRequest request, HttpServletResponse response) { List<AbstractDownloadObject> downloadList = new ArrayList<AbstractDownloadObject>(); if (result instanceof AbstractDownloadObject) { downloadList.add((AbstractDownloadObject) result); } else { BeanWrapper wrapper = new BeanWrapperImpl(result); PropertyDescriptor[] propertyDescriptors = wrapper.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod == null) { continue; } Class type = readMethod.getReturnType(); if (AbstractDownloadObject.class.isAssignableFrom(type)) { downloadList .add((AbstractDownloadObject) wrapper.getPropertyValue(propertyDescriptor.getName())); } } } if (downloadList.isEmpty()) { return; } // _E??[hIuWFNg???O if (downloadList.size() != 1) { throw new SystemException(new IllegalStateException("Too many AbstractDownloadObject properties."), TOO_MANY_DOWNLOAD_ERROR); } try { download(downloadList.get(0), request, response, true); } catch (SocketException e) { if (log.isDebugEnabled()) { log.debug(e.getMessage(), e); } } catch (IOException e) { if (log.isErrorEnabled()) { log.error("IOException has occurred while downloading", e); } } }
From source file:gr.interamerican.bo2.utils.JavaBeanUtils.java
/** * Copies all common properties of an object to another excluding some properties. * /*from ww w . j a va 2s .c om*/ * @see #copyProperties(Object, Object, String[]) * * @param source * Object who's properties will be copied to the target object. * @param target * Object to which the properties will be copied. * @param excluded * List of properties to exclude. */ public static void copyPropertiesExcluding(Object source, Object target, String[] excluded) { if (excluded == null || excluded.length == 0) { copyProperties(source, target, null); return; } PropertyDescriptor[] sourceProperties = JavaBeanUtils.getBeansProperties(source.getClass()); Set<String> properties = new HashSet<String>(); for (PropertyDescriptor pd : sourceProperties) { String property = pd.getName(); if (StringUtils.arrayContainsString(excluded, property) == -1) { properties.add(property); } } if (properties.size() == 0) { return; } copyProperties(source, target, properties.toArray(new String[] {})); }
From source file:de.micromata.genome.jpa.PropertyEntityCopier.java
/** * Copy property./*from w ww .j a va2s . c o m*/ * * @param pd the pd * @param target the target * @param source the source * @return the {@link EntityCopyStatus} */ public static EntityCopyStatus copyPropertyRaw(PropertyDescriptor pd, Object target, Object source) { Object value = null; try { value = PropertyDescriptorUtils.readProperty(source, pd); } catch (PropertyAccessException ex) { /** * @logging * @reason Das interne Lesen einer Objekteigenschaft ist nicht mglich. * @action Interner Fehler. Entwickler / Support kontaktieren. */ GLog.warn(GenomeLogCategory.Jpa, "Cannot read bean property: " + source.getClass().getSimpleName() + DOT + pd.getName() + SEMICOLON_SPACE + ex.getMessage(), new LogExceptionAttribute(ex)); return EntityCopyStatus.NONE; } Object backupValue = null; try { backupValue = PropertyDescriptorUtils.readProperty(target, pd); } catch (PropertyAccessException ex) { /** * @logging * @reason Das interne Lesen einer Objekteigenschaft ist nicht mglich. * @action Interner Fehler. Entwickler / Support kontaktieren. */ GLog.warn(GenomeLogCategory.Jpa, "Cannot read bean property: " + target.getClass().getSimpleName() + DOT + pd.getName() + SEMICOLON_SPACE + ex.getMessage(), new LogExceptionAttribute(ex)); return EntityCopyStatus.NONE; } EntityCopyStatus ret = EntityCopyStatus.NONE; if (Objects.equals(value, backupValue) == false) { ret = EntityCopyStatus.MAJOR; } if (writeProperty(target, pd, value) == false) { return EntityCopyStatus.NONE; } return ret; }