List of usage examples for java.beans Introspector getBeanInfo
public static BeanInfo getBeanInfo(Class<?> beanClass, Class<?> stopClass) throws IntrospectionException
From source file:com.google.feedserver.util.BeanUtil.java
/** * Applies a collection of properties to a JavaBean. Converts String and * String[] values to correct property types * //from w w w. j a v a2s . c om * @param properties A map of the properties to set on the JavaBean * @param bean The JavaBean to set the properties on */ public void convertPropertiesToBean(Map<String, Object> properties, Object bean) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, ParseException { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class); for (PropertyDescriptor p : beanInfo.getPropertyDescriptors()) { String name = p.getName(); Object value = properties.get(name); Method reader = p.getReadMethod(); Method writer = p.getWriteMethod(); // we only care about "complete" properties if (reader != null && writer != null && value != null) { Class<?> propertyType = writer.getParameterTypes()[0]; if (isBean(propertyType)) { // this is a bean if (propertyType.isArray()) { propertyType = propertyType.getComponentType(); Object beanArray = Array.newInstance(propertyType, 1); if (value.getClass().isArray()) { Object[] valueArrary = (Object[]) value; int length = valueArrary.length; beanArray = Array.newInstance(propertyType, length); for (int index = 0; index < valueArrary.length; ++index) { Object valueObject = valueArrary[index]; fillBeanInArray(propertyType, beanArray, index, valueObject); } } else { fillBeanInArray(propertyType, beanArray, 0, value); } value = beanArray; } else if (propertyType == Timestamp.class) { value = new Timestamp(TIMESTAMP_FORMAT.parse((String) value).getTime()); } else { Object beanObject = createBeanObject(propertyType, value); value = beanObject; } } else { Class<?> valueType = value.getClass(); if (!propertyType.isAssignableFrom(valueType)) { // convert string input values to property type try { if (valueType == String.class) { value = ConvertUtils.convert((String) value, propertyType); } else if (valueType == String[].class) { value = ConvertUtils.convert((String[]) value, propertyType); } else if (valueType == Object[].class) { // best effort conversion Object[] objectValues = (Object[]) value; String[] stringValues = new String[objectValues.length]; for (int i = 0; i < objectValues.length; i++) { stringValues[i] = objectValues[i] == null ? null : objectValues[i].toString(); } value = ConvertUtils.convert(stringValues, propertyType); } else { } } catch (ConversionException e) { throw new IllegalArgumentException( "Conversion failed for " + "property '" + name + "' with value '" + value + "'", e); } } } // We only write values that are present in the map. This allows // defaults or previously set values in the bean to be retained. writer.invoke(bean, value); } } }
From source file:com.link_intersystems.beans.BeanClass.java
/** * @param stopClass/*from w ww. ja va 2 s . co m*/ * the class to stop {@link PropertyDescriptor} resolution. Must * be a superclass of this class. If the stop class is not null * then all {@link PropertyDescriptor}s are contained in the * result map that this class and every class along the hierarchy * until the stop class has. The {@link PropertyDescriptor} of * the stop class are not included. * @return a map whose keys are the property names of the properties that * this class defines according to the java bean specification. The * values are the corresponding {@link PropertyDescriptor}s. The * returned {@link Map} can be modified by clients without * interfering this object's state. * @throws IllegalArgumentException * if the stop class is not a super class of this class or * another Exception occurs while resolving the * {@link PropertyDescriptor}s. The cause might be an * {@link IntrospectionException}. * @since 1.2.0.0 */ public Map<String, PropertyDescriptor> getPropertyDescriptors(Class<?> stopClass) throws IllegalStateException { Class<T> beanType = getType(); try { BeanInfo beanInfo = Introspector.getBeanInfo(beanType, stopClass); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); Map<String, PropertyDescriptor> propertyDescriptorsMap = UtilFacade.keyMap( Arrays.asList(propertyDescriptors), new MethodInvokingParameterizedObjectFactory<PropertyDescriptor, String>( PropertyDescriptor.class, "getName")); return propertyDescriptorsMap; } catch (IntrospectionException e) { throw new IllegalArgumentException( "Unable to build property map for " + beanType + " with stopClass " + stopClass, e); } }
From source file:org.mule.security.oauth.BaseOAuthClientFactory.java
/** * This method is to provide backwards compatibility with connectors generated * using devkit 3.4.0 or lower. Those connectors used one custom OAuthState class * per connector which disabled the possibility of token sharing. The * {@link org.mule.common.security.oauth.OAuthState} solves that problem but * generates a migration issues with applications using such a connector and * wishing to upgrade. This method retrieves a value from the ObjectStore and if * it's not a generic org.mule.common.security.oauth.OAuthState instance it * translates it to one, generating an ongoing migration process. If * <code>replace</code> is true, then the value in the ObjectStore is replaced. * Once Mule 3.4.0 reaches end of life status, this method can be replaced by * simple object store lookup// w ww .j a v a 2 s . c o m * * @param key the object store key * @param replace if true and if the obtained value is not an instance of * {@link org.mule.common.security.oauth.OAuthState}, then the value * is replaced in the object store by the transformed instance */ private synchronized OAuthState retrieveOAuthState(String key, boolean replace) { Object state = null; try { state = this.objectStore.retrieve(key); } catch (ObjectStoreException e) { throw new RuntimeException("Error retrieving value from object store with key " + key, e); } if (state != null && !(state instanceof OAuthState)) { OAuthState newState = new OAuthState(); try { for (PropertyDescriptor beanProperty : Introspector.getBeanInfo(state.getClass(), Object.class) .getPropertyDescriptors()) { Object value = beanProperty.getReadMethod().invoke(state, (Object[]) null); if (value != null) { PropertyDescriptor stateProperty = oauthStateProperties.get(beanProperty.getName()); if (stateProperty != null) { stateProperty.getWriteMethod().invoke(newState, value); } else { newState.setCustomProperty(beanProperty.getName(), value.toString()); } } } } catch (IllegalAccessException e) { throw new RuntimeException("Error accessing value through reflection", e); } catch (IntrospectionException e) { throw new RuntimeException( "Error introspecting object of class " + state.getClass().getCanonicalName(), e); } catch (IllegalArgumentException e) { throw new RuntimeException("Error setting value through reflection", e); } catch (InvocationTargetException e) { throw new RuntimeException("Object threw exception while setting value by reflection", e); } state = newState; if (replace) { try { this.objectStore.remove(key); this.objectStore.store(key, newState); } catch (ObjectStoreException e) { throw new RuntimeException("ObjectStore threw exception while replacing instance", e); } } } return (OAuthState) state; }
From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlUrlRewriteRulesExporter.java
private Element createElement(Document document, String name, Object bean) throws IntrospectionException, InvocationTargetException, NoSuchMethodException, IllegalAccessException { Element element = document.createElement(name); BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class); for (PropertyDescriptor propInfo : beanInfo.getPropertyDescriptors()) { String propName = propInfo.getName(); if (propInfo.getReadMethod() != null && String.class.isAssignableFrom(propInfo.getPropertyType())) { String propValue = BeanUtils.getProperty(bean, propName); if (propValue != null && !propValue.isEmpty()) { // Doing it the hard way to avoid having the &'s in the query string escaped at & Attr attr = document.createAttribute(propName); attr.setValue(propValue); element.setAttributeNode(attr); //element.setAttribute( propName, propValue ); }/*from www . j a v a 2 s .co m*/ } } return element; }
From source file:org.rhq.bindings.ScriptEngineFactory.java
/** * Goes through the methods of the object found in the <code>scriptEngine</code>'s ENGINE_SCOPE * and for each of them generates a top-level function that is called the same name and accepts the same * parameters./*from ww w . java 2 s . com*/ * * @param scriptEngine the script engine to generate the top-level functions in * @param bindingName the name of the object in the script engine to generate the functions from * * @see ScriptEngineInitializer#generateIndirectionMethod(String, Method) * @see NoTopLevelIndirection */ public static void bindIndirectionMethods(ScriptEngine scriptEngine, String bindingName) { Object object = scriptEngine.get(bindingName); if (object == null) { LOG.debug("The script engine doesn't contain a binding called '" + bindingName + "'. No indirection functions will be generated."); return; } ScriptEngineInitializer initializer = getInitializer(scriptEngine.getFactory().getLanguageName()); try { BeanInfo beanInfo = Introspector.getBeanInfo(object.getClass(), Object.class); MethodDescriptor[] methodDescriptors = beanInfo.getMethodDescriptors(); Map<String, Set<Method>> overloadsPerMethodName = new HashMap<String, Set<Method>>(); for (MethodDescriptor methodDescriptor : methodDescriptors) { Method method = methodDescriptor.getMethod(); if (shouldIndirect(method)) { Set<Method> overloads = overloadsPerMethodName.get(method.getName()); if (overloads == null) { overloads = new HashSet<Method>(); overloadsPerMethodName.put(method.getName(), overloads); } overloads.add(method); } } for (Set<Method> overloads : overloadsPerMethodName.values()) { Set<String> methodDefs = initializer.generateIndirectionMethods(bindingName, overloads); for (String methodDef : methodDefs) { try { scriptEngine.eval(methodDef); } catch (ScriptException e) { LOG.warn("Unable to define global function declared as:\n" + methodDef, e); } } } } catch (IntrospectionException e) { LOG.debug("Could not inspect class " + object.getClass().getName() + ". No indirection methods for variable '" + bindingName + "' will be generated.", e); } }
From source file:org.codehaus.enunciate.modules.xfire_client.EnunciatedClientOperationBinding.java
/** * Loads the property descriptors for the ordered properties of the specified class. * * @param wrapperClass The wrapper class. * @return The ordered property descriptors. *///from ww w . ja v a 2s. c om protected PropertyDescriptor[] loadOrderedProperties(Class wrapperClass) throws XFireFault { String[] propOrder = annotations.getPropertyOrder(wrapperClass); if (propOrder == null) { throw new XFireFault( "Unable use use " + wrapperClass.getName() + " as a wrapper class: no propOrder specified.", XFireFault.RECEIVER); } BeanInfo responseBeanInfo; try { responseBeanInfo = Introspector.getBeanInfo(wrapperClass, Object.class); } catch (IntrospectionException e) { throw new XFireFault("Unable to introspect " + wrapperClass.getName(), e, XFireFault.RECEIVER); } return PropertyUtil.sortProperties(wrapperClass, responseBeanInfo.getPropertyDescriptors(), propOrder); }
From source file:padl.util.Util.java
public static List getPatternProperties(final Class clazz) { final List roProperties = new ArrayList(); final List rwProperties = new ArrayList(); final List exProperties = new ArrayList(); try {//from ww w . j a va 2s . c o m final PropertyDescriptor[] basicProperties = Introspector.getBeanInfo(clazz, null) .getPropertyDescriptors(); for (int x = 0; x < basicProperties.length; x++) { final Method writeMethod = basicProperties[x].getWriteMethod(); final Method readMethod = basicProperties[x].getReadMethod(); if (readMethod != null) { if (writeMethod != null) { rwProperties.add(basicProperties[x].getName()); } else { roProperties.add(basicProperties[x].getName()); } } } } catch (final Exception e) { } // I look for all suitable "add" and "remove" methods. try { final Map adds = new HashMap(); final Map removes = new HashMap(); final Method[] methods = clazz.getMethods(); for (int i = 0; i < methods.length; i++) { final Method currentMethod = methods[i]; final int mods = currentMethod.getModifiers(); final String currentName = currentMethod.getName(); final Class argTypes[] = currentMethod.getParameterTypes(); if (Modifier.isStatic(mods) || !Modifier.isPublic(mods) // || // argTypes.length // != 1 || currentMethod.getReturnType() != Void.TYPE) { continue; // RV: pour que Yann soit content !!!! } // Yann 2001/06/27: I check the number of arguments // depending on which type of method I am looking at // to handle correctly the add and remove methods // of the Faade pattern. if (currentName.startsWith("add") && argTypes.length > 0) { adds.put(new String(currentName.substring(3) + ":" + argTypes[0]), currentMethod); } else if (currentName.startsWith("remove") && argTypes.length == 1) { removes.put(new String(currentName.substring(6) + ":" + argTypes[0]), currentMethod); } } // Now I look for matching add + remove pairs. final Iterator keys = adds.keySet().iterator(); while (keys.hasNext()) { final String addKey = (String) keys.next(); // Skip any "add" which doesn't have a matching "remove". if (removes.get(addKey) != null) { exProperties.add(addKey.substring(0, addKey.indexOf(":"))); } } } catch (final Exception e) { e.printStackTrace(ProxyConsole.getInstance().errorOutput()); } final List props = roProperties; props.addAll(rwProperties); props.addAll(exProperties); return props; }
From source file:org.springframework.beans.CachedIntrospectionResults.java
/** * Retrieve a {@link BeanInfo} descriptor for the given target class. * @param beanClass the target class to introspect * @param ignoreBeaninfoClasses whether to apply {@link Introspector#IGNORE_ALL_BEANINFO} mode * @return the resulting {@code BeanInfo} descriptor (never {@code null}) * @throws IntrospectionException from the underlying {@link Introspector} *///from w ww.j a v a 2s . c om private static BeanInfo getBeanInfo(Class<?> beanClass, boolean ignoreBeaninfoClasses) throws IntrospectionException { for (BeanInfoFactory beanInfoFactory : beanInfoFactories) { BeanInfo beanInfo = beanInfoFactory.getBeanInfo(beanClass); if (beanInfo != null) { return beanInfo; } } return (ignoreBeaninfoClasses ? Introspector.getBeanInfo(beanClass, Introspector.IGNORE_ALL_BEANINFO) : Introspector.getBeanInfo(beanClass)); }
From source file:org.codehaus.enunciate.modules.xfire.EnunciatedJAXWSOperationBinding.java
/** * Loads the property descriptors for the ordered properties of the specified class. * * @param wrapperClass The wrapper class. * @return The ordered property descriptors. *//* w ww . j a v a 2 s . co m*/ protected PropertyDescriptor[] loadOrderedProperties(Class wrapperClass) throws XFireFault { XmlType typeInfo = (XmlType) wrapperClass.getAnnotation(XmlType.class); if ((typeInfo == null) || (typeInfo.propOrder() == null) || ((typeInfo.propOrder().length == 1) && "".equals(typeInfo.propOrder()[0]))) { throw new XFireFault( "Unable use use " + wrapperClass.getName() + " as a wrapper class: no propOrder specified.", XFireFault.RECEIVER); } String[] propOrder = typeInfo.propOrder(); BeanInfo beanInfo; try { beanInfo = Introspector.getBeanInfo(wrapperClass, Object.class); } catch (IntrospectionException e) { throw new XFireFault("Unable to introspect " + wrapperClass.getName(), e, XFireFault.RECEIVER); } PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); PropertyDescriptor[] props = new PropertyDescriptor[propOrder.length]; RESPONSE_PROPERTY_LOOP: for (int i = 0; i < propOrder.length; i++) { String property = propOrder[i]; if ((property.length() > 1) && (!Character.isLowerCase(property.charAt(1)))) { //if the second letter is uppercase, javabean spec says the first character of the property is also to be kept uppercase. property = capitalize(property); } for (PropertyDescriptor descriptor : pds) { if (descriptor.getName().equals(property)) { props[i] = descriptor; continue RESPONSE_PROPERTY_LOOP; } } throw new XFireFault("Unknown property " + property + " on wrapper " + wrapperClass.getName(), XFireFault.RECEIVER); } return props; }
From source file:tradeok.HttpTool.java
public static String bean2json(Object bean) { StringBuilder json = new StringBuilder(); json.append("{"); PropertyDescriptor[] props = null; try {/*www .jav a2 s . c o m*/ props = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors(); } catch (IntrospectionException e) { } if (props != null) { for (int i = 0; i < props.length; i++) { try { String name = object2json(props[i].getName()); String value = object2json(props[i].getReadMethod().invoke(bean)); json.append(name); json.append(":"); json.append(value); json.append(","); } catch (Exception e) { } } json.setCharAt(json.length() - 1, '}'); } else { json.append("}"); } return json.toString(); }