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.github.mrgoro.interactivedata.spring.service.SwaggerService.java

/**
 * Get Parameters from a/*from  w  w w.ja  v a  2 s. co  m*/
 * {@link com.github.mrgoro.interactivedata.api.data.operations.OperationData OperationData}-Class.
 *
 * @param dataClass Operation Data Class
 * @param type Type of operation
 * @return Map of parameters with their names as keys
 */
private Map<String, Parameter> getParametersForClass(Class<?> dataClass, String type) {
    Map<String, Parameter> parameters = new HashMap<>();
    try {
        PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(dataClass).getPropertyDescriptors();
        for (PropertyDescriptor pd : propertyDescriptors) {
            // Class is a property descriptor => filter out
            if (pd.getReadMethod() != null && !"class".equals(pd.getName())) {
                parameters.put(pd.getName(),
                        new QueryParameter().name(pd.getName()).description(type + " param for " + pd.getName())
                                .required(false).property(getProperty(pd.getPropertyType())));
            }
        }
    } catch (IntrospectionException e) {
        log.error("Exception using introspection for generating Interactive Data API (Parameters)", e);
    }
    return parameters;
}

From source file:org.dphibernate.serialization.HibernateDeserializer.java

private Object readBean(Object obj) {
    try {/*  w  w w .j av a 2  s  .c  om*/
        BeanInfo info = Introspector.getBeanInfo(obj.getClass());
        for (PropertyDescriptor pd : info.getPropertyDescriptors()) {
            String propName = pd.getName();
            if (!"class".equals(propName) && !"annotations".equals(propName)
                    && !"hibernateLazyInitializer".equals(propName)) {
                Object val = pd.getReadMethod().invoke(obj, null);
                if (val != null) {
                    Object newVal = translate(val, pd.getPropertyType());
                    try {
                        Method writeMethod = pd.getWriteMethod();
                        if (writeMethod != null) {
                            writeMethod.invoke(obj, newVal);
                        }
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                        throw new RuntimeException(e);
                    } catch (NullPointerException npe) {
                        throw npe;
                    }

                }
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
    return obj;
}

From source file:cat.albirar.framework.sets.impl.SetBuilderDefaultImpl.java

/**
 * {@inheritDocs}/* w  w  w  .j av  a 2s  . com*/
 */
@Override
public ISetBuilder<T> pushPropertyPath(String propertyPath) {
    StringTokenizer stk;
    String spath;
    PropertyDescriptor pdesc;

    // Verify propertyPath
    Assert.hasText(propertyPath);
    stk = new StringTokenizer(propertyPath, ".");
    while (stk.hasMoreTokens()) {
        spath = stk.nextToken();
        if ((pdesc = currentModelDescriptor.getProperties().get(spath)) != null) {
            currentModelDescriptor = new ModelDescriptor(resolvePath(spath), propertyPath,
                    pdesc.getPropertyType());
        } else {
            throw new IllegalArgumentException(
                    "The path denoted by '" + propertyPath + "' at '" + getCurrentPathOrRoot() + "' for model '"
                            + rootModel.getName() + "' doesn't exists. Cannot be pushed!");
        }
    }
    pathStack.push(currentModelDescriptor);
    return this;
}

From source file:org.apache.ojb.broker.metadata.fieldaccess.PersistentFieldIntrospectorImpl.java

public void set(Object target, Object value) throws MetadataException {
    if (target == null)
        return;// w w w.  j  a  v a  2  s . c  o  m
    List propertyDescriptors = getPropertyGraph();
    int size = propertyDescriptors.size() - 1;
    PropertyDescriptor pd;
    for (int i = 0; i < size; i++) {
        Object attribute;
        pd = (PropertyDescriptor) propertyDescriptors.get(i);
        attribute = getValueFrom(pd, target);
        if (attribute != null || value != null) {
            if (attribute == null) {
                try {
                    attribute = ClassHelper.newInstance(pd.getPropertyType());
                } catch (Exception e) {
                    throw new MetadataException("Can't instantiate nested object of type '"
                            + pd.getPropertyType() + "' for field '" + pd.getName() + "'", e);
                }
            }
            setValueFor(pd, target, attribute);
        } else {
            return;
        }
        target = attribute;
    }
    pd = (PropertyDescriptor) propertyDescriptors.get(size);
    setValueFor(pd, target, value);
}

From source file:net.jolm.JolmLdapTemplate.java

private boolean isAttributeApplicableInFilter(PropertyDescriptor pd) {
    String propertyName = pd.getName();
    return applicableTypesInFilter.contains(pd.getPropertyType()) && !isReservedField(propertyName);
}

From source file:org.codehaus.groovy.grails.commons.DefaultGrailsControllerClass.java

private void flowStrategy(Collection<String> closureNames) {

    for (PropertyDescriptor propertyDescriptor : getPropertyDescriptors()) {
        Method readMethod = propertyDescriptor.getReadMethod();
        if (readMethod != null && !Modifier.isStatic(readMethod.getModifiers())) {
            final Class<?> propertyType = propertyDescriptor.getPropertyType();
            if ((propertyType == Object.class || propertyType == Closure.class)
                    && propertyDescriptor.getName().endsWith(FLOW_SUFFIX)) {
                String closureName = propertyDescriptor.getName();
                String flowId = closureName.substring(0, closureName.length() - FLOW_SUFFIX.length());
                flows.put(flowId, propertyDescriptor);
                closureNames.add(flowId);
                configureMappingForMethodAction(flowId);
            }/*from   w  ww.j a va  2 s . com*/
        }
    }
    if (!isReadableProperty(defaultActionName) && closureNames.size() == 1) {
        defaultActionName = closureNames.iterator().next();
    }
}

From source file:org.kuali.kfs.module.cam.document.service.impl.AssetPaymentServiceImpl.java

/**
 * @see org.kuali.kfs.module.cam.document.service.AssetPaymentService#adjustPaymentAmounts(org.kuali.kfs.module.cam.businessobject.AssetPayment,
 *      boolean, boolean)/*from w  w w  .j  a  v  a2 s  .com*/
 */
public void adjustPaymentAmounts(AssetPayment assetPayment, boolean reverseAmount,
        boolean nullPeriodDepreciation) throws IllegalAccessException, InvocationTargetException {
    LOG.debug("Starting - adjustAmounts() ");
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(AssetPayment.class);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        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) {
                // Reset periodic depreciation expenses
                if (nullPeriodDepreciation
                        && Pattern.matches(CamsConstants.SET_PERIOD_DEPRECIATION_AMOUNT_REGEX,
                                writeMethod.getName().toLowerCase())) {
                    Object[] nullVal = new Object[] { null };
                    writeMethod.invoke(assetPayment, nullVal);
                } else if (reverseAmount) {
                    // reverse the amounts
                    writeMethod.invoke(assetPayment, (amount.negated()));
                }
            }

        }
    }
    LOG.debug("Finished - adjustAmounts()");
}

From source file:org.toobsframework.data.beanutil.BeanMonkey.java

public static void populate(Object bean, Map properties, boolean validate)
        throws IllegalAccessException, InvocationTargetException, ValidationException, PermissionException {

    // Do nothing unless both arguments have been specified
    if ((bean == null) || (properties == null)) {
        return;/*from  ww w.j a v  a  2  s.c  o m*/
    }
    if (log.isDebugEnabled()) {
        log.debug("BeanMonkey.populate(" + bean + ", " + properties + ")");
    }

    Errors e = null;
    if (validate) {
        String beanClassName = null;
        beanClassName = bean.getClass().getName();
        beanClassName = beanClassName.substring(beanClassName.lastIndexOf(".") + 1);
        e = new BindException(bean, beanClassName);
    }

    String namespace = null;
    if (properties.containsKey("namespace") && !"".equals(properties.get("namespace"))) {
        namespace = (String) properties.get("namespace") + ".";
    }

    // Loop through the property name/value pairs to be set
    Iterator names = properties.keySet().iterator();
    while (names.hasNext()) {

        // Identify the property name and value(s) to be assigned
        String name = (String) names.next();
        if (name == null) {
            continue;
        }
        Object value = properties.get(name);
        if (namespace != null) {
            name = name.replace(namespace, "");
        }

        PropertyDescriptor descriptor = null;
        Class type = null; // Java type of target property
        try {
            descriptor = PropertyUtils.getPropertyDescriptor(bean, name);
            if (descriptor == null) {
                continue; // Skip this property setter
            }
        } catch (NoSuchMethodException nsm) {
            continue; // Skip this property setter
        } catch (IllegalArgumentException iae) {
            continue; // Skip null nested property
        }

        if (descriptor.getWriteMethod() == null) {
            if (log.isDebugEnabled()) {
                log.debug("Skipping read-only property");
            }
            continue; // Read-only, skip this property setter
        }
        type = descriptor.getPropertyType();
        String className = type.getName();

        try {
            value = evaluatePropertyValue(name, className, namespace, value, properties, bean);
        } catch (NoSuchMethodException nsm) {
            continue;
        }

        try {
            if (value != null) {
                BeanUtils.setProperty(bean, name, value);
            }
        } catch (ConversionException ce) {
            log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name + " value:"
                    + value + "] ");
            if (validate) {
                e.rejectValue(name, name + ".conversionError", ce.getMessage());
            } else {
                throw new ValidationException(bean, className, name, ce.getMessage());
            }
        } catch (Exception be) {
            log.error("populate - exception [bean:" + bean.getClass().getName() + " name:" + name + " value:"
                    + value + "] ");
            if (validate) {
                e.rejectValue(name, name + ".error", be.getMessage());
            } else {
                throw new ValidationException(bean, className, name, be.getMessage());
            }
        }
    }
    if (validate && e.getErrorCount() > 0) {
        throw new ValidationException(e);
    }
}

From source file:org.codehaus.mojo.pomtools.wrapper.reflection.BeanFields.java

public BeanFields(String fieldFullName, Object objectToInspect) {
    this.fieldFullName = fieldFullName;

    PomToolsPluginContext context = PomToolsPluginContext.getInstance();

    Log log = context.getLog();/*from w  ww .ja  v  a2  s.  c om*/

    PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(objectToInspect);

    for (int i = 0; i < descriptors.length; i++) {
        PropertyDescriptor pd = descriptors[i];

        FieldConfiguration config = context
                .getFieldConfiguration(ModelHelper.buildFullName(fieldFullName, pd.getName()));
        if (pd.getWriteMethod() != null && (config == null || !config.isIgnore())) {
            if (log.isDebugEnabled()) {
                log.debug("Property: " + ModelHelper.buildFullName(fieldFullName, pd.getName()) + " => "
                        + pd.getPropertyType().getName());
            }

            if (pd.getPropertyType().equals(String.class)) {
                add(new StringField(fieldFullName, pd.getName()));
            } else if (pd.getPropertyType().equals(boolean.class)) {
                add(new BooleanField(fieldFullName, pd.getName()));
            } else if (pd.getPropertyType().equals(List.class)) {
                addListField(pd, objectToInspect);
            } else if (pd.getPropertyType().equals(Properties.class)) {
                add(new PropertiesBeanField(fieldFullName, pd.getName()));
            } else {
                add(new CompositeField(fieldFullName, pd.getName(), pd.getPropertyType()));
            }
        }
    }

}

From source file:gr.interamerican.bo2.utils.TestJavaBeanUtils.java

/**
 * Unit test for getPropertyDescriptor./*from   w  w  w .j a  v  a  2  s  .c  o m*/
 */
@SuppressWarnings("nls")
@Test
public void testGetPropertyDescriptor() {

    //class
    PropertyDescriptor[] props = JavaBeanUtils.getBeansProperties(BeanWith2Fields.class);
    for (PropertyDescriptor p : props) {
        PropertyDescriptor pd = JavaBeanUtils.getPropertyDescriptor(BeanWith2Fields.class, p.getName());
        assertNotNull(pd);
        assertEquals(pd.getName(), p.getName());
        assertEquals(pd.getPropertyType(), p.getPropertyType());
    }

    //class with inheritance
    props = JavaBeanUtils.getBeansProperties(Child.class);
    for (PropertyDescriptor p : props) {
        PropertyDescriptor pd = JavaBeanUtils.getPropertyDescriptor(Child.class, p.getName());
        assertNotNull(pd);
        assertEquals(pd.getName(), p.getName());
        assertEquals(pd.getPropertyType(), p.getPropertyType());
    }

    //abstract class
    PropertyDescriptor pd1 = JavaBeanUtils.getPropertyDescriptor(SampleAbstractClass2.class, "field1"); //$NON-NLS-1$
    assertNull(pd1);

    //interface
    props = JavaBeanUtils.getBeansProperties(SuperSampleInterface.class);
    for (PropertyDescriptor p : props) {
        PropertyDescriptor pd = JavaBeanUtils.getPropertyDescriptor(SuperSampleInterface.class, p.getName());
        assertNotNull(pd);
        assertEquals(pd.getName(), p.getName());
        assertEquals(pd.getPropertyType(), p.getPropertyType());
    }

    //interface with inheritance
    props = JavaBeanUtils.getBeansProperties(SubSampleInterface.class);
    for (PropertyDescriptor p : props) {
        PropertyDescriptor pd = JavaBeanUtils.getPropertyDescriptor(SubSampleInterface.class, p.getName());
        assertNotNull(pd);
        assertEquals(pd.getName(), p.getName());
        assertEquals(pd.getPropertyType(), p.getPropertyType());
    }

    //nested property
    PropertyDescriptor nestedPd = JavaBeanUtils.getPropertyDescriptor(BeanWithNestedBean.class,
            "nested.field1");
    PropertyDescriptor directPd = JavaBeanUtils.getPropertyDescriptor(BeanWith2Fields.class, "field1");
    assertNotNull(nestedPd);
    assertNotNull(directPd);
    assertEquals(nestedPd.getName(), directPd.getName());
    assertEquals(nestedPd.getPropertyType(), directPd.getPropertyType());

}