Example usage for java.beans PropertyDescriptor getName

List of usage examples for java.beans PropertyDescriptor getName

Introduction

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

Prototype

public String getName() 

Source Link

Document

Gets the programmatic name of this feature.

Usage

From source file:org.archive.spring.ConfigPathConfigurer.java

/**
 * Find any ConfigPath properties in the passed bean; ensure that
 * if they have a null 'base', that is replaced with the job home
 * directory. Also, remember all ConfigPaths so fixed-up for later
 * reference. //from ww w . j  a  v  a2s .c om
 * 
 * @param bean
 * @param beanName
 * @return Same bean as passed in, fixed as necessary
 */
protected Object fixupPaths(Object bean, String beanName) {
    BeanWrapperImpl wrapper = new BeanWrapperImpl(bean);
    for (PropertyDescriptor d : wrapper.getPropertyDescriptors()) {
        if (d.getPropertyType().isAssignableFrom(ConfigPath.class)
                || d.getPropertyType().isAssignableFrom(ConfigFile.class)) {
            Object value = wrapper.getPropertyValue(d.getName());
            if (value != null && value instanceof ConfigPath) {
                String patchName = beanName + "." + d.getName();
                fixupConfigPath((ConfigPath) value, patchName);
            }
        } else if (Iterable.class.isAssignableFrom(d.getPropertyType())) {
            Iterable<?> iterable = (Iterable<?>) wrapper.getPropertyValue(d.getName());
            if (iterable != null) {
                int i = 0;
                for (Object candidate : iterable) {
                    if (candidate != null && candidate instanceof ConfigPath) {
                        String patchName = beanName + "." + d.getName() + "[" + i + "]";
                        fixupConfigPath((ConfigPath) candidate, patchName);
                    }
                    i++;
                }
            }
        }
    }
    return bean;
}

From source file:com.nortal.petit.beanmapper.BeanMappingFactoryImpl.java

@SuppressWarnings("unchecked")
private <B> void initProperty(Map<String, Property<B, Object>> props, List<Property<B, Object>> idProps,
        String name, Class<B> type) {
    PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(type, name);

    if (!isPropertyReadableAndWritable(pd)) {
        return;//from www . ja va 2 s  . c o m
    }

    List<Annotation> ans = BeanMappingReflectionUtils.readAnnotations(type, pd.getName());

    if (BeanMappingReflectionUtils.getAnnotation(ans, Transient.class) != null) {
        return;
    }

    Column column = BeanMappingReflectionUtils.getAnnotation(ans, Column.class);

    ReflectionProperty<B, Object> prop = new ReflectionProperty<B, Object>(name,
            (Class<Object>) pd.getPropertyType(), inferColumn(name, column), pd.getWriteMethod(),
            pd.getReadMethod());

    if (column != null) {
        prop.readOnly(!column.insertable());
    }

    if (BeanMappingReflectionUtils.getAnnotation(ans, Id.class) != null) {
        idProps.add(prop);
    }

    if (useAdditionalConfiguration()) {
        prop.getConfiguration().setAnnotations(ans);
        if (Collection.class.isAssignableFrom(pd.getPropertyType())) {
            prop.getConfiguration().setCollectionTypeArguments(
                    ((ParameterizedType) pd.getReadMethod().getGenericReturnType()).getActualTypeArguments());
        }
    }

    if (BeanMappingReflectionUtils.getAnnotation(ans, Embedded.class) != null) {
        props.putAll(getCompositeProperties(prop, ans));
    } else {
        props.put(prop.name(), prop);
    }
}

From source file:com.artistech.protobuf.TuioProtoConverter.java

@Override
public GeneratedMessage.Builder convertToProtobuf(Object obj) {
    GeneratedMessage.Builder builder;//from  w  ww .j a  v  a 2s  . c  o  m

    if (obj.getClass().getName().equals(TUIO.TuioTime.class.getName())) {
        builder = TuioProtos.Time.newBuilder();
    } else if (obj.getClass().getName().equals(TUIO.TuioCursor.class.getName())) {
        builder = TuioProtos.Cursor.newBuilder();
    } else if (obj.getClass().getName().equals(TUIO.TuioObject.class.getName())) {
        builder = TuioProtos.Object.newBuilder();
    } else if (obj.getClass().getName().equals(TUIO.TuioBlob.class.getName())) {
        builder = TuioProtos.Blob.newBuilder();
    } else if (obj.getClass().getName().equals(TUIO.TuioPoint.class.getName())) {
        builder = TuioProtos.Point.newBuilder();
    } else {
        return null;
    }

    try {
        PropertyDescriptor[] objProps = Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors();
        BeanInfo beanInfo = Introspector.getBeanInfo(builder.getClass());
        PropertyDescriptor[] builderProps = beanInfo.getPropertyDescriptors();
        Method[] methods = builder.getClass().getMethods();
        for (PropertyDescriptor prop1 : objProps) {
            for (PropertyDescriptor prop2 : builderProps) {
                if (prop1.getName().equals(prop2.getName())) {
                    Method readMethod = prop1.getReadMethod();
                    ArrayList<Method> methodsToTry = new ArrayList<>();
                    for (Method m : methods) {
                        if (m.getName().equals(readMethod.getName().replaceFirst("get", "set"))) {
                            methodsToTry.add(m);
                        }
                    }

                    for (Method setMethod : methodsToTry) {
                        try {
                            if (Iterable.class.isAssignableFrom(readMethod.getReturnType())) {
                                if (DeepCopy) {
                                    ArrayList<Method> methodsToTry2 = new ArrayList<>();
                                    for (Method m : methods) {
                                        if (m.getName()
                                                .equals(readMethod.getName().replaceFirst("get", "add"))) {
                                            methodsToTry2.add(m);
                                        }
                                    }

                                    boolean success = false;
                                    for (Method setMethod2 : methodsToTry2) {
                                        Iterable iter = (Iterable) readMethod.invoke(obj);
                                        Iterator it = iter.iterator();
                                        while (it.hasNext()) {
                                            Object o = it.next();
                                            //call set..
                                            for (ProtoConverter converter : services) {
                                                if (converter.supportsConversion(o)) {
                                                    try {
                                                        GeneratedMessage.Builder convertToProtobuf = converter
                                                                .convertToProtobuf(o);
                                                        setMethod2.invoke(builder, convertToProtobuf);
                                                        success = true;
                                                        break;
                                                    } catch (IllegalAccessException | IllegalArgumentException
                                                            | InvocationTargetException ex) {

                                                    }
                                                }
                                            }
                                        }
                                        if (success) {
                                            break;
                                        }
                                    }
                                }
                            } else {
                                boolean primitiveOrWrapper = ClassUtils
                                        .isPrimitiveOrWrapper(readMethod.getReturnType());

                                if (primitiveOrWrapper) {
                                    setMethod.invoke(builder, readMethod.invoke(obj));
                                } else {
                                    Object invoke = readMethod.invoke(obj);
                                    com.google.protobuf.GeneratedMessage.Builder val = convertToProtobuf(
                                            invoke);

                                    setMethod.invoke(builder, val);
                                    break;
                                }
                            }
                        } catch (IllegalAccessException | IllegalArgumentException
                                | InvocationTargetException ex) {
                            //                            Logger.getLogger(TuioProtoConverter.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        break;
                    }
                }
            }
        }
    } catch (IntrospectionException ex) {
        logger.fatal(ex);
    }

    return builder;
}

From source file:edu.harvard.med.screensaver.model.AbstractEntity.java

/**
 * Performs a shallow compare of this <code>AbstractEntity</code> with another
 * and returns <code>true</code> iff they are the exact same class and have
 * matching values for each property, excluding properties that return
 * <code>Collection</code>, <code>Map</code>, and <code>AbstractEntity</code>,
 * which, presumably, return entity relationships.
 * /* www.  j  a  v a2s . co  m*/
 * @motivation for comparing entities in test code
 * @param that the other AbstractEntity to compare equivalency with
 * @return true iff the two AbstractEntities are equivalent
 */
public boolean isEquivalent(AbstractEntity that) {
    if (!this.getClass().equals(that.getClass())) {
        return false;
    }
    PropertyDescriptor[] beanProperties = PropertyUtils.getPropertyDescriptors(this.getClass());

    for (int i = 0; i < beanProperties.length; i++) {
        PropertyDescriptor beanProperty = beanProperties[i];
        if (isEquivalenceProperty(beanProperty)) {
            String propertyName = beanProperty.getName();
            try {
                Object thisValue = beanProperty.getReadMethod().invoke(this);
                Object thatValue = beanProperty.getReadMethod().invoke(that);
                if (thisValue == null ^ thatValue == null
                        || thisValue != null && !thisValue.equals(thatValue)) {
                    log.debug("property '" + propertyName + "' differs: this='" + thisValue + "', that='"
                            + thatValue + "'");
                    return false;
                }
            } catch (Exception e) {
                log.error("error comparing bean properties: " + e.getMessage());
                return false;
            }
        }
    }
    return true;
}

From source file:com.expressui.core.view.field.SelectField.java

private void assertValidPropertyId() {
    boolean propertyIdFound = false;
    Class<T> beanType = typedForm.getType();
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanType);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        if (propertyDescriptor.getName().equals(getPropertyId())) {
            propertyIdFound = true;/*  ww w .  ja v  a  2 s  . c  o m*/
        }
    }

    Assert.PROGRAMMING.isTrue(propertyIdFound,
            "property not found: " + beanType.getName() + "." + getPropertyId());
}

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;/*from  w  w  w . j a 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:com.khubla.cbean.CBeanType.java

/**
 * build the map of getters and setters to properties
 *///from w w  w  . j a  v  a2 s.  c  om
private void buildGetterSetterMap() {
    final PropertyUtilsBean propertyUtilsBean = new PropertyUtilsBean();
    final PropertyDescriptor[] propertyDescriptors = propertyUtilsBean.getPropertyDescriptors(clazz);
    if (null != propertyDescriptors) {
        for (int i = 0; i < propertyDescriptors.length; i++) {
            final PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
            if (null != propertyDescriptor.getReadMethod()) {
                getterMap.put(propertyDescriptor.getReadMethod().getName(), propertyDescriptor.getName());
            }
            if (null != propertyDescriptor.getWriteMethod()) {
                setterMap.put(propertyDescriptor.getWriteMethod().getName(), propertyDescriptor.getName());
            }
        }
    }
}

From source file:com.zhumeng.dream.orm.hibernate.HibernateDao.java

/**
 * ?,hibernate???select count(o) from Xxx o?BUG,
 * hibernatejpql??sqlselect count(field1,field2,...),count()
 * ??HQL?:"select count(*) from Object"//  ww w  . ja v a2s  . c  o  m
 * @author: lizhong
 * @param <E>
 * @param clazz
 * @return
 */
protected static <E> String getCountField(Class<E> clazz) {
    String out = "o";
    try {
        PropertyDescriptor[] propertys = Introspector.getBeanInfo(clazz).getPropertyDescriptors();
        for (PropertyDescriptor property : propertys) {
            Method method = property.getReadMethod();
            if (method != null && method.isAnnotationPresent(EmbeddedId.class)) {
                PropertyDescriptor[] props = Introspector.getBeanInfo(property.getPropertyType())
                        .getPropertyDescriptors();
                out = "o." + property.getName() + "."
                        + (!props[1].getName().equals("class") ? props[1].getName() : props[0].getName());
                break;
            }
        }
    } catch (IntrospectionException e) {
        e.printStackTrace();
    }
    return out;
}

From source file:com.artistech.protobuf.TuioProtoConverter.java

@Override
public Object convertFromProtobuf(final GeneratedMessage obj) {
    Object target;//from   w  w  w.j a  v a 2  s  .  c  o  m

    if (TuioProtos.Blob.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioBlob();
    } else if (TuioProtos.Time.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioTime();
    } else if (TuioProtos.Cursor.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioCursor();
    } else if (TuioProtos.Object.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioObject();
    } else if (TuioProtos.Point.class.isAssignableFrom(obj.getClass())) {
        target = new TUIO.TuioPoint();
    } else {
        return null;
    }

    try {
        PropertyDescriptor[] targetProps = Introspector.getBeanInfo(target.getClass()).getPropertyDescriptors();

        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] messageProps = beanInfo.getPropertyDescriptors();
        Method[] methods = obj.getClass().getMethods();

        for (PropertyDescriptor targetProp : targetProps) {
            for (PropertyDescriptor messageProp : messageProps) {
                if (targetProp.getName().equals(messageProp.getName())) {
                    Method writeMethod = targetProp.getWriteMethod();
                    Method readMethod = null;
                    for (Method m : methods) {
                        if (writeMethod != null
                                && m.getName().equals(writeMethod.getName().replaceFirst("set", "get"))) {
                            readMethod = m;
                            break;
                        }
                    }
                    try {
                        if (writeMethod != null && readMethod != null && targetProp.getReadMethod() != null) {
                            boolean primitiveOrWrapper = ClassUtils
                                    .isPrimitiveOrWrapper(targetProp.getReadMethod().getReturnType());

                            if (readMethod.getParameterTypes().length > 0) {
                                if (DeepCopy) {
                                    if (!Modifier.isAbstract(targetProp.getPropertyType().getModifiers())) {
                                        //basically, ArrayList
                                        Object newInstance = targetProp.getPropertyType().newInstance();
                                        Method addMethod = newInstance.getClass().getMethod("add",
                                                Object.class);
                                        Method m = obj.getClass().getMethod(readMethod.getName() + "Count");
                                        int size = (int) m.invoke(obj);
                                        for (int ii = 0; ii < size; ii++) {
                                            Object o = readMethod.invoke(obj, ii);
                                            addMethod.invoke(newInstance, o);
                                        }
                                        writeMethod.invoke(target, newInstance);
                                    } else if (Collection.class
                                            .isAssignableFrom(targetProp.getPropertyType())) {
                                        //do something if it is a collection or iterable...
                                    }
                                }
                            } else if (primitiveOrWrapper) {
                                writeMethod.invoke(target, messageProp.getReadMethod().invoke(obj));
                            } else {
                                if (GeneratedMessage.class
                                        .isAssignableFrom(messageProp.getReadMethod().getReturnType())) {

                                    GeneratedMessage invoke = (GeneratedMessage) messageProp.getReadMethod()
                                            .invoke(obj);
                                    Object val = null;
                                    for (ProtoConverter converter : services) {
                                        if (converter.supportsConversion(invoke)) {
                                            val = convertFromProtobuf(invoke);
                                            break;
                                        }
                                    }
                                    if (val != null) {
                                        writeMethod.invoke(target, val);
                                    }
                                }
                                //                                    System.out.println("Prop1 Name!: " + targetProp.getName());
                            }
                        }
                    } catch (NullPointerException ex) {
                        //Logger.getLogger(ZeroMqMouse.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (InstantiationException | NoSuchMethodException | IllegalArgumentException
                            | SecurityException | IllegalAccessException | InvocationTargetException ex) {
                        logger.error(ex);
                    }
                    break;
                }
            }
        }
    } catch (java.beans.IntrospectionException ex) {
        logger.fatal(ex);
    }
    return target;
}

From source file:es.logongas.ix3.web.json.impl.JsonReaderImplEntityJackson.java

/**
 * Obtiene el valor de la propiedad de un Bean
 *
 * @param obj El objeto Bean//from   www. j  a  v  a 2 s .  c  o  m
 * @param propertyName El nombre de la propiedad
 * @return El valor de la propiedad
 */
private Object getValueFromBean(Object obj, String propertyName) {
    try {
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

        Method readMethod = null;
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            if (propertyDescriptor.getName().equals(propertyName)) {
                readMethod = propertyDescriptor.getReadMethod();
            }
        }

        if (readMethod == null) {
            throw new RuntimeException(
                    "No existe la propiedad:" + propertyName + " en " + obj.getClass().getName());
        }

        return readMethod.invoke(obj);

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