Example usage for java.beans PropertyDescriptor getPropertyType

List of usage examples for java.beans PropertyDescriptor getPropertyType

Introduction

In this page you can find the example usage for java.beans PropertyDescriptor getPropertyType.

Prototype

public synchronized Class<?> getPropertyType() 

Source Link

Document

Returns the Java type info for the property.

Usage

From source file:com.bstek.dorado.config.definition.Definition.java

/**
 * ?//from   ww w.j  a  v  a2s  .c  o  m
 * 
 * @param object
 *            ?
 * @param property
 *            ??
 * @param value
 *            @see {@link #getProperties()}
 * @param context
 *            
 * @throws Exception
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void setObjectProperty(Object object, String property, Object value, CreationContext context)
        throws Exception {
    if (object instanceof Map) {
        value = DefinitionUtils.getRealValue(value, context);
        if (value instanceof DefinitionSupportedList && ((DefinitionSupportedList) value).hasDefinitions()) {
            List collection = new ArrayList();
            for (Object element : (Collection) value) {
                Object realElement = DefinitionUtils.getRealValue(element, context);
                if (realElement != ConfigUtils.IGNORE_VALUE) {
                    collection.add(realElement);
                }
            }
            value = collection;
        }
        if (value != ConfigUtils.IGNORE_VALUE) {
            ((Map) object).put(property, value);
        }
    } else {
        PropertyDescriptor propertyDescriptor = PropertyUtils.getPropertyDescriptor(object, property);
        if (propertyDescriptor != null) {
            Method readMethod = propertyDescriptor.getReadMethod();
            Method writeMethod = propertyDescriptor.getWriteMethod();

            Class<?> propertyType = propertyDescriptor.getPropertyType();
            if (writeMethod != null) {
                Class<?> oldImpl = context.getDefaultImpl();
                try {
                    context.setDefaultImpl(propertyType);
                    value = DefinitionUtils.getRealValue(value, context);
                } finally {
                    context.setDefaultImpl(oldImpl);
                }
                if (!propertyType.equals(String.class) && value instanceof String) {
                    if (propertyType.isEnum()) {
                        value = Enum.valueOf((Class) propertyType, (String) value);
                    } else if (StringUtils.isBlank((String) value)) {
                        value = null;
                    }
                } else if (value instanceof DefinitionSupportedList
                        && ((DefinitionSupportedList) value).hasDefinitions()) {
                    List collection = new ArrayList();
                    for (Object element : (Collection) value) {
                        Object realElement = DefinitionUtils.getRealValue(element, context);
                        if (realElement != ConfigUtils.IGNORE_VALUE) {
                            collection.add(realElement);
                        }
                    }
                    value = collection;
                }
                if (value != ConfigUtils.IGNORE_VALUE) {
                    writeMethod.invoke(object, new Object[] { ConvertUtils.convert(value, propertyType) });
                }
            } else if (readMethod != null && Collection.class.isAssignableFrom(propertyType)) {
                Collection collection = (Collection) readMethod.invoke(object, EMPTY_ARGS);
                if (collection != null) {
                    if (value instanceof DefinitionSupportedList
                            && ((DefinitionSupportedList) value).hasDefinitions()) {
                        for (Object element : (Collection) value) {
                            Object realElement = DefinitionUtils.getRealValue(element, context);
                            if (realElement != ConfigUtils.IGNORE_VALUE) {
                                collection.add(realElement);
                            }
                        }
                    } else {
                        collection.addAll((Collection) value);
                    }
                }
            } else {
                throw new NoSuchMethodException(
                        "Property [" + property + "] of [" + object + "] is not writable.");
            }
        } else {
            throw new NoSuchMethodException("Property [" + property + "] not found in [" + object + "].");
        }
    }
}

From source file:com.meidusa.venus.frontend.http.VenusPoolFactory.java

@SuppressWarnings("unchecked")
public void afterPropertiesSet() throws Exception {
    logger.trace("current Venus Client id=" + PacketConstant.VENUS_CLIENT_ID);

    beanContext = new BeanContext() {
        public Object getBean(String beanName) {
            if (beanFactory != null) {
                return beanFactory.getBean(beanName);
            } else {
                return null;
            }//from w w w.j  ava 2s . com
        }

        public Object createBean(Class clazz) throws Exception {
            if (beanFactory instanceof AutowireCapableBeanFactory) {
                AutowireCapableBeanFactory factory = (AutowireCapableBeanFactory) beanFactory;
                return factory.autowire(clazz, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
            }
            return null;
        }
    };

    BeanContextBean.getInstance().setBeanContext(beanContext);
    VenusBeanUtilsBean.setInstance(new BeanUtilsBean(new ConvertUtilsBean(), new PropertyUtilsBean()) {

        public void setProperty(Object bean, String name, Object value)
                throws IllegalAccessException, InvocationTargetException {
            if (value instanceof String) {
                PropertyDescriptor descriptor = null;
                try {
                    descriptor = getPropertyUtils().getPropertyDescriptor(bean, name);
                    if (descriptor == null) {
                        return; // Skip this property setter
                    } else {
                        if (descriptor.getPropertyType().isEnum()) {
                            Class<Enum> clazz = (Class<Enum>) descriptor.getPropertyType();
                            value = Enum.valueOf(clazz, (String) value);
                        } else {
                            Object temp = null;
                            try {
                                temp = ConfigUtil.filter((String) value, beanContext);
                            } catch (Exception e) {
                            }
                            if (temp == null) {
                                temp = ConfigUtil.filter((String) value);
                            }
                            value = temp;
                        }
                    }
                } catch (NoSuchMethodException e) {
                    return; // Skip this property setter
                }
            }
            super.setProperty(bean, name, value);
        }

    });

    reloadConfiguration();

    __RELOAD: {
        if (enableReload) {
            File[] files = new File[this.configFiles.length];
            for (int i = 0; i < this.configFiles.length; i++) {
                try {
                    files[i] = ResourceUtils.getFile(configFiles[i].trim());
                } catch (FileNotFoundException e) {
                    logger.warn(e.getMessage());
                    enableReload = false;
                    logger.warn("venus serviceFactory configuration reload disabled!");
                    break __RELOAD;
                }
            }
            VenusFileWatchdog dog = new VenusFileWatchdog(files);
            dog.setDelay(1000 * 10);
            dog.start();
        }
    }
}

From source file:org.onebusaway.siri.core.filters.ElementPathModuleDeliveryFilter.java

private void applyFilter(Object parent, PropertyDescriptor propertyDescriptor) {

    Method readMethod = propertyDescriptor.getReadMethod();
    Method writeMethod = propertyDescriptor.getWriteMethod();

    if (writeMethod != null) {

        Class<?>[] parameterTypes = writeMethod.getParameterTypes();
        Class<?> parameterType = parameterTypes[0];
        Object value = convertValue(_value, parameterType);
        PropertyConverterSupport.setTargetPropertyValue(parent, writeMethod, value);
    } else if (Collection.class.isAssignableFrom(propertyDescriptor.getPropertyType())
            && (_value == null || _value instanceof Collection)) {
        Collection<?> values = (Collection<?>) _value;
        if (values == null)
            values = Collections.emptyList();
        PropertyConverterSupport.setTargetPropertyValues(parent, readMethod, values);
    } else {/*w ww . jav  a  2 s .  c  o m*/
        throw new SiriException(
                "no write method for property \"" + propertyDescriptor.getName() + " on " + parent);
    }
}

From source file:com.vecna.taglib.processor.JspAnnotationsProcessor.java

/**
 * Build a JSP tag model object from an annotated tag class
 * @param type tag class/*from  w  ww . j  a v  a  2  s .  com*/
 * @return JSP tag model
 */
public JspTagModel getTagMetadata(Class<?> type) {
    JspTagModel metadata = new JspTagModel();
    JspTag jspTagAnnotation = type.getAnnotation(JspTag.class);
    metadata.bodyContent = jspTagAnnotation.bodyContent();
    metadata.name = jspTagAnnotation.name();
    metadata.tagClass = type.getName();
    metadata.dynamicAttributes = jspTagAnnotation.dynamicAttributes();

    for (JspVariable jspVariableAnnotation : jspTagAnnotation.variables()) {
        JspVariableModel variable = new JspVariableModel();
        variable.declare = jspVariableAnnotation.declare();

        variable.nameFromAttribute = StringUtils.stripToNull(jspVariableAnnotation.nameFromAttribute());
        variable.nameGiven = StringUtils.stripToNull(jspVariableAnnotation.nameGiven());

        variable.scope = jspVariableAnnotation.scope();
        variable.variableClass = jspVariableAnnotation.variableClass().getName();
        metadata.variables.add(variable);
    }

    for (PropertyDescriptor pd : PropertyUtils.getPropertyDescriptors(type)) {
        s_log.debug("processing property {}", pd.getName());
        if (pd.getWriteMethod() != null && pd.getWriteMethod().isAnnotationPresent(JspAttribute.class)) {
            s_log.debug("attribute metadata present on {}", pd.getName());
            JspAttributeModel attr = new JspAttributeModel();
            attr.name = pd.getName();
            attr.type = pd.getPropertyType().getName();
            JspAttribute jspAttributeAnnotation = pd.getWriteMethod().getAnnotation(JspAttribute.class);
            attr.required = jspAttributeAnnotation.required();
            attr.rtExprValue = jspAttributeAnnotation.rtExprValue();
            attr.fragment = jspAttributeAnnotation.fragment();

            attr.deferredMethod = jspAttributeAnnotation.deferredMethod() ? true : null;
            attr.deferredValue = jspAttributeAnnotation.deferredValue() ? true : null;

            metadata.attributes.add(attr);
        }
    }

    return metadata;
}

From source file:com.seovic.core.DynamicObject.java

/**
 * Update specified target from this object.
 *
 * @param target  target object to update
 *//*from  ww w  .  j av  a 2  s  . c  om*/
public void update(Object target) {
    if (target == null) {
        throw new IllegalArgumentException("Target to update cannot be null");
    }

    BeanWrapper bw = new BeanWrapperImpl(target);
    bw.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    for (Map.Entry<String, Object> property : m_properties.entrySet()) {
        String propertyName = property.getKey();
        Object value = property.getValue();

        if (value instanceof Map) {
            PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
            if (!Map.class.isAssignableFrom(pd.getPropertyType()) || pd.getWriteMethod() == null) {
                value = new DynamicObject((Map<String, Object>) value);
            }
        }

        if (value instanceof DynamicObject) {
            ((DynamicObject) value).update(bw.getPropertyValue(propertyName));
        } else {
            bw.setPropertyValue(propertyName, value);
        }
    }
}

From source file:org.kuali.kfs.module.cam.util.AssetSeparatePaymentDistributor.java

/**
 * Utility method which will negate the payment amounts for a given payment
 * /*from w w w .j  a  v  a 2  s . co  m*/
 * @param assetPayment Payment to be negated
 */
public void negatePaymentAmounts(AssetPayment assetPayment) {
    try {
        for (PropertyDescriptor propertyDescriptor : assetPaymentProperties) {
            Method readMethod = propertyDescriptor.getReadMethod();
            if (readMethod != null && propertyDescriptor.getPropertyType() != null
                    && KualiDecimal.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
                KualiDecimal amount = (KualiDecimal) readMethod.invoke(assetPayment);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                if (writeMethod != null && amount != null) {
                    writeMethod.invoke(assetPayment, (amount.negated()));
                }

            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils.java

/**
 * This is a util method to set a nested property of a given object. The nested property is a
 * dot separated string where each nesting level is separated by a dot. This method makes use of
 * PropertyUtils methods from apache-commons library and assumes that the field names provided in
 * the input propertyName have valid setters. eg. the propertyName sd.serdeInfo.inputFormat represents
 * the inputformat field of the serdeInfo field of the sd field. The argument bean should have these
 * fields (in this case it should be a Partition object). The value argument is the value to be set
 * for the nested field. Note that if in case of one of nested levels is null you must set
 * instantiateMissingFields argument to true otherwise this method could throw a NPE.
 *
 * @param bean the object whose nested field needs to be set. This object must have setter methods
 *             defined for each nested field name in the propertyName
 * @param propertyName the nested propertyName to be set. Each level of nesting is dot separated
 * @param value the value to which the nested property is set
 * @param instantiateMissingFields in case of some nestedFields being nulls, setting this argument
 *                                 to true will attempt to instantiate the missing fields using the
 *                                 default constructor. If there is no default constructor available this would throw a MetaException
 * @throws MetaException//from   w  w  w  .j  a  v  a2 s .c  o m
 */
public static void setNestedProperty(Object bean, String propertyName, Object value,
        boolean instantiateMissingFields) throws MetaException {
    try {
        String[] nestedFields = propertyName.split("\\.");
        //check if there are more than one nested levels
        if (nestedFields.length > 1 && instantiateMissingFields) {
            StringBuilder fieldNameBuilder = new StringBuilder();
            //check if all the nested levels until the given fieldName is set
            for (int level = 0; level < nestedFields.length - 1; level++) {
                fieldNameBuilder.append(nestedFields[level]);
                String currentFieldName = fieldNameBuilder.toString();
                Object fieldVal = PropertyUtils.getProperty(bean, currentFieldName);
                if (fieldVal == null) {
                    //one of the nested levels is null. Instantiate it
                    PropertyDescriptor fieldDescriptor = PropertyUtils.getPropertyDescriptor(bean,
                            currentFieldName);
                    //this assumes the MPartition and the nested field objects have a default constructor
                    Object defaultInstance = fieldDescriptor.getPropertyType().newInstance();
                    PropertyUtils.setNestedProperty(bean, currentFieldName, defaultInstance);
                }
                //add dot separator for the next level of nesting
                fieldNameBuilder.append(DOT);
            }
        }
        PropertyUtils.setNestedProperty(bean, propertyName, value);
    } catch (Exception e) {
        throw new MetaException(org.apache.hadoop.hive.metastore.utils.StringUtils.stringifyException(e));
    }
}

From source file:org.kuali.kfs.module.cam.util.AssetSeparatePaymentDistributor.java

/**
 * Utility method which can take one payment and distribute its amount by ratio to the target payments
 * /*ww  w . j  a  v  a  2s. c o  m*/
 * @param source Source Payment
 * @param targets Target Payment
 * @param ratios Ratio to be applied for each target
 */
private void applyRatioToPaymentAmounts(AssetPayment source, AssetPayment[] targets, double[] ratios) {
    try {
        for (PropertyDescriptor propertyDescriptor : assetPaymentProperties) {
            Method readMethod = propertyDescriptor.getReadMethod();
            if (readMethod != null && propertyDescriptor.getPropertyType() != null
                    && KualiDecimal.class.isAssignableFrom(propertyDescriptor.getPropertyType())) {
                KualiDecimal amount = (KualiDecimal) readMethod.invoke(source);
                if (amount != null && amount.isNonZero()) {
                    KualiDecimal[] ratioAmounts = KualiDecimalUtils.allocateByRatio(amount, ratios);
                    Method writeMethod = propertyDescriptor.getWriteMethod();
                    if (writeMethod != null) {
                        for (int i = 0; i < ratioAmounts.length; i++) {
                            writeMethod.invoke(targets[i], ratioAmounts[i]);
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

From source file:com.opensymphony.xwork2.ognl.accessor.CompoundRootAccessor.java

public Object callMethod(Map context, Object target, String name, Object[] objects)
        throws MethodFailedException {
    CompoundRoot root = (CompoundRoot) target;

    if ("describe".equals(name)) {
        Object v;//w  w w  .ja v a  2  s  . c o m
        if (objects != null && objects.length == 1) {
            v = objects[0];
        } else {
            v = root.get(0);
        }

        if (v instanceof Collection || v instanceof Map || v.getClass().isArray()) {
            return v.toString();
        }

        try {
            Map<String, PropertyDescriptor> descriptors = OgnlRuntime.getPropertyDescriptors(v.getClass());

            int maxSize = 0;
            for (String pdName : descriptors.keySet()) {
                if (pdName.length() > maxSize) {
                    maxSize = pdName.length();
                }
            }

            SortedSet<String> set = new TreeSet<String>();
            StringBuffer sb = new StringBuffer();
            for (PropertyDescriptor pd : descriptors.values()) {

                sb.append(pd.getName()).append(": ");
                int padding = maxSize - pd.getName().length();
                for (int i = 0; i < padding; i++) {
                    sb.append(" ");
                }
                sb.append(pd.getPropertyType().getName());
                set.add(sb.toString());

                sb = new StringBuffer();
            }

            sb = new StringBuffer();
            for (Object aSet : set) {
                String s = (String) aSet;
                sb.append(s).append("\n");
            }

            return sb.toString();
        } catch (IntrospectionException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Got exception in callMethod", e);
            }
        } catch (OgnlException e) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Got exception in callMethod", e);
            }
        }

        return null;
    }

    for (Object o : root) {
        if (o == null) {
            continue;
        }

        Class clazz = o.getClass();
        Class[] argTypes = getArgTypes(objects);

        MethodCall mc = null;

        if (argTypes != null) {
            mc = new MethodCall(clazz, name, argTypes);
        }

        if ((argTypes == null) || !invalidMethods.containsKey(mc)) {
            try {
                Object value = OgnlRuntime.callMethod((OgnlContext) context, o, name, objects);

                if (value != null) {
                    return value;
                }
            } catch (OgnlException e) {
                // try the next one
                Throwable reason = e.getReason();

                if (!context.containsKey(OgnlValueStack.THROW_EXCEPTION_ON_FAILURE) && (mc != null)
                        && (reason != null) && (reason.getClass() == NoSuchMethodException.class)) {
                    invalidMethods.put(mc, Boolean.TRUE);
                } else if (reason != null) {
                    throw new MethodFailedException(o, name, e.getReason());
                }
            }
        }
    }

    return null;
}

From source file:net.sf.dsig.Environment.java

/**
 * <p>Initialize an object's public properties, using any environmental
 * values that have been declared./*from   ww  w .  j  a v  a2s .  c o  m*/
 * 
 * @param obj the object to initialize.
 * @param prefix the prefix to add while looking at the environmental values
 */
public void init(Object obj, String prefix) {
    // Iterate through all the properties declared for the applet class
    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(obj);
    for (PropertyDescriptor descriptor : descriptors) {
        String propertyName = descriptor.getName();
        logger.debug("Checking" + ": obj.class=" + obj.getClass() + ", propertyName=" + propertyName);

        if (descriptor.getWriteMethod() == null) {
            continue;
        }

        // Check if an environment parameter has been specified; if so, 
        // override the value with the one supplied
        String key = (prefix != null) ? prefix + propertyName : propertyName;

        Object value;
        if (descriptor.getPropertyType().isArray()) {
            value = getValues(key);
        } else {
            value = getValue(key);
        }

        if (value != null) {
            logger.debug("Setting" + ": obj.class=" + obj.getClass() + ", propertyName=" + propertyName
                    + ", value=" + value);

            try {
                BeanUtils.setProperty(obj, propertyName, value);
            } catch (Exception e) {
                logger.warn("Object initialization error", e);
            }
        }
    }
}