List of usage examples for org.springframework.beans BeanWrapper setPropertyValue
void setPropertyValue(String propertyName, @Nullable Object value) throws BeansException;
From source file:com.seovic.core.DynamicObject.java
/** * Update specified target from this object. * * @param target target object to update *//*from ww w. ja v a2 s .com*/ public void update(Object target) { if (target == null) { throw new IllegalArgumentException("Target to update cannot be null"); } BeanWrapper bw = new BeanWrapperImpl(target); bw.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true)); for (Map.Entry<String, Object> property : m_properties.entrySet()) { String propertyName = property.getKey(); Object value = property.getValue(); if (value instanceof Map) { PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName); if (!Map.class.isAssignableFrom(pd.getPropertyType()) || pd.getWriteMethod() == null) { value = new DynamicObject((Map<String, Object>) value); } } if (value instanceof DynamicObject) { ((DynamicObject) value).update(bw.getPropertyValue(propertyName)); } else { bw.setPropertyValue(propertyName, value); } } }
From source file:com.aw.swing.mvp.binding.component.support.ColumnInfo.java
/** * Set the value to the specific cell//from w w w .jav a 2 s . c o m * * @param object */ public void setValue(Object object, Object value, int row) { // At this moment in the case of Object[] only the first element could be updated. if (object instanceof Object[]) { ((Object[]) object)[0] = value; } else { if (value instanceof Boolean) { value = ((Boolean) value).booleanValue() ? valueTrue : valueFalse; } BeanWrapper bwRow = getRow(object); Object oldValue = null; if (existChangeValueListener() || existVetoableChangeListener()) { oldValue = bwRow.getPropertyValue(fieldName); } if (formatter == DateFormatter.DATE_FORMATTER) { value = BndIJTextField.getValidDate((String) value); } try { if (existVetoableChangeListener()) { Object convertedValue = getConvertedValue(object, fieldName, value); vetoableChangeListener.vetoableChange(object, oldValue, convertedValue); } bwRow.setPropertyValue(fieldName, value); value = bwRow.getPropertyValue(fieldName); executeChangeValueListener(object, value, oldValue); } catch (AWBusinessException e) { bwRow.setPropertyValue(fieldName, oldValue); showErrorMsg(e); return; } } }
From source file:com.insframework.common.spring.jdbc.mapper.BeanPropertyRowMapper.java
/** * Extract the values for all columns in the current row. * <p>Utilizes public setters and result set metadata. * @see java.sql.ResultSetMetaData/*w w w . ja v a2 s. c o m*/ */ @Override public T mapRow(ResultSet rs, int rowNumber) throws SQLException { Assert.state(this.mappedClass != null, "Mapped class was not specified"); T mappedObject = BeanUtils.instantiate(this.mappedClass); BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject); initBeanWrapper(bw); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null); for (int index = 1; index <= columnCount; index++) { String column = JdbcUtils.lookupColumnName(rsmd, index); PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase()); if (pd != null) { try { Object value = getColumnValue(rs, index, pd); if (logger.isDebugEnabled() && rowNumber == 0) { logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type " + pd.getPropertyType()); } try { //add by guom if (pd.getPropertyType() != null && "java.lang.String".equals(pd.getPropertyType().getName())) { if (value != null) { bw.setPropertyValue(pd.getName(), String.valueOf(value)); } else { bw.setPropertyValue(pd.getName(), ""); } } else if (pd.getPropertyType() != null && "double".equals(pd.getPropertyType().getName())) { if (value != null) { bw.setPropertyValue(pd.getName(), value); } else { bw.setPropertyValue(pd.getName(), 0d); } } else { bw.setPropertyValue(pd.getName(), value); } } catch (TypeMismatchException e) { if (value == null && primitivesDefaultedForNullValue) { logger.info("Intercepted TypeMismatchException for row " + rowNumber + " and column '" + column + "' with value " + value + " when setting property '" + pd.getName() + "' of type " + pd.getPropertyType() + " on object: " + mappedObject); } else { throw e; } } if (populatedProperties != null) { populatedProperties.add(pd.getName()); } } catch (NotWritablePropertyException ex) { throw new DataRetrievalFailureException( "Unable to map column " + column + " to property " + pd.getName(), ex); } } } if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) { throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields " + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties); } return mappedObject; }
From source file:org.ambraproject.article.service.IngesterImpl.java
/** * Update an existing article by copying properties from the new one over. Note that we can't call saveOrUpdate, * since the new article is not a persistent instance, but has all the properties that we want. * <p/>//from w w w .j av a2 s . c o m * See <a href="http://stackoverflow.com/questions/4779239/update-persistent-object-with-transient-object-using-hibernate">this * post on stack overflow</a> for more information * <p/> * For collections, we clear the old property and add all the new entries, relying on 'delete-orphan' to delete the * old objects. The downside of this approach is that it results in a delete statement for each entry in the old * collection, and an insert statement for each entry in the new collection. There a couple of things we could do to * optimize this: <ol> <li>Write a sql statement to delete the old entries in one go</li> <li>copy over collection * properties recursively instead of clearing the old collection. e.g. for {@link Article#assets}, instead of * clearing out the old list, we would find the matching asset by DOI and Extension, and update its properties</li> * </ol> * <p/> * Option number 2 is messy and a lot of code (I've done it before) * * @param article the new article, parsed from the xml * @param existingArticle the article pulled up from the database * @throws IngestException if there's a problem copying properties or updating */ @SuppressWarnings("unchecked") private void updateArticle(final Article article, final Article existingArticle) throws IngestException { log.debug("ReIngesting (force ingest) article: {}", existingArticle.getDoi()); //Hibernate deletes orphans after inserting the new rows, which violates a unique constraint on (doi, extension) for assets //this temporary change gets around the problem, before the old assets are orphaned and deleted hibernateTemplate.execute(new HibernateCallback() { @Override public Object doInHibernate(Session session) throws HibernateException, SQLException { session.createSQLQuery("update articleAsset " + "set doi = concat('old-',doi), " + "extension = concat('old-',extension) " + "where articleID = :articleID") .setParameter("articleID", existingArticle.getID()).executeUpdate(); return null; } }); final BeanWrapper source = new BeanWrapperImpl(article); final BeanWrapper destination = new BeanWrapperImpl(existingArticle); try { //copy properties for (final PropertyDescriptor property : destination.getPropertyDescriptors()) { final String name = property.getName(); if (!name.equals("ID") && !name.equals("created") && !name.equals("lastModified") && !name.equals("class")) { //Collections shouldn't be dereferenced but have elements added //See http://www.onkarjoshi.com/blog/188/hibernateexception-a-collection-with-cascade-all-delete-orphan-was-no-longer-referenced-by-the-owning-entity-instance/ if (Collection.class.isAssignableFrom(property.getPropertyType())) { Collection orig = (Collection) destination.getPropertyValue(name); orig.clear(); Collection sourcePropertyValue = (Collection) source.getPropertyValue(name); if (sourcePropertyValue != null) { orig.addAll((Collection) source.getPropertyValue(name)); } } else { //just set the new value destination.setPropertyValue(name, source.getPropertyValue(name)); } } } //Circular relationship in related articles for (ArticleRelationship articleRelationship : existingArticle.getRelatedArticles()) { articleRelationship.setParentArticle(existingArticle); } } catch (Exception e) { throw new IngestException("Error copying properties for article " + article.getDoi(), e); } hibernateTemplate.update(existingArticle); }
From source file:net.sf.juffrou.reflect.spring.BeanWrapperTests.java
@Test public void testGetterThrowsException() { GetterBean gb = new GetterBean(); BeanWrapper bw = new JuffrouSpringBeanWrapper(gb); bw.setPropertyValue("name", "tom"); assertTrue("Set name to tom", gb.getName().equals("tom")); }
From source file:net.sf.juffrou.reflect.spring.BeanWrapperTests.java
@Test public void testTypedMapReadOnlyMap() { TypedReadOnlyMap map = new TypedReadOnlyMap(Collections.singletonMap("key", new TestBean())); TypedReadOnlyMapClient bean = new TypedReadOnlyMapClient(); BeanWrapper bw = new JuffrouSpringBeanWrapper(bean); bw.setPropertyValue("map", map); }
From source file:net.sf.juffrou.reflect.spring.BeanWrapperTests.java
@Test public void testPrimitiveArray() { PrimitiveArrayBean tb = new PrimitiveArrayBean(); BeanWrapper bw = new JuffrouSpringBeanWrapper(tb); bw.setPropertyValue("array", new String[] { "1", "2" }); assertEquals(2, tb.getArray().length); assertEquals(1, tb.getArray()[0]);/* w w w . jav a 2 s . com*/ assertEquals(2, tb.getArray()[1]); }
From source file:net.sf.juffrou.reflect.spring.BeanWrapperTests.java
@Test public void testNestedProperties() { String doctorCompany = ""; String lawyerCompany = "Dr. Sueem"; TestBean tb = new TestBean(); BeanWrapper bw = new JuffrouSpringBeanWrapper(tb); bw.setPropertyValue("doctor.company", doctorCompany); bw.setPropertyValue("lawyer.company", lawyerCompany); assertEquals(doctorCompany, tb.getDoctor().getCompany()); assertEquals(lawyerCompany, tb.getLawyer().getCompany()); }
From source file:net.sf.juffrou.reflect.spring.BeanWrapperTests.java
@Test public void testGenericEnum() { EnumConsumer consumer = new EnumConsumer(); BeanWrapper bw = new JuffrouSpringBeanWrapper(consumer); bw.setPropertyValue("enumValue", TestEnum.class.getName() + ".TEST_VALUE"); assertEquals(TestEnum.TEST_VALUE, consumer.getEnumValue()); }