List of usage examples for org.apache.commons.beanutils PropertyUtils getSimpleProperty
public static Object getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
Return the value of the specified simple property of the specified bean, with no type conversions.
For more details see PropertyUtilsBean
.
From source file:com.mb.framework.util.property.PropertyUtilExt.java
public static boolean equalsSimpleProperties(Object mainObject, Object otherObject) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(mainObject); for (int i = 0; i < origDescriptors.length; i++) { String name = origDescriptors[i].getName(); if (PropertyUtils.getPropertyDescriptor(otherObject, name) != null) { Object origValue = PropertyUtils.getSimpleProperty(mainObject, name); Object otherValue = PropertyUtils.getSimpleProperty(otherObject, name); if (origValue != null && otherValue == null) { return false; }/*ww w . java 2 s. c o m*/ if (origValue == null && otherValue != null) { return false; } if (origValue != null && otherValue != null) { /* * to walk around timestamp and date equals behavior Date d * = new Date(); Timestamp t = new Timestamp(d.getTime()); * d.equals(t) > == true; t.equals(d) > == false; */ if (origValue instanceof java.sql.Timestamp && (otherValue instanceof java.sql.Date || otherValue instanceof java.util.Date)) { if (!otherValue.equals(origValue)) { return false; } } else { if (!origValue.equals(otherValue)) { return false; } } } } } return true; }
From source file:ca.sqlpower.object.PersistedSPObjectTest.java
/** * Tests the SPPersisterListener will persist a property change to its * target persister./* w ww. j a v a2 s . c o m*/ */ public void testSPListenerPersistsProperty() throws Exception { CountingSPPersister countingPersister = new CountingSPPersister(); SPPersisterListener listener = new SPPersisterListener(countingPersister, getConverter()); NewValueMaker valueMaker = createNewValueMaker(root, getPLIni()); SPObject wo = getSPObjectUnderTest(); wo.addSPListener(listener); List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass())); Set<String> propertiesToPersist = findPersistableBeanProperties(false, false); for (PropertyDescriptor property : settableProperties) { Object oldVal; if (!propertiesToPersist.contains(property.getName())) continue; countingPersister.clearAllPropertyChanges(); try { oldVal = PropertyUtils.getSimpleProperty(wo, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug( "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName()); continue; } Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); int oldChangeCount = countingPersister.getPersistPropertyCount(); try { //The first property change at current is always the property change we are //looking for, this may need to be changed in the future to find the correct //property. PersistedSPOProperty propertyChange = null; try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + newVal.getClass().getName() + ")"); wo.setMagicEnabled(false); BeanUtils.copyProperty(wo, property.getName(), newVal); assertTrue("Did not persist property " + property.getName(), oldChangeCount < countingPersister.getPersistPropertyCount()); for (PersistedSPOProperty nextPropertyChange : countingPersister.getPersistPropertyList()) { if (nextPropertyChange.getPropertyName().equals(property.getName())) { propertyChange = nextPropertyChange; break; } } assertNotNull("A property change event cannot be found for the property " + property.getName(), propertyChange); assertEquals(wo.getUUID(), propertyChange.getUUID()); assertEquals(property.getName(), propertyChange.getPropertyName()); assertEquals( "Old value of property " + property.getName() + " was wrong, value expected was " + oldVal + " but is " + countingPersister.getLastOldValue(), getConverter().convertToBasicType(oldVal), propertyChange.getOldValue()); } finally { wo.setMagicEnabled(true); } //Input streams from images are being compared by hash code not values if (Image.class.isAssignableFrom(property.getPropertyType())) { logger.debug(propertyChange.getNewValue().getClass()); assertTrue(Arrays.equals(PersisterUtils.convertImageToStreamAsPNG((Image) newVal).toByteArray(), PersisterUtils .convertImageToStreamAsPNG((Image) getConverter() .convertToComplexType(propertyChange.getNewValue(), Image.class)) .toByteArray())); } else { assertEquals(getConverter().convertToBasicType(newVal), propertyChange.getNewValue()); } Class<? extends Object> classType; if (oldVal != null) { classType = oldVal.getClass(); } else { classType = newVal.getClass(); } assertEquals(PersisterUtils.getDataType(classType), propertyChange.getDataType()); } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + wo.getClass().getName()); } } }
From source file:com.fiveamsolutions.nci.commons.search.SearchCallback.java
private Object getSimpleProperty(Object bean, String property) { Object subPropResult = null;//from www. jav a 2 s. c om try { subPropResult = PropertyUtils.getSimpleProperty(bean, property); } catch (Exception e) { throw new IllegalArgumentException("Unable to process property with name:" + property, e); } return subPropResult; }
From source file:com.panemu.tiwulfx.control.skin.LookupFieldSkin.java
private void updateTextField() { detectTextChanged = false;/*from w w w. j a v a2 s . c o m*/ needValidation = false; if (lookupField.getValue() == null) { textField.setText(""); lookupField.markInvalidProperty().set(false); detectTextChanged = true; return; } try { Object value = PropertyUtils.getSimpleProperty(lookupField.getValue(), lookupField.getPropertyName()); if (value != null) { textField.setText(value.toString()); } else { textField.setText(""); } lookupField.markInvalidProperty().set(false); detectTextChanged = true; } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { throw new RuntimeException(ex); } }
From source file:com.github.pagehelper.PageHelper.java
/** * ???// ww w.ja v a 2 s . c o m * * @param parameterObject ? * @param page ? * @return ?? * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ private MapperMethod.ParamMap setPageParameter(Object parameterObject, BoundSql boundSql, Page page) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { MapperMethod.ParamMap<Object> paramMap = null; if (parameterObject == null) { paramMap = new MapperMethod.ParamMap<Object>(); } else if (parameterObject instanceof MapperMethod.ParamMap) { paramMap = (MapperMethod.ParamMap) parameterObject; } else { paramMap = new MapperMethod.ParamMap<Object>(); if (boundSql.getParameterMappings() != null && boundSql.getParameterMappings().size() > 0) { for (ParameterMapping parameterMapping : boundSql.getParameterMappings()) { if (!parameterMapping.getProperty().equals(PAGEPARAMETER_FIRST) && !parameterMapping.getProperty().equals(PAGEPARAMETER_SECOND)) { if (parameterObject instanceof Map) { paramMap.put(parameterMapping.getProperty(), ((Map) parameterObject).get(parameterMapping.getProperty())); } else { // paramMap.put(parameterMapping.getProperty(), parameterObject); Object value = PropertyUtils.getSimpleProperty(parameterObject, parameterMapping.getProperty()); System.out.println("set param: ??: " + parameterMapping.getProperty() + " , value: " + value); paramMap.put(parameterMapping.getProperty(), value); } // System.out.println("parameterObject: "+parameterObject.getClass()); // paramMap.put(parameterMapping.getProperty(), 86); } } } } if ("mysql".equals(dialect)) { paramMap.put(PAGEPARAMETER_FIRST, page.getStartRow()); paramMap.put(PAGEPARAMETER_SECOND, page.getPageSize()); } else if ("hsqldb".equals(dialect)) { paramMap.put(PAGEPARAMETER_FIRST, page.getPageSize()); paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow()); } else if ("oracle".equals(dialect)) { paramMap.put(PAGEPARAMETER_FIRST, page.getEndRow()); paramMap.put(PAGEPARAMETER_SECOND, page.getStartRow()); } return paramMap; }
From source file:ca.sqlpower.wabit.AbstractWabitObjectTest.java
/** * This will reflectively iterate over all of the properties in the Wabit * object and set each value that has a setter and getter. When the property * is set it should cause the property to be persisted through the * {@link WorkspacePersisterListener}./*from w ww . ja v a 2 s.co m*/ */ public void testPropertiesArePersisted() throws Exception { CountingWabitPersister countingPersister = new CountingWabitPersister(); WorkspacePersisterListener listener = new WorkspacePersisterListener( new StubWabitSession(new StubWabitSessionContext()), countingPersister, true); SPObject wo = getObjectUnderTest(); wo.addSPListener(listener); WabitSessionPersisterSuperConverter converterFactory = new WabitSessionPersisterSuperConverter( new StubWabitSession(new StubWabitSessionContext()), new WabitWorkspace(), true); List<PropertyDescriptor> settableProperties; settableProperties = Arrays.asList(PropertyUtils.getPropertyDescriptors(wo.getClass())); //Ignore properties that are not in events because we won't have an event //to respond to. Set<String> propertiesToIgnoreForEvents = getPropertiesToIgnoreForEvents(); Set<String> propertiesToIgnoreForPersisting = getPropertiesToIgnoreForPersisting(); for (PropertyDescriptor property : settableProperties) { Object oldVal; if (propertiesToIgnoreForEvents.contains(property.getName())) continue; if (propertiesToIgnoreForPersisting.contains(property.getName())) continue; countingPersister.clearAllPropertyChanges(); try { oldVal = PropertyUtils.getSimpleProperty(wo, property.getName()); // check for a setter if (property.getWriteMethod() == null) continue; } catch (NoSuchMethodException e) { logger.debug( "Skipping non-settable property " + property.getName() + " on " + wo.getClass().getName()); continue; } Object newVal = valueMaker.makeNewValue(property.getPropertyType(), oldVal, property.getName()); int oldChangeCount = countingPersister.getPersistPropertyCount(); try { logger.debug("Setting property '" + property.getName() + "' to '" + newVal + "' (" + newVal.getClass().getName() + ")"); BeanUtils.copyProperty(wo, property.getName(), newVal); assertTrue("Did not persist property " + property.getName(), oldChangeCount < countingPersister.getPersistPropertyCount()); //The first property change at current is always the property change we are //looking for, this may need to be changed in the future to find the correct //property. PersistedSPOProperty propertyChange = null; for (PersistedSPOProperty nextPropertyChange : countingPersister.getAllPropertyChanges()) { if (nextPropertyChange.getPropertyName().equals(property.getName())) { propertyChange = nextPropertyChange; break; } } assertNotNull("A property change event cannot be found for the property " + property.getName(), propertyChange); assertEquals(wo.getUUID(), propertyChange.getUUID()); assertEquals(property.getName(), propertyChange.getPropertyName()); //XXX will replace this later List<Object> additionalVals = new ArrayList<Object>(); if (wo instanceof OlapQuery && property.getName().equals("currentCube")) { additionalVals.add(((OlapQuery) wo).getOlapDataSource()); } Object oldConvertedType = converterFactory.convertToBasicType(oldVal, additionalVals.toArray()); assertEquals( "Old value of property " + property.getName() + " was wrong, value expected was " + oldConvertedType + " but is " + countingPersister.getLastOldValue(), oldConvertedType, propertyChange.getOldValue()); //Input streams from images are being compared by hash code not values if (Image.class.isAssignableFrom(property.getPropertyType())) { logger.debug(propertyChange.getNewValue().getClass()); assertTrue(Arrays.equals(PersisterUtils.convertImageToStreamAsPNG((Image) newVal).toByteArray(), PersisterUtils .convertImageToStreamAsPNG((Image) converterFactory .convertToComplexType(propertyChange.getNewValue(), Image.class)) .toByteArray())); } else { assertEquals(converterFactory.convertToBasicType(newVal, additionalVals.toArray()), propertyChange.getNewValue()); } Class<? extends Object> classType; if (oldVal != null) { classType = oldVal.getClass(); } else { classType = newVal.getClass(); } assertEquals(PersisterUtils.getDataType(classType), propertyChange.getDataType()); } catch (InvocationTargetException e) { logger.debug("(non-fatal) Failed to write property '" + property.getName() + " to type " + wo.getClass().getName()); } } }
From source file:com.mb.framework.util.property.PropertyUtilExt.java
/** * Resets the bean's <code>String</code> type properties to a specified * value.//from w ww .j av a 2 s .c o m * * @param orig * Origin bean whose properties are retrieved. * @param value * the value to set the bean properties to. */ public static void resetProperties(Object orig, String value) { PropertyDescriptor origDescriptors[] = null; try { origDescriptors = PropertyUtils.getPropertyDescriptors(orig); } catch (Exception e) { return; } if (origDescriptors != null) { for (int i = 0; i < origDescriptors.length; i++) { try { String name = origDescriptors[i].getName(); Object orgValue = PropertyUtils.getSimpleProperty(orig, name); if ((orgValue != null) && (orgValue instanceof String)) { PropertyUtils.setSimpleProperty(orig, name, value); } } catch (Exception e) { // skip it } } } }
From source file:com.sqewd.open.dal.core.persistence.db.AbstractDbPersister.java
private String getEntityKey(final AbstractEntity entity) throws Exception { StringBuffer buff = new StringBuffer(); boolean first = true; StructEntityReflect enref = ReflectionUtils.get().getEntityMetadata(entity.getClass()); for (String key : enref.FieldMaps.keySet()) { StructAttributeReflect attr = enref.get(key); if (attr == null || !attr.IsKeyColumn) { continue; }//from w w w . j av a 2 s . c om if (first) { first = false; } else { buff.append(':'); } String value = null; if (attr.Reference == null) { if (attr.Field.getType().equals(Date.class)) { Date dt = (Date) PropertyUtils.getSimpleProperty(entity, attr.Field.getName()); value = String.valueOf(dt.getTime()); } else { value = String.valueOf(PropertyUtils.getSimpleProperty(entity, attr.Field.getName())); if (!EnumPrimitives.isPrimitiveType(attr.Field.getType())) { value = "'" + value + "'"; } } } else { Object dvalue = PropertyUtils.getSimpleProperty(entity, attr.Field.getName()); StructAttributeReflect rattr = ReflectionUtils.get() .getAttribute(Class.forName(attr.Reference.Class), attr.Reference.Field); value = String.valueOf(PropertyUtils.getSimpleProperty(dvalue, rattr.Field.getName())); if (!EnumPrimitives.isPrimitiveType(attr.Field.getType())) { value = "'" + value + "'"; } } buff.append(value); } return buff.toString(); }
From source file:com.sop4j.dbutils.QueryRunner.java
protected <T> InsertExecutor internalEntityCreate(final Class<? extends T> entityClass, final T entity, final Set<String> excludeColumns) throws SQLException { final String tableName = EntityUtils.getTableName(entity.getClass()); final Map<String, String> columns = EntityUtils.getColumns(entityClass); final StringBuilder sb = new StringBuilder("insert into "); // create the SQL command sb.append(tableName);/*w w w . ja va 2s . co m*/ sb.append(" ("); sb.append(EntityUtils.joinColumnsWithComma(columns.keySet(), null)); sb.append(") values("); sb.append(EntityUtils.joinColumnsWithComma(columns.keySet(), ":")); sb.append(")"); LOG.debug("INSERT: {}", sb.toString()); // create the executor final InsertExecutor exec = new InsertExecutor(this.prepareConnection(), sb.toString(), true); for (String column : columns.keySet()) { // don't bind the exclude columns if (excludeColumns.contains(column)) { continue; } try { // bind all of the values final Object value = PropertyUtils.getSimpleProperty(entity, columns.get(column)); if (value == null) { exec.bindNull(column); } else { exec.bind(column, value); } } catch (final IllegalAccessException e) { throw new SQLException(e); } catch (final InvocationTargetException e) { throw new SQLException(e); } catch (final NoSuchMethodException e) { throw new SQLException(e); } } return exec; }
From source file:com.sqewd.open.dal.core.persistence.db.AbstractDbPersister.java
private String getQueryByKey(final AbstractEntity entity) throws Exception { StringBuffer buff = new StringBuffer(); boolean first = true; StructEntityReflect enref = ReflectionUtils.get().getEntityMetadata(entity.getClass()); for (String key : enref.FieldMaps.keySet()) { StructAttributeReflect attr = enref.get(key); if (attr == null || !attr.IsKeyColumn) { continue; }//w w w . j a v a 2 s . c o m if (first) { first = false; } else { buff.append(';'); } String value = null; StringBuffer column = new StringBuffer(); column.append(attr.Column); if (attr.Reference == null) { if (attr.Field.getType().equals(Date.class)) { Date dt = (Date) PropertyUtils.getSimpleProperty(entity, attr.Field.getName()); value = String.valueOf(dt.getTime()); } else { value = String.valueOf(PropertyUtils.getSimpleProperty(entity, attr.Field.getName())); if (!EnumPrimitives.isPrimitiveType(attr.Field.getType())) { value = "'" + value + "'"; } } } else { Object dvalue = PropertyUtils.getSimpleProperty(entity, attr.Field.getName()); StructAttributeReflect rattr = ReflectionUtils.get() .getAttribute(Class.forName(attr.Reference.Class), attr.Reference.Field); column.append('.').append(attr.Reference.Field); value = String.valueOf(PropertyUtils.getSimpleProperty(dvalue, rattr.Field.getName())); if (!EnumPrimitives.isPrimitiveType(attr.Field.getType())) { value = "'" + value + "'"; } } buff.append(enref.Entity).append('.').append(column.toString()).append("=").append(value); } return buff.toString(); }