Example usage for org.springframework.beans BeanUtils getPropertyDescriptors

List of usage examples for org.springframework.beans BeanUtils getPropertyDescriptors

Introduction

In this page you can find the example usage for org.springframework.beans BeanUtils getPropertyDescriptors.

Prototype

public static PropertyDescriptor[] getPropertyDescriptors(Class<?> clazz) throws BeansException 

Source Link

Document

Retrieve the JavaBeans PropertyDescriptor s of a given class.

Usage

From source file:edu.cmu.cs.lti.discoursedb.api.browsing.controller.BrowsingRestController.java

@RequestMapping(value = "/action/downloadQueryCsv/discoursedb_data.csv", method = RequestMethod.GET)
@ResponseBody//from   w w  w  .  java  2 s.com
String downloadQueryCsv(HttpServletResponse response, @RequestParam("query") String query,
        HttpServletRequest hsr, HttpSession session) throws IOException {

    securityUtils.authenticate(hsr, session);
    response.setContentType("application/csv; charset=utf-8");
    response.setHeader("Content-Disposition", "attachment");

    try {
        logger.info("Got query for csv: " + query);

        DdbQuery q = new DdbQuery(selector, discoursePartService, query);

        Page<BrowsingContributionResource> lbcr = q.retrieveAllContributions()
                .map(c -> new BrowsingContributionResource(c, annoService));

        StringBuilder output = new StringBuilder();
        ArrayList<String> headers = new ArrayList<String>();
        for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(BrowsingContributionResource.class)) {
            String name = pd.getName();
            if (!name.equals("class") && !name.equals("id") && !name.equals("links")) {
                headers.add(name);
            }
        }
        output.append(String.join(",", headers));
        output.append("\n");

        for (BrowsingContributionResource bcr : lbcr.getContent()) {
            String comma = "";
            BeanWrapper wrap = PropertyAccessorFactory.forBeanPropertyAccess(bcr);
            for (String hdr : headers) {

                String item = "";
                try {
                    item = wrap.getPropertyValue(hdr).toString();
                    item = item.replaceAll("\"", "\"\"");
                    item = item.replaceAll("^\\[(.*)\\]$", "$1");
                } catch (Exception e) {
                    logger.info(e.toString() + " For header " + hdr + " item " + item);
                    item = "";
                }
                if (hdr.equals("annotations") && item.length() > 0) {
                    logger.info("Annotation is " + item);
                }
                output.append(comma + "\"" + item + "\"");
                comma = ",";
            }
            output.append("\n");
        }
        return output.toString();
    } catch (Exception e) {
        return "ERROR:" + e.getMessage();
    }
}

From source file:grails.util.GrailsClassUtils.java

/**
 * Retrieves a PropertyDescriptor for the specified instance and property value
 *
 * @param instance The instance//from w  w w.  j  a va  2 s  .  c o  m
 * @param propertyValue The value of the property
 * @return The PropertyDescriptor
 */
public static PropertyDescriptor getPropertyDescriptorForValue(Object instance, Object propertyValue) {
    if (instance == null || propertyValue == null) {
        return null;
    }

    PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(instance.getClass());
    for (PropertyDescriptor pd : descriptors) {
        if (isAssignableOrConvertibleFrom(pd.getPropertyType(), propertyValue.getClass())) {
            Object value;
            try {
                ReflectionUtils.makeAccessible(pd.getReadMethod());
                value = pd.getReadMethod().invoke(instance);
            } catch (Exception e) {
                throw new FatalBeanException("Problem calling readMethod of " + pd, e);
            }
            if (propertyValue.equals(value)) {
                return pd;
            }
        }
    }
    return null;
}

From source file:grails.util.GrailsClassUtils.java

/**
 * Retrieves all the properties of the given class for the given type
 *
 * @param clazz The class to retrieve the properties from
 * @param propertyType The type of the properties you wish to retrieve
 *
 * @return An array of PropertyDescriptor instances
 *///from   ww w . j  a va  2s  .c o  m
public static PropertyDescriptor[] getPropertiesOfType(Class<?> clazz, Class<?> propertyType) {
    if (clazz == null || propertyType == null) {
        return new PropertyDescriptor[0];
    }

    Set<PropertyDescriptor> properties = new HashSet<PropertyDescriptor>();
    PropertyDescriptor descriptor = null;
    try {
        PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(clazz);
        for (int i = 0; i < descriptors.length; i++) {
            descriptor = descriptors[i];
            Class<?> currentPropertyType = descriptor.getPropertyType();
            if (isTypeInstanceOfPropertyType(propertyType, currentPropertyType)) {
                properties.add(descriptor);
            }
        }
    } catch (Exception e) {
        if (descriptor == null) {
            LOG.error(String.format("Got exception while checking property descriptors for class %s",
                    clazz.getName()), e);
        } else {
            LOG.error(String.format(
                    "Got exception while checking PropertyDescriptor.propertyType for field %s.%s",
                    clazz.getName(), descriptor.getName()), e);
        }
        // if there are any errors in instantiating just return null for the moment
        return new PropertyDescriptor[0];
    }
    return properties.toArray(new PropertyDescriptor[properties.size()]);
}

From source file:grails.util.GrailsClassUtils.java

/**
 * Retrieves all the properties of the given class which are assignable to the given type
 *
 * @param clazz             The class to retrieve the properties from
 * @param propertySuperType The type of the properties you wish to retrieve
 * @return An array of PropertyDescriptor instances
 *//*from   w w w.  j  a  va 2 s  .  co  m*/
public static PropertyDescriptor[] getPropertiesAssignableToType(Class<?> clazz, Class<?> propertySuperType) {
    if (clazz == null || propertySuperType == null)
        return new PropertyDescriptor[0];

    Set<PropertyDescriptor> properties = new HashSet<PropertyDescriptor>();
    PropertyDescriptor descriptor = null;
    try {
        PropertyDescriptor[] descriptors = BeanUtils.getPropertyDescriptors(clazz);
        for (int i = 0; i < descriptors.length; i++) {
            descriptor = descriptors[i];
            Class<?> currentPropertyType = descriptor.getPropertyType();
            if (propertySuperType.isAssignableFrom(descriptor.getPropertyType())) {
                properties.add(descriptor);
            }
        }
    } catch (Exception e) {
        if (descriptor == null) {
            LOG.error(String.format("Got exception while checking property descriptors for class %s",
                    clazz.getName()), e);
        } else {
            LOG.error(String.format(
                    "Got exception while checking PropertyDescriptor.propertyType for field %s.%s",
                    clazz.getName(), descriptor.getName()), e);
        }
        return new PropertyDescriptor[0];
    }
    return properties.toArray(new PropertyDescriptor[properties.size()]);
}

From source file:it.doqui.index.ecmengine.client.webservices.AbstractWebServiceDelegateBase.java

@SuppressWarnings("unchecked")
protected Object convertDTO(Object sourceDTO, Class destDTOClass) throws Exception {
    if (log.isDebugEnabled()) {
        log.debug("[" + getClass().getSimpleName() + "::convertDTO] BEGIN");
    }/*ww  w. j a  v  a2  s.  c  o  m*/

    Object destDTO = null;
    try {
        if (sourceDTO != null) {
            if (log.isDebugEnabled()) {
                log.debug("[" + getClass().getSimpleName() + "::convertDTO] converting DTO from type "
                        + sourceDTO.getClass().getName() + " to type " + destDTOClass.getName());
            }
            destDTO = BeanUtils.instantiateClass(destDTOClass);
            PropertyDescriptor[] targetpds = BeanUtils.getPropertyDescriptors(destDTOClass);
            PropertyDescriptor sourcepd = null;
            if (log.isDebugEnabled()) {
                log.debug(" found " + targetpds.length + " properties for type " + destDTOClass.getName());
            }

            for (int i = 0; i < targetpds.length; i++) {
                if (targetpds[i].getWriteMethod() != null) {
                    Method writeMethod = targetpds[i].getWriteMethod();
                    sourcepd = BeanUtils.getPropertyDescriptor(sourceDTO.getClass(), targetpds[i].getName());
                    if (sourcepd != null && sourcepd.getReadMethod() != null) {
                        if (log.isDebugEnabled()) {
                            log.debug("[" + getClass().getSimpleName() + "::convertDTO] found property: "
                                    + targetpds[i].getName());
                            log.debug("[" + getClass().getSimpleName() + "::convertDTO] source type: "
                                    + sourcepd.getPropertyType().getName() + ", dest type: "
                                    + targetpds[i].getPropertyType().getName());
                        }
                        Method readMethod = sourcepd.getReadMethod();
                        Object valueObject = null;
                        if (!BeanUtils.isSimpleProperty(targetpds[i].getPropertyType())) {
                            if (sourcepd.getPropertyType().isArray()) {
                                valueObject = convertDTOArray(
                                        (Object[]) readMethod.invoke(sourceDTO, new Object[] {}),
                                        targetpds[i].getPropertyType().getComponentType());
                            } else if (sourcepd.getPropertyType().equals(java.util.Calendar.class)
                                    && targetpds[i].getPropertyType().equals(java.util.Date.class)) {
                                // if java.util.Calendar => convert to java.util.Date
                                valueObject = readMethod.invoke(sourceDTO, new Object[0]);
                                if (valueObject != null) {
                                    valueObject = ((Calendar) valueObject).getTime();
                                }
                            } else if (sourcepd.getPropertyType().equals(java.util.Date.class)
                                    && targetpds[i].getPropertyType().equals(java.util.Calendar.class)) {
                                // if java.util.Date => convert to java.util.Calendar
                                Calendar calendar = Calendar.getInstance();
                                valueObject = readMethod.invoke(sourceDTO, new Object[0]);
                                if (valueObject != null) {
                                    calendar.setTime((Date) valueObject);
                                    valueObject = calendar;
                                }
                            } else {
                                valueObject = convertDTO(readMethod.invoke(sourceDTO, new Object[0]),
                                        targetpds[i].getPropertyType());
                            }
                        } else {
                            valueObject = readMethod.invoke(sourceDTO, new Object[0]);
                        }
                        if (log.isDebugEnabled()) {
                            log.debug("[" + getClass().getSimpleName() + "::convertDTO] writing value: "
                                    + valueObject);
                        }
                        writeMethod.invoke(destDTO, new Object[] { valueObject });
                    } else {
                        if (log.isDebugEnabled()) {
                            log.debug("[" + getClass().getSimpleName() + "::convertDTO] skipping property: "
                                    + targetpds[i].getName());
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        log.error("[" + getClass().getSimpleName() + "::convertDTO] ERROR", e);
        throw e;
    } finally {
        if (log.isDebugEnabled()) {
            log.debug("[" + getClass().getSimpleName() + "::convertDTO] END");
        }
    }
    return destDTO;
}

From source file:jp.co.ctc_g.jfw.core.util.Beans.java

/**
 * ????????/*from ww  w  .j  av  a2 s.  c om*/
 * @param clazz 
 * @return 
 */
public static PropertyDescriptor[] findPropertyDescriptorsFor(Class<?> clazz) {
    Args.checkNotNull(clazz);
    return BeanUtils.getPropertyDescriptors(clazz);
}

From source file:org.apache.syncope.core.persistence.jpa.entity.AbstractEntity.java

/**
 * @return fields to be excluded when computing equals() or hashcode()
 *///from   w  w w.  j  a v a  2  s  .  c  om
private String[] getExcludeFields() {
    Set<String> excludeFields = new HashSet<>();

    for (PropertyDescriptor propDesc : BeanUtils.getPropertyDescriptors(getClass())) {
        if (propDesc.getPropertyType().isInstance(Collections.emptySet())
                || propDesc.getPropertyType().isInstance(Collections.emptyList())) {

            excludeFields.add(propDesc.getName());
        }
    }

    return excludeFields.toArray(new String[] {});
}

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

private void init() {
    FieldCallback fieldCallback = new ReflectionUtils.FieldCallback() {
        public void doWith(Field field) {
            if (field.isSynthetic()) {
                return;
            }/* ww  w.  j a va  2s  .  com*/
            final int modifiers = field.getModifiers();
            if (!Modifier.isPublic(modifiers)) {
                return;
            }

            final String name = field.getName();
            if (name.indexOf('$') == -1) {
                boolean staticField = Modifier.isStatic(modifiers);
                if (staticField) {
                    staticFetchers.put(name, new FieldReaderFetcher(field, staticField));
                } else {
                    instanceFetchers.put(name, new FieldReaderFetcher(field, staticField));
                }
            }
        }
    };

    MethodCallback methodCallback = new ReflectionUtils.MethodCallback() {
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            if (method.isSynthetic()) {
                return;
            }
            if (!Modifier.isPublic(method.getModifiers())) {
                return;
            }
            if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() != Void.class) {
                if (method.getParameterTypes().length == 0) {
                    String name = method.getName();
                    if (name.indexOf('$') == -1) {
                        if (name.length() > 3 && name.startsWith("get")
                                && Character.isUpperCase(name.charAt(3))) {
                            name = name.substring(3);
                        } else if (name.length() > 2 && name.startsWith("is")
                                && Character.isUpperCase(name.charAt(2))
                                && (method.getReturnType() == Boolean.class
                                        || method.getReturnType() == boolean.class)) {
                            name = name.substring(2);
                        }
                        PropertyFetcher fetcher = new GetterPropertyFetcher(method, true);
                        staticFetchers.put(name, fetcher);
                        staticFetchers.put(StringUtils.uncapitalize(name), fetcher);
                    }
                }
            }
        }
    };

    List<Class<?>> allClasses = resolveAllClasses(clazz);
    for (Class<?> c : allClasses) {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            try {
                fieldCallback.doWith(field);
            } catch (IllegalAccessException ex) {
                throw new IllegalStateException(
                        "Shouldn't be illegal to access field '" + field.getName() + "': " + ex);
            }
        }
        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            try {
                methodCallback.doWith(method);
            } catch (IllegalAccessException ex) {
                throw new IllegalStateException(
                        "Shouldn't be illegal to access method '" + method.getName() + "': " + ex);
            }
        }
    }

    propertyDescriptors = BeanUtils.getPropertyDescriptors(clazz);
    for (PropertyDescriptor desc : propertyDescriptors) {
        Method readMethod = desc.getReadMethod();
        if (readMethod != null) {
            boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers());
            if (staticReadMethod) {
                staticFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod));
            } else {
                instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod));
            }
        }
    }
}

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

/**
 * Retrieves all the properties of the given class which are assignable to the given type
 *
 * @param clazz             The class to retrieve the properties from
 * @param propertySuperType The type of the properties you wish to retrieve
 * @return An array of PropertyDescriptor instances
 *//*from ww  w .ja  va 2 s .co  m*/
public static PropertyDescriptor[] getPropertiesAssignableToType(Class<?> clazz, Class<?> propertySuperType) {
    if (clazz == null || propertySuperType == null)
        return new PropertyDescriptor[0];

    Set<PropertyDescriptor> properties = new HashSet<PropertyDescriptor>();
    try {
        for (PropertyDescriptor descriptor : BeanUtils.getPropertyDescriptors(clazz)) {
            if (propertySuperType.isAssignableFrom(descriptor.getPropertyType())) {
                properties.add(descriptor);
            }
        }
    } catch (Exception e) {
        return new PropertyDescriptor[0];
    }
    return properties.toArray(new PropertyDescriptor[properties.size()]);
}