List of usage examples for org.apache.commons.beanutils PropertyUtils setSimpleProperty
public static void setSimpleProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
Set the value of the specified simple property of the specified bean, with no type conversions.
For more details see PropertyUtilsBean
.
From source file:org.tinygroup.commons.beanutil.BeanUtil.java
public static Object deepCopy(Object orig) throws Exception { Object dest = orig.getClass().newInstance(); PropertyDescriptor[] origDescriptors = PropertyUtils.getPropertyDescriptors(orig); for (PropertyDescriptor propertyDescriptor : origDescriptors) { String name = propertyDescriptor.getName(); if (PropertyUtils.isReadable(orig, name) && PropertyUtils.isWriteable(dest, name)) { Object value = PropertyUtils.getSimpleProperty(orig, name); Object valueDest = null; if (value != null && canDeepCopyObject(value)) { if (value instanceof Collection) { Collection coll = (Collection) value; Collection newColl = createApproximateCollection(value); Iterator it = coll.iterator(); while (it.hasNext()) { newColl.add(deepCopy(it.next())); }//from w ww. j a va 2s . co m valueDest = newColl; } else if (value.getClass().isArray()) { Object[] values = (Object[]) value; Object[] newValues = new Object[values.length]; for (int i = 0; i < newValues.length; i++) { newValues[i] = deepCopy(values[i]); } valueDest = newValues; } else if (value instanceof Map) { Map map = (Map) value; Map newMap = createApproximateMap(map); for (Object key : map.keySet()) { newMap.put(key, deepCopy(map.get(key))); } valueDest = newMap; } else { valueDest = deepCopy(value); } } else { valueDest = value; } PropertyUtils.setSimpleProperty(dest, name, valueDest); } } return dest; }
From source file:org.wickedsource.wickedforms.model.binding.PropertyBinding.java
@Override public void setValue(T value) { try {/*ww w. ja v a2s.c o m*/ PropertyUtils.setSimpleProperty(boundObject, property, value); } catch (Exception e) { throw new IllegalStateException( String.format("Binding error! Setting property '%s' on bound object of class %s failed!", property, boundObject.getClass()), e); } }
From source file:org.xmldb.core.xml.manager.FileSystemXmldbManagerImpl.java
public <T> T merge(PersistenceClass persistenceClass, Object o) { try {//from www . j av a 2 s. com Object value = PropertyUtils.getProperty(o, persistenceClass.getPkField().getFieldName()); String xpath = createXpathQuery(persistenceClass, value); if (!xmlHelper.existElement(xpath)) { value = sequenceManager.nextId(persistenceClass); } xmlHelper.removeUnique(xpath); PropertyUtils.setSimpleProperty(o, persistenceClass.getPkField().getFieldName(), value); Trasformers trasf = new ObjectTrasformers(persistenceClass); Element element = trasf.trasformElement(o); xmlHelper.addEntity(element); return (T) o; } catch (Exception e) { throw new XmlDBRuntimeException(e); } }
From source file:play.modules.resteasy.crud.RESTResource.java
/** * Override this method to implement your own endpoint, otherwise it will be magically bound to the * right path and parameters for editing an entity. * @param model the model type/*from w w w .j ava 2s .co m*/ * @param id the entity id to update * @param elem the new values for the entity * @return a response with no content */ public <T extends Model> Response edit(Class<T> model, Object id, final T elem) { Factory factory = Manager.factoryFor(model); @SuppressWarnings("unchecked") final T elemFromDB = (T) factory.findById(id); checkForUpdate(elem, elemFromDB); // copy every field walkProperties(model, new PropertyWalker() { @Override public void walk(Property property, Field field, CRUDField crud) { Object newValue; try { newValue = PropertyUtils.getSimpleProperty(elem, property.name); } catch (Exception e) { throw toThrowable(internalError(e, "Failed to get property %s", property.name)); } // if that field is not editable, let us barf if (crud == null || !crud.editable()) checkEmpty(newValue); else { // we can set it try { PropertyUtils.setSimpleProperty(elemFromDB, property.name, newValue); } catch (Exception e) { throw toThrowable(internalError(e, "Failed to set property %s", property.name)); } } } }); elemFromDB._save(); return noContent(); }
From source file:pt.ist.fenix.service.services.TransferDomainObjectProperty.java
@Atomic public static void run(DomainObject srcObject, DomainObject dstObject, String slotName) throws FenixServiceException { AccessControl.check(RolePredicates.MANAGER_PREDICATE); try {/* w w w.ja v a 2s.c om*/ Object srcProperty = PropertyUtils.getSimpleProperty(srcObject, slotName); if (srcProperty != null && srcProperty instanceof Collection) { Collection srcCollection = (Collection) srcProperty; Object dstProperty = PropertyUtils.getSimpleProperty(dstObject, slotName); if (dstProperty instanceof Collection) { Collection dstCollection = (Collection) dstProperty; dstCollection.addAll(srcCollection); } } else { PropertyUtils.setSimpleProperty(dstObject, slotName, srcProperty); } } catch (InvocationTargetException e) { if (e.getTargetException() != null) { if (e.getTargetException() instanceof WriteOnReadError) { throw ((WriteOnReadError) e.getTargetException()); } throw new FenixServiceException(e.getTargetException()); } throw new FenixServiceException(e); } catch (IllegalAccessException e) { throw new FenixServiceException(e); } catch (NoSuchMethodException e) { throw new FenixServiceException(e); } }
From source file:pt.ist.maidSyncher.domain.SynchableObject.java
/** * /* ww w . j a va2 s. c om*/ * @param orig * @return a collection with the {@link PropertyDescriptor} s that changed * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws TaskNotVisibleException */ public Collection<String> copyPropertiesFrom(Object orig) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, TaskNotVisibleException { Set<PropertyDescriptor> propertyDescriptorsThatChanged = new HashSet<PropertyDescriptor>(); Object dest = this; if (orig == null) { throw new IllegalArgumentException("No origin bean specified"); } PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(orig); for (PropertyDescriptor origDescriptor : origDescriptors) { String name = origDescriptor.getName(); if (PropertyUtils.isReadable(orig, name)) { if (PropertyUtils.isWriteable(dest, name)) { Object valueDest = PropertyUtils.getSimpleProperty(dest, name); Object valueOrigin = PropertyUtils.getSimpleProperty(orig, name); if (valueOrigin != null && valueOrigin.getClass().getPackage().getName() .equalsIgnoreCase("org.eclipse.egit.github.core")) continue; //let's skip the properties with egit core objects (they shall be copied from a custom overriden version of this method) if (valueOrigin instanceof Date) valueOrigin = new DateTime(valueOrigin); if (Objects.equal(valueDest, valueOrigin) == false) propertyDescriptorsThatChanged.add(origDescriptor); try { //let's see if this is actually a Date, if so, let's convert it PropertyUtils.setSimpleProperty(dest, name, valueOrigin); } catch (IllegalArgumentException ex) { throw new Error("setSimpleProperty returned an exception, dest: " + dest.getClass().getName() + " oid: " + ((DomainObject) dest).getExternalId() + " name : " + name + " valueOrig: " + valueOrigin, ex); } LOGGER.trace("Copied property " + name + " from " + orig.getClass().getName() + " object to a " + dest.getClass().getName() + " oid: " + getExternalId()); } } } return Collections2.transform(propertyDescriptorsThatChanged, new Function<PropertyDescriptor, String>() { @Override public String apply(PropertyDescriptor propertyDescriptor) { if (propertyDescriptor == null) { return null; } return propertyDescriptor.getName(); } }); }
From source file:pt.ist.maidSyncher.domain.SynchableObject.java
public void copyPropertiesTo(Object dest) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, TaskNotVisibleException { Set<PropertyDescriptor> propertyDescriptorsThatChanged = new HashSet<PropertyDescriptor>(); Object orig = this; checkNotNull(dest);//from www .j a v a 2 s . c o m PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(orig); for (PropertyDescriptor origDescriptor : origDescriptors) { String name = origDescriptor.getName(); if (PropertyUtils.isReadable(orig, name)) { PropertyDescriptor destDescriptor = PropertyUtils.getPropertyDescriptor(dest, origDescriptor.getName()); if (PropertyUtils.isWriteable(dest, name) || (destDescriptor != null && MiscUtils.getWriteMethodIncludingFlowStyle(destDescriptor, dest.getClass()) != null)) { Object valueDest = PropertyUtils.getSimpleProperty(dest, name); Object valueOrigin = PropertyUtils.getSimpleProperty(orig, name); LOGGER.debug("OrigDescriptor PropertyType: " + origDescriptor.getPropertyType().getName()); // System.out.println("OrigDescriptor PropertyType: " + origDescriptor.getPropertyType().getName()); //let's ignore the properties were the values are our domain packages if (valueOrigin != null && (SynchableObject.class.isAssignableFrom(valueOrigin.getClass()))) { // System.out.println("Skipping"); continue; //let's skip these properties } if (SynchableObject.class.isAssignableFrom(origDescriptor.getPropertyType())) { // System.out.println("Skipping"); continue; } if (origDescriptor instanceof IndexedPropertyDescriptor) { IndexedPropertyDescriptor indexedPropertyDescriptor = (IndexedPropertyDescriptor) origDescriptor; // System.out.println("OrigDescriptor IndexedPropertyDescriptor: " + indexedPropertyDescriptor.getName()); if (SynchableObject.class .isAssignableFrom(indexedPropertyDescriptor.getIndexedPropertyType())) { // System.out.println("Skipping"); continue; } } //let's ignore all of the dates - as they should be filled by //the system if (valueOrigin instanceof LocalTime) continue; if (Objects.equal(valueDest, valueOrigin) == false) propertyDescriptorsThatChanged.add(origDescriptor); try { if (PropertyUtils.isWriteable(dest, name) == false) { //let's use the flow version Class<?> origPropertyType = origDescriptor.getPropertyType(); Method writeMethodIncludingFlowStyle = MiscUtils .getWriteMethodIncludingFlowStyle(destDescriptor, dest.getClass()); if (Arrays.asList(writeMethodIncludingFlowStyle.getParameterTypes()) .contains(origPropertyType)) { writeMethodIncludingFlowStyle.invoke(dest, valueOrigin); } else { continue; } } else { PropertyUtils.setSimpleProperty(dest, name, valueOrigin); } } catch (IllegalArgumentException ex) { throw new Error("setSimpleProperty returned an exception, dest: " + dest.getClass().getName() + " name : " + name + " valueOrig: " + valueOrigin, ex); } LOGGER.trace("Copied property " + name + " from " + orig.getClass().getName() + " object to a " + dest.getClass().getName() + " oid: " + getExternalId()); } // System.out.println("--"); } } }
From source file:recite18th.controller.Controller.java
public void input(String pkFieldValue) { try {//from w ww . jav a2 s. com if (pkFieldValue.equals("-2")) { //masukkan nilai yg tadi dimasukkan.. hadeuh... //Drawbacks : semua field harus didefinisikan jenis validasinya. dan itu ga baik. TODO : ubah ke formParams //dan sesuaikan dengan ada/tidaknya fieldnya dari model. Jika ada, baru diset. Jika tidak, berarti kontrol lain,e.g, Submit //SOLVED! Already use formParams to refill the value Enumeration e = validation.keys(); Model.session = request.getSession();//store session here modelForm = modelForm.createNewModel(); while (e.hasMoreElements()) { //TOFIX : restore PK Field Value and Foreign Field. //SOLVED. PK Field restored by refilled the value using formParams, whilst Foreign Field restored by adding translated value in corresponding model class String ruleName = (String) e.nextElement(); String value = getFormFieldValue(ruleName); try { PropertyUtils.setSimpleProperty(modelForm, ruleName, value); Logger.getLogger(Controller.class.getName()).log(Level.INFO, "validasi error, mengisi kembali " + ruleName + ", dengan value = " + value); } catch (Exception exception) { Logger.getLogger(Controller.class.getName()).log(Level.INFO, exception.getMessage()); } } String key = null, value = null; Iterator it = formParams.entrySet().iterator(); while (it.hasNext()) { Map.Entry pairs = (Map.Entry) it.next(); Logger.getLogger(Controller.class.getName()).log(Level.INFO, pairs.getKey() + " = " + pairs.getValue()); try { key = pairs.getKey() + ""; value = pairs.getValue() + ""; if (key.equals("hidden_" + modelForm.getPkFieldName())) { PropertyUtils.setSimpleProperty(modelForm, modelForm.getPkFieldName(), value); } else { PropertyUtils.setSimpleProperty(modelForm, key, value); } } catch (Exception ex) { Logger.getLogger(Controller.class.getName()).log(Level.INFO, "prop error = " + key + ", " + value); } } } else if (pkFieldValue == null || pkFieldValue.equals("") || pkFieldValue.equals("-1")) { Logger.getLogger(Controller.class.getName()).log(Level.INFO, "Buat Model baru"); Model.session = request.getSession(); modelForm = modelForm.createNewModel(); } else { Logger.getLogger(Controller.class.getName()).log(Level.INFO, "Ambil model dengan ID " + pkFieldValue); Model.session = request.getSession(); modelForm = modelForm.getModelById(pkFieldValue); } //TODO : maybe automatified here. But currently it's suffice ... (or being autogenerated by Synch.java.. that's it! later...) //expand for FOREIGN KEY label... No need. Model subclass just derived its corresponding _***Model.java, //..and add a property that translate its FK field (using Db.findValue is suffice. request.setAttribute("model", modelForm); ServletUtil.dispatch("/WEB-INF/views/" + formPage, request, response); } catch (Exception ex) { Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:recite18th.library.Db.java
public static ArrayList processDataSetResultSetAsArrayList(ResultSet resultSet, String fqnModel) { ArrayList result = new ArrayList(); try {//from w ww . java 2 s .c o m ResultSetMetaData metaData; int nColoumn; String columnName; String fieldValue; Field field; Object modelInstance; metaData = resultSet.getMetaData(); nColoumn = metaData.getColumnCount(); resultSet.beforeFirst(); Class modelClass = Class.forName(fqnModel); while (resultSet.next()) { modelInstance = modelClass.newInstance(); for (int i = 1; i <= nColoumn; i++) { columnName = metaData.getColumnName(i); fieldValue = resultSet.getString(i); PropertyUtils.setSimpleProperty(modelInstance, columnName, fieldValue); //the good ol'ways.. don't use BeanUtils... The problem is, how can it able to get the //field from super class?? //field = modelInstance.getClass().getDeclaredField(columnName); //field.set(modelInstance, fieldValue); } result.add(modelInstance); } } catch (Exception ex) { Logger.getLogger(Db.class.getName()).log(Level.SEVERE, null, ex); } return result; }
From source file:recite18th.library.Db.java
public static Object getBySql(String sql, String fqn) { Object modelInstance = null;/* w w w . j a v a 2 s . c o m*/ try { Class modelClass = Class.forName(fqn); ResultSetMetaData metaData; String columnName; String fieldValue; Field field; PreparedStatement pstmt = getCon().prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); Logger.getLogger(Db.class.getName()).log(Level.INFO, sql); ResultSet resultSet = pstmt.executeQuery(); metaData = resultSet.getMetaData(); int nColoumn = metaData.getColumnCount(); resultSet.beforeFirst(); Logger.getLogger(Db.class.getName()).log(Level.INFO, "About to process data"); if (resultSet.next()) { Logger.getLogger(Db.class.getName()).log(Level.INFO, "Data exist"); modelInstance = modelClass.newInstance(); for (int i = 1; i <= nColoumn; i++) { //the good ol'ways.. don't use BeanUtils... The problem is, how can it able to get the //field from super class?? //field = modelInstance.getClass().getDeclaredField(columnName); //field.set(modelInstance, fieldValue); columnName = metaData.getColumnName(i); fieldValue = resultSet.getString(i); PropertyUtils.setSimpleProperty(modelInstance, columnName, fieldValue); } } else { Logger.getLogger(Db.class.getName()).log(Level.INFO, "Data !exist"); } } catch (Exception ex) { Logger.getLogger(Db.class.getName()).log(Level.SEVERE, ex.getMessage(), ex); } return modelInstance; }