List of usage examples for java.beans Introspector getBeanInfo
public static BeanInfo getBeanInfo(Class<?> beanClass) throws IntrospectionException
From source file:BeanVector.java
/** * Filters a property using the Comparable.compareTo() on the porperty to * test for a range/*w w w . j a v a2s . c o m*/ * @param propertyName property to filter on * @param inclusive include the values of the range limiters * @param fromValue low range value * @param toValue high range value * @throws java.lang.IllegalAccessException reflection exception * @throws java.beans.IntrospectionException reflection exception * @throws java.lang.reflect.InvocationTargetException reflection exception * @return new BeanVector filtered on the range */ public BeanVector<T> getFiltered(String propertyName, boolean inclusive, Comparable fromValue, Comparable toValue) throws java.lang.IllegalAccessException, java.beans.IntrospectionException, java.lang.reflect.InvocationTargetException { Hashtable cache = new Hashtable(); String currentClass = ""; PropertyDescriptor pd = null; BeanVector<T> results = new BeanVector<T>(); for (int i = 0; i < this.size(); i++) { T o = this.elementAt(i); if (!currentClass.equals(o.getClass().getName())) { pd = (PropertyDescriptor) cache.get(o.getClass().getName()); if (pd == null) { 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]; cache.put(o.getClass().getName(), pd); foundProperty = true; } } } } Comparable value = (Comparable) pd.getReadMethod().invoke(o); if ((value.compareTo(fromValue) > 0) && (value.compareTo(toValue) < 0)) { results.add(o); } else if (inclusive && ((value.compareTo(fromValue) == 0) || (value.compareTo(toValue) == 0))) { results.add(o); } } return results; }
From source file:BeanArrayList.java
/** * Filters a property using the Comparable.compareTo() on the porperty to * test for a range/* w ww. ja va2 s. c o m*/ * @param propertyName property to filter on * @param inclusive include the values of the range limiters * @param fromValue low range value * @param toValue high range value * @throws java.lang.IllegalAccessException reflection exception * @throws java.beans.IntrospectionException reflection exception * @throws java.lang.reflect.InvocationTargetException reflection exception * @return new BeanArrayList filtered on the range */ public BeanArrayList<T> getFiltered(String propertyName, boolean inclusive, Comparable fromValue, Comparable toValue) throws java.lang.IllegalAccessException, java.beans.IntrospectionException, java.lang.reflect.InvocationTargetException { HashMap cache = new HashMap(); String currentClass = ""; PropertyDescriptor pd = null; BeanArrayList<T> results = new BeanArrayList<T>(); for (int i = 0; i < this.size(); i++) { T o = this.get(i); if (!currentClass.equals(o.getClass().getName())) { pd = (PropertyDescriptor) cache.get(o.getClass().getName()); if (pd == null) { 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]; cache.put(o.getClass().getName(), pd); foundProperty = true; } } } } Comparable value = (Comparable) pd.getReadMethod().invoke(o); if ((value.compareTo(fromValue) > 0) && (value.compareTo(toValue) < 0)) { results.add(o); } else if (inclusive && ((value.compareTo(fromValue) == 0) || (value.compareTo(toValue) == 0))) { results.add(o); } } return results; }
From source file:com.kangdainfo.common.util.BeanUtil.java
public static Class getPropertyType(Object o, String propertyName) throws Exception { PropertyDescriptor[] pds = Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors(); for (int i = 0; i < pds.length; i++) { if (pds[i].getName().equals(propertyName)) { return pds[i].getPropertyType(); }/*from w ww .ja va 2s . c om*/ } throw new Exception("Property not found."); }
From source file:org.tros.utils.PropertiesInitializer.java
/** * Initialize from JSON if possible.//from w w w .j ava 2s .c o m */ private void initializeFromJson() { try { java.util.Enumeration<URL> resources = ClassLoader.getSystemClassLoader() .getResources(this.getClass().getCanonicalName().replace('.', '/') + ".json"); ArrayList<URL> urls = new ArrayList<>(); //HACK: semi sort classpath to put "files" first and "jars" second. //this has an impact once we are workin in tomcat where //the classes in tomcat are not stored in a jar. while (resources.hasMoreElements()) { URL url = resources.nextElement(); if (url.toString().startsWith("file:")) { urls.add(0, url); } else { boolean added = false; for (int ii = 0; !added && ii < urls.size(); ii++) { if (!urls.get(ii).toString().startsWith("file:")) { urls.add(ii, url); added = true; } } if (!added) { urls.add(url); } } } //reverse the list, so that the item found first in the //classpath will be the last one run though and thus //be the one to set the final value Collections.reverse(urls); PropertyDescriptor[] props = Introspector.getBeanInfo(this.getClass()).getPropertyDescriptors(); for (URL url : urls) { try { PropertiesInitializer obj = (PropertiesInitializer) readValue(url.openStream(), this.getClass()); for (PropertyDescriptor p : props) { if (p.getWriteMethod() != null && p.getReadMethod() != null && p.getReadMethod().getDeclaringClass() != Object.class) { Object val = p.getReadMethod().invoke(obj); if (val != null) { p.getWriteMethod().invoke(this, val); } } } } catch (NullPointerException | IOException | IllegalArgumentException | InvocationTargetException | IllegalAccessException ex) { LOGGER.debug(null, ex); } } } catch (IOException ex) { } catch (IntrospectionException ex) { LOGGER.warn(null, ex); } }
From source file:org.rhq.cassandra.DeploymentOptions.java
public TokenReplacingProperties toMap() { try {/* w w w .ja va 2 s .c o m*/ BeanInfo beanInfo = Introspector.getBeanInfo(DeploymentOptions.class); Map<String, String> properties = new TreeMap<String, String>(); for (PropertyDescriptor pd : beanInfo.getPropertyDescriptors()) { if (pd.getReadMethod() == null) { throw new RuntimeException("The [" + pd.getName() + "] property must define a getter method"); } Method method = pd.getReadMethod(); DeploymentProperty deploymentProperty = method.getAnnotation(DeploymentProperty.class); if (deploymentProperty != null) { Object value = method.invoke(this, null); if (value != null) { properties.put(deploymentProperty.name(), value.toString()); } } } return new TokenReplacingProperties(properties); } catch (Exception e) { throw new RuntimeException("Failed to convert " + DeploymentOptions.class.getName() + " to a map", e); } }
From source file:org.obiba.onyx.jade.instrument.gemac800.CardiosoftInstrumentRunner.java
/** * Place the results and xml file into a map object to send them to the server for persistence * * @param resultParser// w w w.j a v a 2s . c o m * @throws Exception */ public void sendDataToServer(CardiosoftInstrumentResultParser resultParser) { Map<String, Data> outputToSend = new HashMap<String, Data>(); try { for (PropertyDescriptor pd : Introspector.getBeanInfo(CardiosoftInstrumentResultParser.class) .getPropertyDescriptors()) { if (instrumentExecutionService.hasOutputParameter(pd.getName())) { Object value = pd.getReadMethod().invoke(resultParser); if (value != null) { if (value instanceof Long) { // We need to subtract one to the birthday month since the month of January is represented by "0" in // java.util.Calendar (January is represented by "1" in Cardiosoft). if (pd.getName().equals("participantBirthMonth")) { outputToSend.put(pd.getName(), DataBuilder.buildInteger(((Long) value) - 1)); } else { outputToSend.put(pd.getName(), DataBuilder.buildInteger((Long) value)); } } else if (value instanceof Double) { outputToSend.put(pd.getName(), DataBuilder.buildDecimal((Double) value)); } else { outputToSend.put(pd.getName(), DataBuilder.buildText(value.toString())); } } else { // send null values as well (ONYX-585) log.info("Output parameter " + pd.getName() + " was null; will send null to server"); if (pd.getPropertyType().isAssignableFrom(Long.class)) { log.info("Output parameter " + pd.getName() + " is of type INTEGER"); outputToSend.put(pd.getName(), new Data(DataType.INTEGER, null)); } else if (pd.getPropertyType().isAssignableFrom(Double.class)) { log.info("Output parameter " + pd.getName() + " is of type DECIMAL"); outputToSend.put(pd.getName(), new Data(DataType.DECIMAL, null)); } else { log.info("Output parameter " + pd.getName() + " is of type TEXT"); outputToSend.put(pd.getName(), new Data(DataType.TEXT, null)); } } } } // Save the xml and pdf files File xmlFile = new File(getExportPath(), getXmlFileName()); outputToSend.put("xmlFile", DataBuilder.buildBinary(xmlFile)); instrumentExecutionService.addOutputParameterValues(outputToSend); } catch (Exception e) { log.debug("Sending data to server failed.", e); throw new RuntimeException(e); } }
From source file:com.github.erchu.beancp.commons.NameBasedMapConvention.java
@Override public List<Binding> getBindings(final MappingInfo mappingsInfo, final Class sourceClass, final Class destinationClass) { List<Binding> result = new LinkedList<>(); BeanInfo sourceBeanInfo, destinationBeanInfo; try {/*w ww . j a v a2s . c o m*/ destinationBeanInfo = Introspector.getBeanInfo(destinationClass); } catch (IntrospectionException ex) { throw new MappingException(String.format("Failed to get bean info for %s", destinationClass), ex); } try { sourceBeanInfo = Introspector.getBeanInfo(sourceClass); } catch (IntrospectionException ex) { throw new MappingException(String.format("Failed to get bean info for %s", sourceClass), ex); } boolean allDestinationMembersMapped = true; for (PropertyDescriptor destinationProperty : destinationBeanInfo.getPropertyDescriptors()) { Method destinationMember = destinationProperty.getWriteMethod(); if (destinationMember != null) { BindingSide destinationBindingSide = new PropertyBindingSide(destinationProperty); if (isDestinationMemberExpectedToBind(destinationBindingSide) == false) { continue; } List<BindingSide> sourceBindingSide = getMatchingSourceMemberByName(sourceBeanInfo, sourceClass, destinationProperty.getName(), MemberAccessType.PROPERTY); if (sourceBindingSide != null) { BindingSide[] sourceBindingSideArray = sourceBindingSide.stream().toArray(BindingSide[]::new); Binding binding = getBindingIfAvailable(sourceClass, destinationClass, mappingsInfo, sourceBindingSideArray, destinationBindingSide); if (binding != null) { result.add(binding); } } else { allDestinationMembersMapped = false; } } } for (Field destinationMember : destinationClass.getFields()) { BindingSide destinationBindingSide = new FieldBindingSide(destinationMember); if (isDestinationMemberExpectedToBind(destinationBindingSide) == false) { continue; } List<BindingSide> sourceBindingSide = getMatchingSourceMemberByName(sourceBeanInfo, sourceClass, destinationMember.getName(), MemberAccessType.FIELD); if (sourceBindingSide != null) { BindingSide[] sourceBindingSideArray = sourceBindingSide.stream().toArray(BindingSide[]::new); Binding binding = getBindingIfAvailable(sourceClass, destinationClass, mappingsInfo, sourceBindingSideArray, destinationBindingSide); if (binding != null) { result.add(binding); } } else { allDestinationMembersMapped = false; } } if (_failIfNotAllDestinationMembersMapped) { if (allDestinationMembersMapped == false) { throw new MapperConfigurationException( "Not all destination members are mapped." + " This exception has been trown because " + "failIfNotAllDestinationMembersMapped option is enabled."); } } if (_failIfNotAllSourceMembersMapped) { boolean allSourceMembersMapped = true; for (PropertyDescriptor sourceProperty : sourceBeanInfo.getPropertyDescriptors()) { Method sourceMember = sourceProperty.getReadMethod(); if (sourceMember != null) { if (sourceMember.getDeclaringClass().equals(Object.class)) { continue; } BindingSide sourceBindingSide = new PropertyBindingSide(sourceProperty); if (isSourceMemberMapped(result, sourceBindingSide) == false) { allSourceMembersMapped = false; break; } } } // if all properties are mapped we still need to check fields if (allSourceMembersMapped) { for (Field sourceMember : sourceClass.getFields()) { if (sourceMember.getDeclaringClass().equals(Object.class)) { continue; } BindingSide sourceBindingSide = new FieldBindingSide(sourceMember); if (isSourceMemberMapped(result, sourceBindingSide) == false) { allSourceMembersMapped = false; break; } } } if (allSourceMembersMapped == false) { throw new MapperConfigurationException( "Not all source members are mapped." + " This exception has been trown because " + "failIfNotAllSourceMembersMapped option is enabled."); } } return result; }
From source file:org.jcronjob.agent.AgentProcessor.java
private Map<String, String> serializableToMap(Object obj) { if (isEmpty(obj)) return Collections.EMPTY_MAP; Map<String, String> resultMap = new HashMap<String, String>(0); // /* ww w.j av a2 s . c om*/ try { PropertyDescriptor[] pds = Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors(); for (int index = 0; pds.length > 1 && index < pds.length; index++) { if (Class.class == pds[index].getPropertyType() || pds[index].getReadMethod() == null) { continue; } Object value = pds[index].getReadMethod().invoke(obj); if (notEmpty(value)) { if (isPrototype(pds[index].getPropertyType())//java() || pds[index].getPropertyType().isPrimitive()// || ReflectUitls.isPrimitivePackageType(pds[index].getPropertyType()) || pds[index].getPropertyType() == String.class) { resultMap.put(pds[index].getName(), value.toString()); } else { resultMap.put(pds[index].getName(), JSON.toJSONString(value)); } } } } catch (Exception e) { e.printStackTrace(); } return resultMap; }
From source file:org.tinygroup.beanwrapper.CachedIntrospectionResults.java
/** * Create a new CachedIntrospectionResults instance for the given class. * @param beanClass the bean class to analyze * @throws BeansException in case of introspection failure *///from www . j av a 2s . co m private CachedIntrospectionResults(Class beanClass) throws BeansException { try { if (logger.isTraceEnabled()) { logger.trace("Getting BeanInfo for class [" + beanClass.getName() + "]"); } this.beanInfo = Introspector.getBeanInfo(beanClass); // Immediately remove class from Introspector cache, to allow for proper // garbage collection on class loader shutdown - we cache it here anyway, // in a GC-friendly manner. In contrast to CachedIntrospectionResults, // Introspector does not use WeakReferences as values of its WeakHashMap! Class classToFlush = beanClass; do { Introspector.flushFromCaches(classToFlush); classToFlush = classToFlush.getSuperclass(); } while (classToFlush != null); if (logger.isTraceEnabled()) { logger.trace("Caching PropertyDescriptors for class [" + beanClass.getName() + "]"); } this.propertyDescriptorCache = new HashMap(); // This call is slow so we do it once. PropertyDescriptor[] pds = this.beanInfo.getPropertyDescriptors(); for (int i = 0; i < pds.length; i++) { PropertyDescriptor pd = pds[i]; if (logger.isTraceEnabled()) { logger.trace("Found bean property '" + pd.getName() + "'" + (pd.getPropertyType() != null ? " of type [" + pd.getPropertyType().getName() + "]" : "") + (pd.getPropertyEditorClass() != null ? "; editor [" + pd.getPropertyEditorClass().getName() + "]" : "")); } if (JdkVersion.isAtLeastJava15()) { pd = new GenericTypeAwarePropertyDescriptor(beanClass, pd.getName(), pd.getReadMethod(), pd.getWriteMethod(), pd.getPropertyEditorClass()); } this.propertyDescriptorCache.put(pd.getName(), pd); } } catch (IntrospectionException ex) { throw new FatalBeanException("Cannot get BeanInfo for object of class [" + beanClass.getName() + "]", ex); } }
From source file:com.kangdainfo.common.util.BeanUtil.java
public static Method getReadMethod(Class<? extends Object> examineClass, String propertyName) throws Exception { PropertyDescriptor[] pds = Introspector.getBeanInfo(examineClass).getPropertyDescriptors(); for (int i = 0; i < pds.length; i++) { if (pds[i].getName().equals(propertyName)) { return pds[i].getReadMethod(); }/*from w w w .ja v a2s. co m*/ } throw new Exception("Property not found."); }