Example usage for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors

List of usage examples for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils getPropertyDescriptors.

Prototype

public static PropertyDescriptor[] getPropertyDescriptors(Object bean) 

Source Link

Document

Retrieve the property descriptors for the specified bean, introspecting and caching them the first time a particular bean class is encountered.

For more details see PropertyUtilsBean.

Usage

From source file:gov.nih.nci.caarray.external.v1_0.AbstractCaArrayEntityTest.java

private void setSomeProperty(AbstractCaArrayEntity a) throws Exception {
    PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(a);
    for (PropertyDescriptor p : pds) {
        if (p.getName().equals("id"))
            continue;
        if (p.getPropertyType() == String.class) {
            p.getWriteMethod().invoke(a, "some String");
            return;
        }// www .  ja  v  a  2 s.  com

        if (p.getPropertyType() == Person.class) {
            p.getWriteMethod().invoke(a, new Person());
            return;
        }

        if (p.getPropertyType() == FileMetadata.class) {
            p.getWriteMethod().invoke(a, new FileMetadata());
            return;
        }

    }

    throw new UnsupportedOperationException("did know how to set a property on " + a.getClass());
}

From source file:com.sf.ddao.crud.param.CRUDBeanPropsParameter.java

private synchronized void init(Context ctx) {
    if (descriptors != null) {
        return;//w w w  . j a  v  a2s. com
    }
    Class<?> beanClass = CRUDParameterService.getCRUDDaoBean(ctx, argNum);
    final PropertyDescriptor[] descriptors = PropertyUtils.getPropertyDescriptors(beanClass);
    List<PropertyDescriptor> res = new ArrayList<PropertyDescriptor>(descriptors.length);
    for (PropertyDescriptor descriptor : descriptors) {
        if (CRUDDao.IGNORED_PROPS.contains(descriptor.getName())) {
            continue;
        }
        final Method readMethod = descriptor.getReadMethod();
        if (readMethod == null) {
            continue;
        }
        if (readMethod.getAnnotation(CRUDIgnore.class) != null) {
            continue;
        }
        res.add(descriptor);
    }
    this.descriptors = res;
}

From source file:com.panguso.lc.analysis.format.dao.impl.DaoImpl.java

@Override
public List<T> search(T condition, int pageNo, int pageSize) {
    StringBuilder qString = new StringBuilder("select model from " + entityClass.getSimpleName() + " model");
    StringBuilder qWhere = new StringBuilder(" where ");
    StringBuilder qCondition = new StringBuilder();
    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(entityClass);
    for (int i = 0, count = propertyDescriptors.length; i < count; i++) {
        PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
        String name = propertyDescriptor.getName();
        Class<?> type = propertyDescriptor.getPropertyType();
        String value = null;//from   ww  w. ja  v  a  2 s. c o m
        try {
            value = BeanUtils.getProperty(condition, name);
        } catch (Exception e) {
            // ?
            continue;
        }
        if (value == null || name.equals("class")) {
            continue;
        }
        if ("java.lang.String".equals(type.getName())) {
            qCondition.append("model.");
            qCondition.append(name);
            qCondition.append(" like ");
            qCondition.append("'%");
            qCondition.append(value);
            qCondition.append("%'");
        } else {
            qCondition.append("model.");
            qCondition.append(name);
            qCondition.append("=");
            qCondition.append(value);
        }
        qCondition.append(" and ");

    }
    if (qCondition.length() != 0) {
        qString.append(qWhere).append(qCondition);
        if (qCondition.toString().endsWith(" and ")) {
            qString.delete(qString.length() - " and ".length(), qString.length());
        }
    }
    Query query = em.createQuery(qString.toString());
    query.setFirstResult(pageNo * pageSize);
    query.setMaxResults(pageSize);
    return query.getResultList();
}

From source file:com.fantasia.snakerflow.engine.SnakerHelper.java

private static String getProperty(NodeModel node) {
    StringBuffer buffer = new StringBuffer();
    buffer.append("props:{");
    try {// w  w  w  .ja  va2s . com
        PropertyDescriptor[] beanProperties = PropertyUtils.getPropertyDescriptors(node);
        for (PropertyDescriptor propertyDescriptor : beanProperties) {
            if (propertyDescriptor.getReadMethod() == null || propertyDescriptor.getWriteMethod() == null)
                continue;
            String name = propertyDescriptor.getName();
            String value = "";
            if (propertyDescriptor.getPropertyType() == String.class) {
                value = (String) BeanUtils.getProperty(node, name);
            } else {
                continue;
            }
            if (value == null || value.equals(""))
                continue;
            buffer.append(name);
            buffer.append(":{value:'");
            buffer.append(convert(value));
            buffer.append("'},");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    buffer.deleteCharAt(buffer.length() - 1);
    buffer.append("}}");
    return buffer.toString();
}

From source file:com.ettrema.httpclient.calsync.parse.CalDavBeanPropertyMapper.java

public String toVCard(Object bean) {
    net.fortuna.ical4j.model.Calendar calendar = new net.fortuna.ical4j.model.Calendar();
    calendar.getProperties().add(new ProdId("-//spliffy.org//iCal4j 1.0//EN"));
    calendar.getProperties().add(Version.VERSION_2_0);
    VEvent vevent = new VEvent();
    calendar.getComponents().add(vevent);

    PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean);
    for (PropertyDescriptor pd : pds) {
        if (pd.getReadMethod() != null && pd.getWriteMethod() != null) {
            Method read = pd.getReadMethod();
            Annotation[] annotations = read.getAnnotations();
            for (Annotation anno : annotations) {
                Mapper mapper = mapOfMappers.get(anno.annotationType());
                if (mapper != null) {
                    mapper.mapToCard(calendar, bean, pd);
                }//from  w w w . j a  va  2s  . c  o  m
            }
        }
    }

    CalendarOutputter outputter = new CalendarOutputter();
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {
        outputter.output(calendar, bout);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } catch (ValidationException ex) {
        throw new RuntimeException(ex);
    }
    return bout.toString();
}

From source file:com.bstek.dorado.data.type.EntityDataTypeSupport.java

protected void doCreatePropertyDefinitons() throws Exception {
    Class<?> type = getMatchType();
    if (type == null) {
        type = getCreationType();/*from  w ww  . j av a  2s .  c  o m*/
    }
    if (type == null || type.isPrimitive() || type.isArray() || Map.class.isAssignableFrom(type)) {
        return;
    }

    PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type);
    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        String name = propertyDescriptor.getName();
        if (!BeanPropertyUtils.isValidProperty(type, name))
            continue;

        PropertyDef propertyDef = getPropertyDef(name);
        DataType dataType = null;
        Class<?> propertyType = propertyDescriptor.getPropertyType();
        if (Collection.class.isAssignableFrom(propertyType)) {
            ParameterizedType parameterizedType = (ParameterizedType) propertyDescriptor.getReadMethod()
                    .getGenericReturnType();
            if (parameterizedType != null) {
                dataType = DataUtils.getDataType(parameterizedType);
            }
        }

        if (dataType == null) {
            dataType = DataUtils.getDataType(propertyType);
        }

        if (propertyDef == null) {
            if (dataType != null) {
                propertyDef = new BasePropertyDef(name);
                propertyDef.setDataType(dataType);
                addPropertyDef(propertyDef);

                if (dataType instanceof EntityDataType || dataType instanceof AggregationDataType) {
                    propertyDef.setIgnored(true);
                }
            }
        } else if (propertyDef.getDataType() == null) {
            if (dataType != null)
                propertyDef.setDataType(dataType);
        }
    }
}

From source file:ca.sqlpower.sqlobject.BaseSQLObjectTestCase.java

/**
 * XXX This test should use the {@link GenericNewValueMaker} as it has it's own mini
 * version inside it. This test should also be using the annotations to decide which 
 * setters can fire events.//  w  w  w .j  ava2  s  .  c  o m
 * 
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 * @throws NoSuchMethodException
 * @throws SQLObjectException
 */
public void testAllSettersGenerateEvents() throws IllegalArgumentException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException, SQLObjectException {
    SQLObject so = getSQLObjectUnderTest();
    so.populate();

    propertiesToIgnoreForEventGeneration.addAll(getPropertiesToIgnoreForEvents());

    //Ignored because we expect the object to be populated.
    propertiesToIgnoreForEventGeneration.add("exportedKeysPopulated");
    propertiesToIgnoreForEventGeneration.add("importedKeysPopulated");
    propertiesToIgnoreForEventGeneration.add("columnsPopulated");
    propertiesToIgnoreForEventGeneration.add("indicesPopulated");

    CountingSQLObjectListener listener = new CountingSQLObjectListener();
    SQLPowerUtils.listenToHierarchy(so, listener);

    if (so instanceof SQLDatabase) {
        // should be handled in the Datasource
        propertiesToIgnoreForEventGeneration.add("name");
    }

    List<PropertyDescriptor> settableProperties;

    settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(so.getClass()));

    for (PropertyDescriptor property : settableProperties) {
        Object oldVal;
        if (propertiesToIgnoreForEventGeneration.contains(property.getName()))
            continue;

        try {
            oldVal = PropertyUtils.getSimpleProperty(so, property.getName());
            // check for a setter
            if (property.getWriteMethod() == null) {
                continue;
            }

        } catch (NoSuchMethodException e) {
            System.out.println(
                    "Skipping non-settable property " + property.getName() + " on " + so.getClass().getName());
            continue;
        }
        Object newVal; // don't init here so compiler can warn if the following code doesn't always give it a value
        if (property.getPropertyType() == Integer.TYPE || property.getPropertyType() == Integer.class) {
            if (oldVal != null) {
                newVal = ((Integer) oldVal) + 1;
            } else {
                newVal = 1;
            }
        } else if (property.getPropertyType() == String.class) {
            // make sure it's unique
            newVal = "new " + oldVal;

        } else if (property.getPropertyType() == Boolean.TYPE || property.getPropertyType() == Boolean.class) {
            if (oldVal == null) {
                newVal = Boolean.TRUE;
            } else {
                newVal = new Boolean(!((Boolean) oldVal).booleanValue());
            }
        } else if (property.getPropertyType() == SQLCatalog.class) {
            newVal = new SQLCatalog(new SQLDatabase(), "This is a new catalog");
        } else if (property.getPropertyType() == SPDataSource.class) {
            newVal = new JDBCDataSource(getPLIni());
            ((SPDataSource) newVal).setName("test");
            ((SPDataSource) newVal).setDisplayName("test");
            ((JDBCDataSource) newVal).setUser("a");
            ((JDBCDataSource) newVal).setPass("b");
            ((JDBCDataSource) newVal).getParentType().setJdbcDriver(MockJDBCDriver.class.getName());
            ((JDBCDataSource) newVal).setUrl("jdbc:mock:tables=tab1");
        } else if (property.getPropertyType() == JDBCDataSource.class) {
            newVal = new JDBCDataSource(getPLIni());
            ((SPDataSource) newVal).setName("test");
            ((SPDataSource) newVal).setDisplayName("test");
            ((JDBCDataSource) newVal).setUser("a");
            ((JDBCDataSource) newVal).setPass("b");
            ((JDBCDataSource) newVal).getParentType().setJdbcDriver(MockJDBCDriver.class.getName());
            ((JDBCDataSource) newVal).setUrl("jdbc:mock:tables=tab1");
        } else if (property.getPropertyType() == SQLTable.class) {
            newVal = new SQLTable();
        } else if (property.getPropertyType() == SQLColumn.class) {
            newVal = new SQLColumn();
        } else if (property.getPropertyType() == SQLIndex.class) {
            newVal = new SQLIndex();
        } else if (property.getPropertyType() == SQLRelationship.SQLImportedKey.class) {
            SQLRelationship rel = new SQLRelationship();
            newVal = rel.getForeignKey();
        } else if (property.getPropertyType() == SQLRelationship.Deferrability.class) {
            if (oldVal == SQLRelationship.Deferrability.INITIALLY_DEFERRED) {
                newVal = SQLRelationship.Deferrability.NOT_DEFERRABLE;
            } else {
                newVal = SQLRelationship.Deferrability.INITIALLY_DEFERRED;
            }
        } else if (property.getPropertyType() == SQLRelationship.UpdateDeleteRule.class) {
            if (oldVal == SQLRelationship.UpdateDeleteRule.CASCADE) {
                newVal = SQLRelationship.UpdateDeleteRule.RESTRICT;
            } else {
                newVal = SQLRelationship.UpdateDeleteRule.CASCADE;
            }
        } else if (property.getPropertyType() == SQLIndex.AscendDescend.class) {
            if (oldVal == SQLIndex.AscendDescend.ASCENDING) {
                newVal = SQLIndex.AscendDescend.DESCENDING;
            } else {
                newVal = SQLIndex.AscendDescend.ASCENDING;
            }
        } else if (property.getPropertyType() == Throwable.class) {
            newVal = new Throwable();
        } else if (property.getPropertyType() == BasicSQLType.class) {
            if (oldVal != BasicSQLType.OTHER) {
                newVal = BasicSQLType.OTHER;
            } else {
                newVal = BasicSQLType.TEXT;
            }
        } else if (property.getPropertyType() == UserDefinedSQLType.class) {
            newVal = new UserDefinedSQLType();
        } else if (property.getPropertyType() == SQLTypeConstraint.class) {
            if (oldVal != SQLTypeConstraint.NONE) {
                newVal = SQLTypeConstraint.NONE;
            } else {
                newVal = SQLTypeConstraint.CHECK;
            }
        } else if (property.getPropertyType() == String[].class) {
            newVal = new String[3];
        } else if (property.getPropertyType() == PropertyType.class) {
            if (oldVal != PropertyType.NOT_APPLICABLE) {
                newVal = PropertyType.NOT_APPLICABLE;
            } else {
                newVal = PropertyType.VARIABLE;
            }
        } else if (property.getPropertyType() == List.class) {
            newVal = Arrays.asList("one", "two");
        } else {
            throw new RuntimeException("This test case lacks a value for " + property.getName() + " (type "
                    + property.getPropertyType().getName() + ") from " + so.getClass() + " on property "
                    + property.getDisplayName());
        }

        int oldChangeCount = listener.getChangedCount();

        try {
            System.out.println("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                    + newVal.getClass().getName() + ")");
            BeanUtils.copyProperty(so, property.getName(), newVal);

            // some setters fire multiple events (they change more than one property)
            assertTrue(
                    "Event for set " + property.getName() + " on " + so.getClass().getName() + " didn't fire!",
                    listener.getChangedCount() > oldChangeCount);
            if (listener.getChangedCount() == oldChangeCount + 1) {
                assertEquals("Property name mismatch for " + property.getName() + " in " + so.getClass(),
                        property.getName(), ((PropertyChangeEvent) listener.getLastEvent()).getPropertyName());
                assertEquals("New value for " + property.getName() + " was wrong", newVal,
                        ((PropertyChangeEvent) listener.getLastEvent()).getNewValue());
            }
        } catch (InvocationTargetException e) {
            System.out.println("(non-fatal) Failed to write property '" + property.getName() + " to type "
                    + so.getClass().getName());
        }
    }
}

From source file:ca.sqlpower.matchmaker.swingui.SaveAndOpenWorkspaceActionTest.java

private void buildChildren(SPObject parent) {

    for (Class c : parent.getAllowedChildTypes()) {
        try {// w  w  w .  j  a v a 2s  . com
            if (parent.getChildren(c).size() > 0) {
                logger.debug("It already had a " + c.getSimpleName() + "!");
                continue;
            }
            SPObject child;
            child = ((SPObject) valueMaker.makeNewValue(c, null, "child"));
            parent.addChild(child, parent.getChildren(c).size());
        } catch (Exception e) {
            logger.warn("Could not add a " + c.getSimpleName() + " to a " + parent.getClass().getSimpleName()
                    + " because of a " + e.getClass().getName());
        }
        try {
            Set<String> s = TestUtils.findPersistableBeanProperties(parent, false, false);

            List<PropertyDescriptor> settableProperties = Arrays
                    .asList(PropertyUtils.getPropertyDescriptors(parent.getClass()));
            TableMergeRules testParent = null; // special case- the parent of all others

            //set all properties of the object
            for (PropertyDescriptor property : settableProperties) {
                Object oldVal;

                if (!s.contains(property.getName()))
                    continue;
                if (property.getName().equals("parent"))
                    continue; //Changing the parent causes headaches.
                if (property.getName().equals("session"))
                    continue;
                if (property.getName().equals("type"))
                    continue;
                try {
                    oldVal = PropertyUtils.getSimpleProperty(parent, property.getName());

                    // check for a setter
                    if (property.getWriteMethod() == null)
                        continue;

                } catch (NoSuchMethodException e) {
                    logger.debug("Skipping non-settable property " + property.getName() + " on "
                            + parent.getClass().getName());
                    continue;
                }
                Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName());
                if (property.getName().equals("parentMergeRule")) {
                    if (testParent == null) {
                        newVal = null;
                        testParent = (TableMergeRules) parent;
                    } else {
                        newVal = testParent;
                    }
                }
                try {
                    logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' ("
                            + (newVal == null ? "null" : newVal.getClass().getName()) + ")");
                    BeanUtils.copyProperty(parent, property.getName(), newVal);

                } catch (InvocationTargetException e) {
                    logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type "
                            + parent.getClass().getName());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    for (SPObject spo : parent.getChildren()) {
        buildChildren(spo);
    }
}

From source file:com.bradmcevoy.property.BeanPropertySource.java

@Override
public List<QName> getAllPropertyNames(Resource r) {
    BeanPropertyResource anno = getAnnotation(r);
    if (anno == null)
        return null;
    PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(r);
    List<QName> list = new ArrayList<QName>();
    for (PropertyDescriptor pd : pds) {
        if (pd.getReadMethod() != null) {
            list.add(new QName(anno.value(), pd.getName()));
        }//from  ww  w .  j av  a2s .com
    }
    return list;
}

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.
 * //from   w w w.  j  a  va  2s.  c  o  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;
}