List of usage examples for java.beans PropertyDescriptor getPropertyType
public synchronized Class<?> getPropertyType()
From source file:eu.squadd.reflections.mapper.ServiceModelTranslator.java
/** * this is Java Reflections translation method doing the magic where JAXB cannot * it is type independent as long as it is a valid java object * it cannot be an interface, abstract class and cannot use generics * // w w w . j av a2s . c o m * @param <T> * @param sourceClass - type of the source object * @param destClass - type of destination object * @param source - source object itself * @return - translated destination object */ public static <T> T transposeModel(Class sourceClass, Class<T> destClass, Object source) { Object destInstance = null; try { destInstance = ConstructorUtils.invokeConstructor(destClass, null); BeanInfo destInfo = Introspector.getBeanInfo(destClass); PropertyDescriptor[] destProps = destInfo.getPropertyDescriptors(); BeanInfo sourceInfo = Introspector.getBeanInfo(sourceClass, Object.class); PropertyDescriptor[] sourceProps = sourceInfo.getPropertyDescriptors(); for (PropertyDescriptor sourceProp : sourceProps) { String name = sourceProp.getName(); Method getter = sourceProp.getReadMethod(); Class<?> sType; try { sType = sourceProp.getPropertyType(); } catch (NullPointerException ex) { System.err .println("The type of source field cannot be determined, field skipped, name: " + name); continue; } Object sValue; try { sValue = getter.invoke(source); } catch (NullPointerException ex) { System.err.println("Cannot obtain the value from field, field skipped, name: " + name); continue; } for (PropertyDescriptor destProp : destProps) { if (destProp.getName().equals(name)) { if (assignPropertyValue(sourceProp, sValue, destProp, destInstance)) System.out.println( "Destination property assigned, source name: " + name + ", type: " + sType); else System.err.println( "Failed to assign property, source name: " + name + ", type: " + sType); break; } } } } catch (InvocationTargetException | IntrospectionException | IllegalAccessException | IllegalArgumentException | NoSuchMethodException | InstantiationException ex) { Logger.getLogger(ServiceModelTranslator.class.getName()).log(Level.SEVERE, null, ex); } return destClass.cast(destInstance); }
From source file:org.jaffa.qm.util.PropertyFilter.java
private static void getFieldList(Class clazz, List<String> fieldList, String prefix, Deque<Class> classStack) throws IntrospectionException { //To avoid recursion, bail out if the input Class has already been introspected if (classStack.contains(clazz)) { if (log.isDebugEnabled()) log.debug("Fields from " + clazz + " prefixed by " + prefix + " will be ignored, since the class has already been introspected as per the stack " + classStack);/*w w w .j a va 2 s. c o m*/ return; } else classStack.addFirst(clazz); //Introspect the input Class BeanInfo beanInfo = Introspector.getBeanInfo(clazz); if (beanInfo != null) { PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); if (pds != null) { for (PropertyDescriptor pd : pds) { if (pd.getReadMethod() != null && pd.getWriteMethod() != null) { String name = pd.getName(); String qualifieldName = prefix == null || prefix.length() == 0 ? name : prefix + '.' + name; Class type = pd.getPropertyType(); if (type.isArray()) type = type.getComponentType(); if (type == String.class || type == Boolean.class || Number.class.isAssignableFrom(type) || IDateBase.class.isAssignableFrom(type) || Currency.class.isAssignableFrom(type) || type.isPrimitive() || type.isEnum()) fieldList.add(qualifieldName); else getFieldList(type, fieldList, qualifieldName, classStack); } } } } classStack.removeFirst(); }
From source file:org.openspotlight.persist.util.SimpleNodeTypeVisitorSupport.java
@SuppressWarnings("unchecked") public static Set<SimpleNodeType> fillItems(final SimpleNodeType rootNode, final Class<? extends Annotation>... annotationsToIgnore) throws Exception { if (rootNode == null) { return Collections.emptySet(); }//from w w w. ja va 2 s . c om final Set<SimpleNodeType> itemsToVisit = new LinkedHashSet<SimpleNodeType>(); final PropertyDescriptor[] allDescriptors = PropertyUtils.getPropertyDescriptors(rootNode); looping: for (final PropertyDescriptor desc : allDescriptors) { final Method readMethod = desc.getReadMethod(); if (readMethod.isAnnotationPresent(ParentProperty.class)) { continue looping; } for (final Class<? extends Annotation> annotation : annotationsToIgnore) { if (readMethod.isAnnotationPresent(annotation)) { continue looping; } } final Class<?> currentType = desc.getPropertyType(); if (SimpleNodeType.class.isAssignableFrom(currentType)) { final SimpleNodeType bean = (SimpleNodeType) readMethod.invoke(rootNode); itemsToVisit.add(bean); } else if (Iterable.class.isAssignableFrom(currentType)) { final UnwrappedCollectionTypeFromMethodReturn<Object> metadata = Reflection .unwrapCollectionFromMethodReturn(readMethod); if (SimpleNodeType.class.isAssignableFrom(metadata.getItemType())) { final Iterable<SimpleNodeType> collection = (Iterable<SimpleNodeType>) readMethod .invoke(rootNode); if (collection != null) { for (final SimpleNodeType t : collection) { itemsToVisit.add(t); } } } } else if (Map.class.isAssignableFrom(currentType)) { final UnwrappedMapTypeFromMethodReturn<Object, Object> metadata = Reflection .unwrapMapFromMethodReturn(readMethod); if (SimpleNodeType.class.isAssignableFrom(metadata.getItemType().getK2())) { final Map<Object, SimpleNodeType> map = (Map<Object, SimpleNodeType>) readMethod .invoke(rootNode); if (map != null) { for (final Entry<Object, SimpleNodeType> entry : map.entrySet()) { itemsToVisit.add(entry.getValue()); } } } } } return itemsToVisit; }
From source file:org.kuali.rice.krad.datadictionary.DataDictionaryPropertyUtils.java
/** * This method determines the Class of the elements in the collectionName passed in. * * @param boClass Class that the collectionName collection exists in. * @param collectionName the name of the collection you want the element class for * @return collection element type// ww w . jav a2 s .c o m */ public static Class getCollectionElementClass(Class boClass, String collectionName) { if (boClass == null) { throw new IllegalArgumentException("invalid (null) boClass"); } if (StringUtils.isBlank(collectionName)) { throw new IllegalArgumentException("invalid (blank) collectionName"); } PropertyDescriptor propertyDescriptor; String[] intermediateProperties = collectionName.split("\\."); Class currentClass = boClass; for (String currentPropertyName : intermediateProperties) { propertyDescriptor = buildSimpleReadDescriptor(currentClass, currentPropertyName); if (propertyDescriptor != null) { Class type = propertyDescriptor.getPropertyType(); if (Collection.class.isAssignableFrom(type)) { currentClass = getLegacyDataAdapter().determineCollectionObjectType(currentClass, currentPropertyName); } else { currentClass = propertyDescriptor.getPropertyType(); } } } return currentClass; }
From source file:io.fabric8.devops.ProjectConfigs.java
/** * Configures the given {@link ProjectConfig} with a map of key value pairs from * something like a JBoss Forge command// ww w. ja v a 2s.com */ public static void configureProperties(ProjectConfig config, Map map) { Class<? extends ProjectConfig> clazz = config.getClass(); BeanInfo beanInfo = null; try { beanInfo = Introspector.getBeanInfo(clazz); } catch (IntrospectionException e) { LOG.warn("Could not introspect " + clazz.getName() + ". " + e, e); } if (beanInfo != null) { PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor descriptor : propertyDescriptors) { Method writeMethod = descriptor.getWriteMethod(); if (writeMethod != null) { String name = descriptor.getName(); Object value = map.get(name); if (value != null) { Object safeValue = null; Class<?> propertyType = descriptor.getPropertyType(); if (propertyType.isInstance(value)) { safeValue = value; } else { PropertyEditor editor = descriptor.createPropertyEditor(config); if (editor == null) { editor = PropertyEditorManager.findEditor(propertyType); } if (editor != null) { String text = value.toString(); editor.setAsText(text); safeValue = editor.getValue(); } else { LOG.warn("Cannot update property " + name + " with value " + value + " of type " + propertyType.getName() + " on " + clazz.getName()); } } if (safeValue != null) { try { writeMethod.invoke(config, safeValue); } catch (Exception e) { LOG.warn("Failed to set property " + name + " with value " + value + " on " + clazz.getName() + " " + config + ". " + e, e); } } } } } } String flow = null; Object flowValue = map.get("pipeline"); if (flowValue == null) { flowValue = map.get("flow"); } if (flowValue != null) { flow = flowValue.toString(); } config.setPipeline(flow); }
From source file:io.github.moosbusch.lumpi.util.LumpiUtil.java
public static Class<?> getPropertyType(Class<?> type, String propertyName) { String[] propertyTokens = StringUtils.split(propertyName, "."); Class<?> result = type; for (String propertyToken : propertyTokens) { PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(result); for (PropertyDescriptor descriptor : descriptors) { if (StringUtils.equalsIgnoreCase(propertyToken, descriptor.getName())) { result = descriptor.getPropertyType(); break; } else { result = null;//from w ww . ja v a 2 s .c o m } } } return result; }
From source file:org.grails.beans.support.CachedIntrospectionResults.java
/** * Compare the given {@code PropertyDescriptors} and return {@code true} if * they are equivalent, i.e. their read method, write method, property type, * property editor and flags are equivalent. * @see java.beans.PropertyDescriptor#equals(Object) *///from w ww . j av a 2 s . co m public static boolean equals(PropertyDescriptor pd, PropertyDescriptor otherPd) { return (ObjectUtils.nullSafeEquals(pd.getReadMethod(), otherPd.getReadMethod()) && ObjectUtils.nullSafeEquals(pd.getWriteMethod(), otherPd.getWriteMethod()) && ObjectUtils.nullSafeEquals(pd.getPropertyType(), otherPd.getPropertyType()) && ObjectUtils.nullSafeEquals(pd.getPropertyEditorClass(), otherPd.getPropertyEditorClass()) && pd.isBound() == otherPd.isBound() && pd.isConstrained() == otherPd.isConstrained()); }
From source file:com.glaf.core.util.Tools.java
@SuppressWarnings("unchecked") public static void populate(Object model, Map<String, Object> dataMap) { if (model instanceof Map) { Map<String, Object> map = (Map<String, Object>) model; Set<Entry<String, Object>> entrySet = map.entrySet(); for (Entry<String, Object> entry : entrySet) { String key = entry.getKey(); if (dataMap.containsKey(key)) { map.put(key, dataMap.get(key)); }/* w w w. j a va2 s . co m*/ } } else { PropertyDescriptor[] propertyDescriptor = BeanUtils.getPropertyDescriptors(model.getClass()); for (int i = 0; i < propertyDescriptor.length; i++) { PropertyDescriptor descriptor = propertyDescriptor[i]; String propertyName = descriptor.getName(); if (propertyName.equalsIgnoreCase("class")) { continue; } String value = null; Object x = null; Object object = dataMap.get(propertyName); if (object != null && object instanceof String) { value = (String) object; } try { Class<?> clazz = descriptor.getPropertyType(); if (value != null) { x = getValue(clazz, value); } else { x = object; } if (x != null) { // PropertyUtils.setProperty(model, propertyName, x); ReflectUtils.setFieldValue(model, propertyName, x); } } catch (Exception ex) { logger.debug(ex); } } } }
From source file:cn.fql.utility.ClassUtility.java
/** * Export property value of specified object to a map * * @param obj object instance * @param isWithNullable denote whether it is required to skip null value * @return map instance includes property value *//*www . j a va 2s. co m*/ public static Map collectAsMap(Object obj, boolean isWithNullable) { Map mapOutput = new HashMap(); PropertyDescriptor[] pds; try { pds = exportPropertyDesc(obj.getClass()); for (int i = 0; i < pds.length; i++) { PropertyDescriptor pd = pds[i]; Method getter = pd.getReadMethod(); if (getter != null && !pd.getName().equals("class")) { Object value = getter.invoke(obj); if (value == null) { if (!isWithNullable) { continue; } } if (pd.getPropertyType().equals(String.class) && value == null) { value = ""; } mapOutput.put(pd.getName(), value); } } } catch (Exception e) { System.out.println(e.getMessage()); } return mapOutput; }
From source file:org.bibsonomy.layout.util.JabRefModelConverter.java
/** * Converts a BibSonomy post into a JabRef BibtexEntry * /*from ww w .ja v a 2 s .c o m*/ * @param post * @param urlGen * - the URLGenerator to create the biburl-field * @return */ public static BibtexEntry convertPost(final Post<? extends Resource> post, URLGenerator urlGen) { try { /* * what we have */ final BibTex bibtex = (BibTex) post.getResource(); /* * what we want */ final BibtexEntry entry = new BibtexEntry(); /* * each entry needs an ID (otherwise we get a NPE) ... let JabRef * generate it */ /* * we use introspection to get all fields ... */ final BeanInfo info = Introspector.getBeanInfo(bibtex.getClass()); final PropertyDescriptor[] descriptors = info.getPropertyDescriptors(); /* * iterate over all properties */ for (final PropertyDescriptor pd : descriptors) { final Method getter = pd.getReadMethod(); // loop over all String attributes final Object o = getter.invoke(bibtex, (Object[]) null); if (String.class.equals(pd.getPropertyType()) && (o != null) && !JabRefModelConverter.EXCLUDE_FIELDS.contains(pd.getName())) { final String value = ((String) o); if (present(value)) entry.setField(pd.getName().toLowerCase(), value); } } /* * convert entry type (Is never null but getType() returns null for * unknown types and JabRef knows less types than we.) * * FIXME: a nicer solution would be to implement the corresponding * classes for the missing entrytypes. */ final BibtexEntryType entryType = BibtexEntryType.getType(bibtex.getEntrytype()); entry.setType(entryType == null ? BibtexEntryType.OTHER : entryType); if (present(bibtex.getMisc()) || present(bibtex.getMiscFields())) { // parse the misc fields and loop over them bibtex.parseMiscField(); if (bibtex.getMiscFields() != null) for (final String key : bibtex.getMiscFields().keySet()) { if ("id".equals(key)) { // id is used by jabref entry.setField("misc_id", bibtex.getMiscField(key)); continue; } if (key.startsWith("__")) // ignore fields starting with // __ - jabref uses them for // control continue; entry.setField(key, bibtex.getMiscField(key)); } } final String month = bibtex.getMonth(); if (present(month)) { /* * try to convert the month abbrev like JabRef does it */ final String longMonth = Globals.MONTH_STRINGS.get(month); if (present(longMonth)) { entry.setField("month", longMonth); } else { entry.setField("month", month); } } final String bibAbstract = bibtex.getAbstract(); if (present(bibAbstract)) entry.setField("abstract", bibAbstract); /* * concatenate tags using the JabRef keyword separator */ final Set<Tag> tags = post.getTags(); final StringBuffer tagsBuffer = new StringBuffer(); for (final Tag tag : tags) { tagsBuffer.append(tag.getName() + jabRefKeywordSeparator); } /* * remove last separator */ if (!tags.isEmpty()) { tagsBuffer.delete(tagsBuffer.lastIndexOf(jabRefKeywordSeparator), tagsBuffer.length()); } final String tagsBufferString = tagsBuffer.toString(); if (present(tagsBufferString)) entry.setField(BibTexUtils.ADDITIONAL_MISC_FIELD_KEYWORDS, tagsBufferString); // set groups - will be used in jabref when exporting to bibsonomy if (present(post.getGroups())) { final Set<Group> groups = post.getGroups(); final StringBuffer groupsBuffer = new StringBuffer(); for (final Group group : groups) groupsBuffer.append(group.getName() + " "); final String groupsBufferString = groupsBuffer.toString().trim(); if (present(groupsBufferString)) entry.setField("groups", groupsBufferString); } // set comment + description final String description = post.getDescription(); if (present(description)) { entry.setField(BibTexUtils.ADDITIONAL_MISC_FIELD_DESCRIPTION, post.getDescription()); entry.setField("comment", post.getDescription()); } if (present(post.getDate())) { entry.setField("added-at", sdf.format(post.getDate())); } if (present(post.getChangeDate())) { entry.setField("timestamp", sdf.format(post.getChangeDate())); } if (present(post.getUser())) entry.setField("username", post.getUser().getName()); // set URL to bibtex version of this entry (bibrecord = ...) entry.setField(BibTexUtils.ADDITIONAL_MISC_FIELD_BIBURL, urlGen.getPublicationUrl(bibtex, post.getUser()).toString()); return entry; } catch (final Exception e) { log.error("Could not convert BibSonomy post into a JabRef BibTeX entry.", e); } return null; }