Example usage for java.beans PropertyDescriptor PropertyDescriptor

List of usage examples for java.beans PropertyDescriptor PropertyDescriptor

Introduction

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

Prototype

PropertyDescriptor(PropertyDescriptor x, PropertyDescriptor y) 

Source Link

Document

Package-private constructor.

Usage

From source file:com.maomao.framework.dao.jdbc.JdbcDAO.java

@SuppressWarnings("rawtypes")
private Column2Property getIdFromObject(Class clazz) throws Exception {

    // ???/* www  .j a va  2  s  . c  om*/
    Column2Property c = null;
    for (Field field : clazz.getDeclaredFields()) {
        String columnName = null;
        Annotation[] annotations = field.getDeclaredAnnotations();
        for (Annotation a : annotations) {
            if (a instanceof Id) {
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                c = new Column2Property();
                c.propertyName = pd.getName();
                c.setterMethodName = pd.getWriteMethod().getName();
                c.getterMethodName = pd.getReadMethod().getName();
                c.columnName = columnName;
                break;
            }
        }
    }

    if (c == null) {
        Class superClass = clazz.getSuperclass();
        for (Field field : superClass.getDeclaredFields()) {
            String columnName = null;
            Annotation[] annotations = field.getDeclaredAnnotations();
            for (Annotation a : annotations) {
                if (a instanceof Id) {
                    PropertyDescriptor pd = new PropertyDescriptor(field.getName(), superClass);
                    c = new Column2Property();
                    c.propertyName = pd.getName();
                    c.setterMethodName = pd.getWriteMethod().getName();
                    c.getterMethodName = pd.getReadMethod().getName();
                    c.columnName = columnName;
                    break;

                }
            }
        }
    }

    return c;
}

From source file:com.haulmont.cuba.restapi.XMLConverter.java

private void setField(Object result, String fieldName, Object value)
        throws IllegalAccessException, InvocationTargetException, IntrospectionException {
    new PropertyDescriptor(fieldName, result.getClass()).getWriteMethod().invoke(result, value);
}

From source file:nl.ucan.navigate.NestedPath.java

private static Class getCollectionReturnType(String property, Class clasz) throws IntrospectionException {
    PropertyDescriptor propertyDescriptor = new PropertyDescriptor(property, clasz);
    Method method = propertyDescriptor.getReadMethod();
    Class klass = GenericCollectionTypeResolver.getCollectionReturnType(method);
    if (klass == null) {
        klass = GenericTypeResolver.resolveReturnType(method, clasz);
        if (klass.isArray()) {
            return klass.getComponentType();
        } else {/*from w  w  w . ja v  a  2s. c  om*/
            throw new IllegalStateException("unsupported return type");
        }
    } else
        return klass;
}

From source file:org.firebrandocm.dao.ClassMeta.java

/**
     * Private helper that caches information for a property for further persistence consideration
     *//w ww  .jav a  2 s . c  om
     * @param colAnnotation   the column annotation
     * @param propertyName    the property name
     * @param type            the property type
     * @param indexed         whether the property should be indexed in the data store
     * @param lazy            if access to this property should be loaded on demand
     * @param counter         if this property represents a counter
     * @param counterIncrease if this property represents a value for a counter arithmetic operation
     */
    private void addProperty(Column colAnnotation, String propertyName, Class<?> type, boolean indexed,
            boolean lazy, boolean counter, boolean counterIncrease)
            throws ClassNotFoundException, IntrospectionException {
        propertiesTypesMap.put(propertyName, type);
        mutationProperties.add(propertyName);
        if (indexed) {
            indexedProperties.add(propertyName);
            log.debug(String.format("added indexed property %s", propertyName));
        }
        if (lazy) {
            PropertyDescriptor descriptor = new PropertyDescriptor(propertyName, target);
            lazyAccesors.put(descriptor.getReadMethod(), propertyName);
            lazyProperties.add(propertyName);
        }
        if (counter) {
            counterProperties.add(propertyName);
        }
        if (!counterIncrease) {
            selectionProperties.add(propertyName);
            addColumnToColumnFamilyDefinition(colAnnotation, propertyName, indexed);
        }
        log.debug(String.format("added property %s", propertyName));
    }

From source file:com.cnd.greencube.server.dao.jdbc.JdbcDAO.java

@SuppressWarnings("rawtypes")
private List<Column2Property> getColumnsFromObj(Object obj, String[] columns) {
    Class clazz = obj.getClass();
    List<Column2Property> validColumns = new ArrayList<Column2Property>();

    // ???/*from  w  w  w  . j ava2 s.com*/
    for (Field field : clazz.getDeclaredFields()) {
        boolean skip = true;
        String columnName = null;
        Annotation[] annotations = field.getAnnotations();
        for (Annotation a : annotations) {
            if (a instanceof Column) {
                columnName = ((Column) a).name();
                if (columns != null && !_inarray_(columns, columnName))
                    skip = true;
                else {
                    skip = false;
                }

                break;
            }
        }

        String s = field.getName();
        PropertyDescriptor pd = null;

        if (!skip) {
            // ?gettersetter
            try {
                pd = new PropertyDescriptor(s, clazz);
                if (pd == null || pd.getWriteMethod() == null || pd.getReadMethod() == null) {
                    skip = true;
                }
            } catch (Exception e) {
                skip = true;
            }
        }

        if (!skip) {
            Column2Property c = new Column2Property();
            c.propertyName = pd.getName();
            c.setterMethodName = pd.getWriteMethod().getName();
            c.getterMethodName = pd.getReadMethod().getName();
            c.columnName = columnName;
            validColumns.add(c);
        }
    }

    Column2Property c = new Column2Property();
    c.propertyName = "id";
    c.setterMethodName = "setId";
    c.getterMethodName = "getId";
    c.columnName = "C_ID";
    validColumns.add(c);

    return validColumns;
}

From source file:org.apache.openjpa.lib.conf.ConfigurationImpl.java

/**
 * Create a property descriptor for the given value.
 *//*from   ww  w.ja  va 2s  .co m*/
private PropertyDescriptor getPropertyDescriptor(Value val) throws IntrospectionException {
    String prop = val.getProperty();
    prop = prop.substring(prop.lastIndexOf('.') + 1);

    // set up property descriptor
    PropertyDescriptor pd;
    try {
        pd = new PropertyDescriptor(Introspector.decapitalize(prop), getClass());
    } catch (IntrospectionException ie) {
        // if there aren't any methods for this value(i.e., if it's a
        // dynamically-added value), then an IntrospectionException will
        // be thrown. Try to create a PD with no read or write methods.
        pd = new PropertyDescriptor(Introspector.decapitalize(prop), (Method) null, (Method) null);
    }
    pd.setDisplayName(findLocalized(prop + "-name", true, val.getScope()));
    pd.setShortDescription(findLocalized(prop + "-desc", true, val.getScope()));
    pd.setExpert("true".equals(findLocalized(prop + "-expert", false, val.getScope())));

    try {
        pd.setReadMethod(getClass().getMethod("get" + StringUtils.capitalize(prop), (Class[]) null));
        pd.setWriteMethod(getClass().getMethod("set" + StringUtils.capitalize(prop),
                new Class[] { pd.getReadMethod().getReturnType() }));
    } catch (Throwable t) {
        // if an error occurs, it might be because the value is a
        // dynamic property.
    }

    String type = findLocalized(prop + "-type", true, val.getScope());
    if (type != null)
        pd.setValue(ATTRIBUTE_TYPE, type);

    String cat = findLocalized(prop + "-cat", false, val.getScope());
    if (cat != null)
        pd.setValue(ATTRIBUTE_CATEGORY, cat);

    pd.setValue(ATTRIBUTE_XML, toXMLName(prop));

    String order = findLocalized(prop + "-displayorder", false, val.getScope());
    if (order != null)
        pd.setValue(ATTRIBUTE_ORDER, order);

    // collect allowed values from alias keys, listed values, and
    // interface implementors
    Collection<String> allowed = new TreeSet<String>();
    List<String> aliases = Collections.emptyList();
    if (val.getAliases() != null) {
        aliases = Arrays.asList(val.getAliases());
        for (int i = 0; i < aliases.size(); i += 2)
            allowed.add(aliases.get(i));
    }
    String[] vals = Strings.split(findLocalized(prop + "-values", false, val.getScope()), ",", 0);
    for (int i = 0; i < vals.length; i++)
        if (!aliases.contains(vals[i]))
            allowed.add(vals[i]);
    try {
        Class<?> intf = Class.forName(findLocalized(prop + "-interface", true, val.getScope()), false,
                getClass().getClassLoader());
        pd.setValue(ATTRIBUTE_INTERFACE, intf.getName());
        String[] impls = Services.getImplementors(intf);
        for (int i = 0; i < impls.length; i++)
            if (!aliases.contains(impls[i]))
                allowed.add(impls[i]);
    } catch (Throwable t) {
    }
    if (!allowed.isEmpty())
        pd.setValue(ATTRIBUTE_ALLOWED_VALUES, (String[]) allowed.toArray(new String[allowed.size()]));

    return pd;
}

From source file:de.terrestris.shogun.dao.DatabaseDao.java

private Criteria setEagerFetchModeForCollections(Criteria criteria, Class<?> clazz) {

    List<Field> fields = getAllFields(new ArrayList<Field>(), clazz);

    for (Field field : fields) {

        boolean isJsonIgnore = false;

        Method getterMethod;/*from  ww  w .j  ava2  s  .  co m*/
        try {
            getterMethod = new PropertyDescriptor(field.getName(), clazz).getReadMethod();
            Annotation[] anoArr = getterMethod.getAnnotations();
            for (Annotation annotation : anoArr) {
                if (annotation instanceof JsonIgnore) {
                    isJsonIgnore = true;
                }
            }
        } catch (IntrospectionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        if (!isJsonIgnore && field.getType().isAssignableFrom(Set.class)) {
            // yes, we have to set the fetch mode
            criteria.setFetchMode(field.getName(), FetchMode.JOIN);
        }
    }

    return criteria;
}

From source file:de.xwic.appkit.webbase.viewer.EntityTableViewer.java

private boolean propertyExists(String propertyId) {
    if (propertyId == null) {
        return false;
    }//from w w  w  . j a  v  a  2 s. c o m

    StringTokenizer stk = new StringTokenizer(propertyId, ".");
    Class<?> clazz = daoClass.getEntityClass();

    for (int nr = 0; stk.hasMoreTokens(); nr++) {
        PropertyDescriptor desc;
        try {
            desc = new PropertyDescriptor(stk.nextToken(), clazz);
            clazz = desc.getPropertyType();
        } catch (IntrospectionException e) {
            return false;
        }
    }

    return true;
}

From source file:de.terrestris.shogun.dao.DatabaseDao.java

/**
 * TODO move to a better place or use existing functionality elsewhere.
 * TODO we have a very similar method in {@link HibernateFilterItem}.
 *
 * @param fields//from   w w  w .j a v a 2s. com
 * @param type
 * @return
 * @throws NoSuchFieldException
 * @throws SecurityException
 * @throws IntrospectionException
 */
public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
    for (Field field : type.getDeclaredFields()) {

        // check if the filed is not a constant
        if (Modifier.isStatic(field.getModifiers()) == false
                && Modifier.isFinal(field.getModifiers()) == false) {

            // now we check if the readmethod of the field
            // has NOT a transient annotation
            try {
                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), type);
                Method readmethod = pd.getReadMethod();
                Annotation[] annotationsArr = readmethod.getAnnotations();
                if (annotationsArr.length == 0) {
                    fields.add(field);
                } else {
                    for (Annotation annotation : annotationsArr) {
                        if (annotation.annotationType().equals(javax.persistence.Transient.class) == false) {
                            fields.add(field);
                        }
                    }
                }
            } catch (IntrospectionException e) {
                LOGGER.error("Trying to determine the getter for field '" + field.getName() + "' in "
                        + type.getSimpleName() + " threw IntrospectionException."
                        + " Is there a getter following the Java-Beans" + " Specification?");
            }
        }

    }

    if (type.getSuperclass() != null) {
        fields = getAllFields(fields, type.getSuperclass());
    }

    return fields;
}

From source file:de.terrestris.shogun.dao.DatabaseDao.java

/**
 *
 * @param list//from  www . j  a v a  2s . co  m
 * @param mainClass
 */
protected void initializeDeepList(List<? extends Object> list, Class<?> mainClass) {
    List<Field> fields = getAllFields(new ArrayList<Field>(), mainClass);
    List<Method> methods = new ArrayList<Method>();

    for (Field field : fields) {
        if (field.getType().isAssignableFrom(Set.class)) {
            // yes, we have to initialize this field via its getter
            Method method = null;
            try {
                method = new PropertyDescriptor(field.getName(), mainClass).getReadMethod();
            } catch (IntrospectionException e) {
                LOGGER.error("Failed to determine getter for field '" + field.getName() + "' of class '"
                        + mainClass.getSimpleName() + "'.");
            }
            methods.add(method);
        }
    }

    for (Iterator<Object> iterator = (Iterator<Object>) list.iterator(); iterator.hasNext();) {
        Object obj = iterator.next();
        if (obj == null) {
            continue;
        }
        for (Method method : methods) {
            String errMsg = "Failed to invoke getter '" + method.getName() + "' of class '"
                    + mainClass.getSimpleName() + "': ";
            try {
                Hibernate.initialize(method.invoke(obj));
            } catch (HibernateException e) {
                LOGGER.error(errMsg + " HibernateException '" + e.getMessage() + "'.");
            } catch (IllegalArgumentException e) {
                LOGGER.error(errMsg + " IllegalArgumentException '" + e.getMessage() + "'.");
            } catch (IllegalAccessException e) {
                LOGGER.error(errMsg + " IllegalAccessException '" + e.getMessage() + "'.");
            } catch (InvocationTargetException e) {
                LOGGER.error(errMsg + " InvocationTargetException '" + e.getMessage() + "'.");
            }
        }
    }
}