List of usage examples for org.springframework.beans BeanWrapper getPropertyDescriptors
PropertyDescriptor[] getPropertyDescriptors();
From source file:org.terasoluna.gfw.web.el.ObjectToMapConverter.java
/** * Convert the given object to the flattened map. * <p>// www .ja v a2s.c o m * Return empty map if the object is null. * </p> * @param prefix prefix of the key * @param object object to convert * @return converted map. all keys are prefixed with the given key * @see ObjectToMapConverter */ public Map<String, String> convert(String prefix, Object object) { Map<String, String> map = new LinkedHashMap<String, String>(); // at first, try to flatten the given object if (flatten(map, "", prefix, object, null)) { return map; } // the given object is a Java Bean BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object); PropertyDescriptor[] pds = beanWrapper.getPropertyDescriptors(); // flatten properties in the given object for (PropertyDescriptor pd : pds) { String name = pd.getName(); if ("class".equals(name) || !beanWrapper.isReadableProperty(name)) { continue; } Object value = beanWrapper.getPropertyValue(name); TypeDescriptor sourceType = beanWrapper.getPropertyTypeDescriptor(name); if (!flatten(map, prefix, name, value, sourceType)) { // the property can be a Java Bean // convert recursively Map<String, String> subMap = this.convert(name, value); map.putAll(subMap); } } return map; }
From source file:com.fmguler.ven.QueryGenerator.java
/** * Generates update query for the specified object * @param object the object to generate update query for * @return the update SQL query/*from www .j av a2 s . c o m*/ */ public String generateUpdateQuery(Object object) throws VenException { BeanWrapper wr = new BeanWrapperImpl(object); String objectName = Convert.toSimpleName(object.getClass().getName()); String tableName = Convert.toDB(objectName); PropertyDescriptor[] pdArr = wr.getPropertyDescriptors(); StringBuffer query = new StringBuffer("update " + tableName + " set "); for (int i = 0; i < pdArr.length; i++) { Class fieldClass = pdArr[i].getPropertyType(); //field class String columnName = Convert.toDB(pdArr[i].getName()); //column name String fieldName = pdArr[i].getName(); //field name if (dbClasses.contains(fieldClass)) { //direct database field (Integer,String,Date, etc) query.append(columnName.equals("order") ? "\"order\"" : columnName).append("=:").append(fieldName); query.append(","); } if (fieldClass.getPackage() != null && domainPackages.contains(fieldClass.getPackage().getName())) { //object query.append(columnName).append("_id=:").append(fieldName).append(".id"); query.append(","); } } query.deleteCharAt(query.length() - 1); query.append(" where id = :id ;"); return query.toString(); }
From source file:com.fmguler.ven.QueryGenerator.java
/** * Generates insert query for the specified object * @param object the object to generate insert query for * @return the insert SQL query//from w ww . j a va 2 s . co m */ public String generateInsertQuery(Object object) { BeanWrapper wr = new BeanWrapperImpl(object); String objectName = Convert.toSimpleName(object.getClass().getName()); String tableName = Convert.toDB(objectName); PropertyDescriptor[] pdArr = wr.getPropertyDescriptors(); //generate insert query StringBuffer query = new StringBuffer("insert into " + tableName + "("); StringBuffer values = new StringBuffer(" values("); for (int i = 0; i < pdArr.length; i++) { Class fieldClass = pdArr[i].getPropertyType(); //field class String columnName = Convert.toDB(pdArr[i].getName()); //column name String fieldName = pdArr[i].getName(); //field name //if (fieldName.equals("id")) continue; //remove if it does not break the sequence if (dbClasses.contains(fieldClass)) { //direct database field (Integer,String,Date, etc) query.append(columnName.equals("order") ? "\"order\"" : columnName); query.append(","); values.append(":").append(fieldName); values.append(","); } if (fieldClass.getPackage() != null && domainPackages.contains(fieldClass.getPackage().getName())) { //object query.append(Convert.toDB(fieldName)).append("_id"); query.append(","); values.append(":").append(fieldName).append(".id"); values.append(","); } } query.deleteCharAt(query.length() - 1); query.append(")"); values.deleteCharAt(values.length() - 1); values.append(");"); query.append(values); return query.toString(); }
From source file:org.ambraproject.user.service.UserServiceImpl.java
@Override public UserProfile getProfileForDisplay(UserProfile userProfile, boolean showPrivateFields) { UserProfile display = new UserProfile(); copyFields(userProfile, display);/*from w ww .j a v a 2 s .c om*/ if (!showPrivateFields) { log.debug("Removing private fields for display on user: {}", userProfile.getDisplayName()); display.setOrganizationName(null); display.setOrganizationType(null); display.setPostalAddress(null); display.setPositionType(null); } //escape html in all string fields BeanWrapper wrapper = new BeanWrapperImpl(display); for (PropertyDescriptor property : wrapper.getPropertyDescriptors()) { if (String.class.isAssignableFrom(property.getPropertyType())) { String name = property.getName(); wrapper.setPropertyValue(name, TextUtils.escapeHtml((String) wrapper.getPropertyValue(name))); } } return display; }
From source file:net.solarnetwork.support.XmlSupport.java
/** * Turn an object into a simple XML Element, supporting custom property * editors.//from w ww .j a v a 2 s . c o m * * <p> * The returned XML will be a single element with all JavaBean properties * turned into attributes. For example: * <p> * * <pre> * <powerDatum * id="123" * pvVolts="123.123" * ... /> * </pre> * * <p> * {@link PropertyEditor} instances can be registered with the supplied * {@link BeanWrapper} for custom handling of properties, e.g. dates. * </p> * * @param bean * the object to turn into XML * @param elementName * the name of the XML element * @return the element, as an XML DOM Element */ public Element getElement(BeanWrapper bean, String elementName, Document dom) { PropertyDescriptor[] props = bean.getPropertyDescriptors(); Element root = null; root = dom.createElement(elementName); for (int i = 0; i < props.length; i++) { PropertyDescriptor prop = props[i]; if (prop.getReadMethod() == null) { continue; } String propName = prop.getName(); if ("class".equals(propName)) { continue; } Object propValue = null; PropertyEditor editor = bean.findCustomEditor(prop.getPropertyType(), prop.getName()); if (editor != null) { editor.setValue(bean.getPropertyValue(propName)); propValue = editor.getAsText(); } else { propValue = bean.getPropertyValue(propName); } if (propValue == null) { continue; } if (log.isTraceEnabled()) { log.trace("attribute name: " + propName + " attribute value: " + propValue); } root.setAttribute(propName, propValue.toString()); } return root; }
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 ww . ja v a 2 s . co 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:org.brushingbits.jnap.common.bean.cloning.BeanCloner.java
private Object cloneBean(Object bean, Class<?> type) { BeanWrapper source = PropertyAccessorFactory.forBeanPropertyAccess(bean); BeanWrapper copy = PropertyAccessorFactory.forBeanPropertyAccess(BeanUtils.instantiate(type)); // keep instance for circular and multiple references context.setAsVisited(bean);/*from ww w . j a v a 2 s . c o m*/ alreadyCloned.put(bean, copy.getWrappedInstance()); PropertyDescriptor[] beanProperties = copy.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : beanProperties) { String name = propertyDescriptor.getName(); context.pushPath(name); if (copy.isReadableProperty(name) && copy.isWritableProperty(name)) { Object value = source.getPropertyValue(name); copy.setPropertyValue(name, clone(value)); } context.popPath(); } Object beanCopy = copy.getWrappedInstance(); source = null; copy = null; return beanCopy; }
From source file:com.yosanai.java.swing.editor.ObjectEditorTableModel.java
protected void addRows(Object wrappedObject, String prefix, Set<Integer> visited) { if (null == visited) { visited = new HashSet<Integer>(); }/*w ww . ja v a2 s . c o m*/ if (null != wrappedObject && !visited.contains(wrappedObject.hashCode())) { visited.add(wrappedObject.hashCode()); BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(wrappedObj); beanWrapper.setExtractOldValueForEditor(true); if (null != dateAndTimePropertyEditor) { beanWrapper.registerCustomEditor(Timestamp.class, dateAndTimePropertyEditor); beanWrapper.registerCustomEditor(Date.class, dateAndTimePropertyEditor); } PropertyDescriptor[] propDescs = beanWrapper.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : propDescs) { addRows(beanWrapper, propertyDescriptor, prefix, visited); } } }
From source file:net.kamhon.ieagle.dao.HibernateDao.java
private QueryParams translateExampleToQueryParams(Object example, String... orderBy) { Object newObj = example;// w ww.j av a2 s . com Entity className = ((Entity) newObj.getClass().getAnnotation(Entity.class)); if (className == null) throw new DataException(newObj.getClass().getSimpleName() + " class is not valid JPA annotated bean"); String aliasName = StringUtils.isBlank(className.name()) ? "obj" : className.name(); String hql = "SELECT " + aliasName + " FROM "; List<Object> params = new ArrayList<Object>(); BeanWrapper beanO1 = new BeanWrapperImpl(newObj); PropertyDescriptor[] proDescriptorsO1 = beanO1.getPropertyDescriptors(); int propertyLength = proDescriptorsO1.length; if (newObj != null) { hql += aliasName; hql += " IN " + example.getClass(); } if (example instanceof VoBase) { VoBase voBase = (VoBase) example; for (String key : voBase.getJoinTables().keySet()) { if (StringUtils.isNotBlank(key)) { hql += " JOIN " + key + " " + voBase.getJoinTables().get(key); } } } hql += " WHERE 1=1"; for (int i = 0; i < propertyLength; i++) { try { Object propertyValueO1 = beanO1.getPropertyValue(proDescriptorsO1[i].getName()); if ((propertyValueO1 instanceof String && StringUtils.isNotBlank((String) propertyValueO1)) || propertyValueO1 instanceof Long || propertyValueO1 instanceof Double || propertyValueO1 instanceof Integer || propertyValueO1 instanceof Boolean || propertyValueO1 instanceof Date || propertyValueO1.getClass().isPrimitive()) { Field field = null; try { field = example.getClass().getDeclaredField(proDescriptorsO1[i].getName()); } catch (NoSuchFieldException e) { if (propertyValueO1 instanceof Boolean || propertyValueO1.getClass().isPrimitive()) { String fieldName = "is" + StringUtils.upperCase(proDescriptorsO1[i].getName().substring(0, 1)) + proDescriptorsO1[i].getName().substring(1); field = example.getClass().getDeclaredField(fieldName); } } if (proDescriptorsO1[i].getName() != null && field != null && !field.isAnnotationPresent(Transient.class)) { if (!Arrays.asList(VoBase.propertiesVer).contains(proDescriptorsO1[i].getName())) { hql += " AND " + aliasName + "." + field.getName() + " = ?"; params.add(propertyValueO1); } } } else if (propertyValueO1 != null) { Field field = example.getClass().getDeclaredField(proDescriptorsO1[i].getName()); if (field.isAnnotationPresent(javax.persistence.Id.class) || field.isAnnotationPresent(javax.persistence.EmbeddedId.class)) { BeanWrapper bean = new BeanWrapperImpl(propertyValueO1); PropertyDescriptor[] proDescriptors = bean.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : proDescriptors) { Object propertyValueId = bean.getPropertyValue(propertyDescriptor.getName()); if (propertyValueId != null && ReflectionUtil.isJavaDataType(propertyValueId)) { hql += " AND " + aliasName + "." + proDescriptorsO1[i].getName() + "." + propertyDescriptor.getName() + " = ?"; params.add(bean.getPropertyValue(propertyDescriptor.getName())); } } } } } catch (Exception e) { } } // not condition if (example instanceof VoBase) { VoBase voBase = (VoBase) example; for (String key : voBase.getNotConditions().keySet()) { if (StringUtils.isNotBlank(key)) { hql += " AND " + aliasName + "." + key + "!=? "; params.add(voBase.getNotConditions().get(key)); } } } // like condition if (example instanceof VoBase) { VoBase voBase = (VoBase) example; for (String key : voBase.getLikeConditions().keySet()) { if (StringUtils.isNotBlank(key)) { hql += " AND " + aliasName + "." + key + " LIKE ? "; params.add(voBase.getLikeConditions().get(key)); } } } if (orderBy != null && orderBy.length != 0) { hql += " ORDER BY "; long count = 1; for (String orderByStr : orderBy) { if (count != 1) hql += ","; hql += aliasName + "." + orderByStr; count += 1; } } log.debug("hql = " + hql); return new QueryParams(hql, params); }
From source file:net.kamhon.ieagle.dao.Jpa2Dao.java
private QueryParams translateExampleToQueryParams(Object example, String... orderBy) { Object newObj = example;// ww w . j a v a2 s. c om Entity entity = ((Entity) newObj.getClass().getAnnotation(Entity.class)); if (entity == null) throw new DataException(newObj.getClass().getSimpleName() + " class is not valid JPA annotated bean"); String entityName = StringUtils.isBlank(entity.name()) ? example.getClass().getSimpleName() : entity.name(); String aliasName = StringUtils.isBlank(entity.name()) ? "obj" : entity.name(); String hql = "SELECT " + aliasName + " FROM "; List<Object> params = new ArrayList<Object>(); BeanWrapper beanO1 = new BeanWrapperImpl(newObj); PropertyDescriptor[] proDescriptorsO1 = beanO1.getPropertyDescriptors(); int propertyLength = proDescriptorsO1.length; if (newObj != null) { hql += entityName + " " + aliasName; } if (example instanceof VoBase) { VoBase voBase = (VoBase) example; for (String key : voBase.getJoinTables().keySet()) { if (StringUtils.isNotBlank(key)) { hql += " JOIN " + key + " " + voBase.getJoinTables().get(key); } } } hql += " WHERE 1=1"; int paramCount = 0; for (int i = 0; i < propertyLength; i++) { try { Object propertyValueO1 = beanO1.getPropertyValue(proDescriptorsO1[i].getName()); if ((propertyValueO1 instanceof String && StringUtils.isNotBlank((String) propertyValueO1)) || propertyValueO1 instanceof Long || propertyValueO1 instanceof Double || propertyValueO1 instanceof Integer || propertyValueO1 instanceof Boolean || propertyValueO1 instanceof Date || propertyValueO1.getClass().isPrimitive()) { Field field = null; try { field = example.getClass().getDeclaredField(proDescriptorsO1[i].getName()); } catch (NoSuchFieldException e) { if (propertyValueO1 instanceof Boolean || propertyValueO1.getClass().isPrimitive()) { String fieldName = "is" + StringUtils.upperCase(proDescriptorsO1[i].getName().substring(0, 1)) + proDescriptorsO1[i].getName().substring(1); field = example.getClass().getDeclaredField(fieldName); } } if (proDescriptorsO1[i].getName() != null && field != null && !field.isAnnotationPresent(Transient.class)) { if (!Arrays.asList(VoBase.propertiesVer).contains(proDescriptorsO1[i].getName())) { hql += " AND " + aliasName + "." + field.getName() + " = ?" + (++paramCount); params.add(propertyValueO1); } } } else if (propertyValueO1 != null) { Field field = example.getClass().getDeclaredField(proDescriptorsO1[i].getName()); if (field.isAnnotationPresent(javax.persistence.Id.class) || field.isAnnotationPresent(javax.persistence.EmbeddedId.class)) { BeanWrapper bean = new BeanWrapperImpl(propertyValueO1); PropertyDescriptor[] proDescriptors = bean.getPropertyDescriptors(); for (PropertyDescriptor propertyDescriptor : proDescriptors) { Object propertyValueId = bean.getPropertyValue(propertyDescriptor.getName()); if (propertyValueId != null && ReflectionUtil.isJavaDataType(propertyValueId)) { hql += " AND " + aliasName + "." + proDescriptorsO1[i].getName() + "." + propertyDescriptor.getName() + " = ?" + (++paramCount); params.add(bean.getPropertyValue(propertyDescriptor.getName())); } } } } } catch (Exception e) { } } // not condition if (example instanceof VoBase) { VoBase voBase = (VoBase) example; for (String key : voBase.getNotConditions().keySet()) { if (StringUtils.isNotBlank(key)) { hql += " AND " + aliasName + "." + key + "!= ?" + (++paramCount); params.add(voBase.getNotConditions().get(key)); } } } // like condition if (example instanceof VoBase) { VoBase voBase = (VoBase) example; for (String key : voBase.getLikeConditions().keySet()) { if (StringUtils.isNotBlank(key)) { hql += " AND " + aliasName + "." + key + " LIKE ?" + (++paramCount); params.add(voBase.getLikeConditions().get(key)); } } } if (orderBy != null && orderBy.length != 0) { hql += " ORDER BY "; long count = 1; for (String orderByStr : orderBy) { if (count != 1) hql += ","; hql += aliasName + "." + orderByStr; count += 1; } } log.debug("hql = " + hql); return new QueryParams(hql, params); }