List of usage examples for org.apache.commons.beanutils PropertyUtils setProperty
public static void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
Set the value of the specified property of the specified bean, no matter which property reference format is used, with no type conversions.
For more details see PropertyUtilsBean
.
From source file:org.isatools.tablib.mapping.properties.StringPropertyMappingHelper.java
/** * Maps a value in the TAB into the target property of this helper, fills the object with the * mapped value.// w w w. ja v a 2 s .c o m * <p/> * This version assumes a standard setter exists, i.e.: * mappedObject.set<{@link #getPropertyName()}>. * It does not map anything if propertyValue is null. */ public void setProperty(T mappedObject, String propertyValue) { if (propertyValue == null) { return; } try { PropertyUtils.setProperty(mappedObject, getPropertyName(), propertyValue); } catch (Exception ex) { throw new TabInternalErrorException( String.format("Problem while mapping property '%s' from class '%s': %s", getPropertyName(), mappedObject.getClass().getSimpleName(), ex.getMessage()), ex); } log.trace("Property " + getFieldName() + "/'" + propertyValue + "' mapped to object " + mappedObject); }
From source file:org.jaffa.util.BeanHelper.java
/** This method will introspect the bean & get the setter method for the input propertyName. * It will then try & convert the propertyValue to the appropriate datatype. * Finally it will invoke the setter./* w w w. j a va 2s . co m*/ * @return A true indicates, the property was succesfully set to the passed value. A false indicates the property doesn't exist or the propertyValue passed is not compatible with the setter. * @param bean The bean class to be introspected. * @param propertyName The Property being searched for. * @param propertyValue The value to be set. * @throws IntrospectionException if an exception occurs during introspection. * @throws IllegalAccessException if the underlying method is inaccessible. * @throws InvocationTargetException if the underlying method throws an exception. */ public static boolean setField(Object bean, String propertyName, Object propertyValue) throws IntrospectionException, IllegalAccessException, InvocationTargetException { boolean result = false; if (bean instanceof DynaBean) { try { PropertyUtils.setProperty(bean, propertyName, propertyValue); result = true; } catch (NoSuchMethodException ignore) { // If the bean is a FlexBean instance, then the field could exist on the associated persistentObject if (bean instanceof FlexBean && ((FlexBean) bean).getPersistentObject() != null) { try { PropertyUtils.setProperty(((FlexBean) bean).getPersistentObject(), propertyName, propertyValue); result = true; } catch (NoSuchMethodException ignore2) { } } } } else { BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass()); if (beanInfo != null) { PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors(); if (pds != null) { for (PropertyDescriptor pd : pds) { if (StringHelper.equalsIgnoreCaseFirstChar(pd.getName(), propertyName)) { Method m = pd.getWriteMethod(); Object convertedPropertyValue = null; if (propertyValue != null) { if (pd.getPropertyType().isEnum()) { convertedPropertyValue = findEnum(pd.getPropertyType(), propertyValue.toString()); } else { try { convertedPropertyValue = DataTypeMapper.instance().map(propertyValue, pd.getPropertyType()); } catch (Exception e) { // do nothing break; } } } m.invoke(bean, new Object[] { convertedPropertyValue }); result = true; break; } } } } try { // Finally, check the FlexBean if (!result && bean instanceof IFlexFields && ((IFlexFields) bean).getFlexBean() != null && ((IFlexFields) bean).getFlexBean().getDynaClass() .getDynaProperty(propertyName) != null) { ((IFlexFields) bean).getFlexBean().set(propertyName, propertyValue); result = true; } } catch (Exception ignore) { } } return result; }
From source file:org.jaxygen.typeconverter.util.BeanUtil.java
/** * Copies bean content from one bean to another. The bean is copied using the * set and get methods. Method invokes all getXX methods on the from object, * and result pass to the corresponding setXX methods in the to object. Note * that it is not obvious that both object are of the same type. * If get and set methods do not match then it tries to use appropriate * converter registered in default type converter factory. * * @param from data provider object./*from w ww.j av a2s . c o m*/ * @param to data acceptor object. */ public static void translateBean(Object from, Object to) { PropertyDescriptor[] fromGetters = null; fromGetters = PropertyUtils.getPropertyDescriptors(from.getClass()); for (PropertyDescriptor pd : fromGetters) { if (pd.getReadMethod().isAnnotationPresent(BeanTransient.class) == false) { if (PropertyUtils.isWriteable(to, pd.getName())) { try { PropertyDescriptor wd = PropertyUtils.getPropertyDescriptor(to, pd.getName()); if (!wd.getWriteMethod().isAnnotationPresent(BeanTransient.class)) { Object copyVal = PropertyUtils.getProperty(from, pd.getName()); if (wd.getPropertyType().isAssignableFrom(pd.getPropertyType())) { PropertyUtils.setProperty(to, wd.getName(), copyVal); } else { try { Object convertedCopyVal = TypeConverterFactory.instance().convert(copyVal, wd.getPropertyType()); PropertyUtils.setProperty(to, wd.getName(), convertedCopyVal); } catch (ConversionError ex) { Logger.getAnonymousLogger().log(Level.WARNING, "Method {0}.{1} of type {2} is not compatible to {3}.{4} of type{5}", new Object[] { from.getClass().getName(), pd.getName(), pd.getPropertyType(), to.getClass().getName(), wd.getName(), wd.getPropertyType() }); } } } } catch (IllegalAccessException ex) { throw new java.lang.IllegalArgumentException("Could not translate bean", ex); } catch (InvocationTargetException ex) { throw new java.lang.IllegalArgumentException("Could not translate bean", ex); } catch (NoSuchMethodException ex) { throw new java.lang.IllegalArgumentException("Could not translate bean", ex); } } } } }
From source file:org.jbuilt.componentTree.jsf.AbstractJsfComponentTreeBuilder.java
@SuppressWarnings("unchecked") public SelectItem selectItems(Object... args) { SelectItem selectItemGroup = new SelectItemGroup(); System.out.print("selectItemGroup"); incrementIndent();//w w w .jav a 2 s . c om System.out.println(" "); for (Object arg : args) { if (arg instanceof ComponentAttribute) { try { PropertyUtils.setProperty(selectItemGroup, ((ComponentAttribute<String, Object>) arg).getKey(), ((ComponentAttribute<String, Object>) arg).getValue()); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } else { throw new IllegalArgumentException( "selectItemGroup method can only accept ComponentAttributes as arguments"); } decrementIndent(); System.out.print("end_selectItemGroup\n"); } return selectItemGroup; }
From source file:org.jbuilt.componentTree.jsf.AbstractJsfComponentTreeBuilder.java
@SuppressWarnings("unchecked") public SelectItem selectItem(Object... args) { SelectItem selectItem = new SelectItem(); System.out.print("selectItem"); incrementIndent();//from w w w . jav a 2 s. com System.out.println(" "); for (Object arg : args) { if (arg instanceof ComponentAttribute) { try { PropertyUtils.setProperty(selectItem, ((ComponentAttribute<String, Object>) arg).getKey(), ((ComponentAttribute<String, Object>) arg).getValue()); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } else { throw new IllegalArgumentException( "selectItem method can only accept ComponentAttributes as arguments"); } decrementIndent(); System.out.print("end_selectItem\n"); } return selectItem; }
From source file:org.jbuilt.utils.ValueClosure.java
public Object execute(/* Object bean, String prop, Object value */UIComponent component) { context = FacesContext.getCurrentInstance(); this.component = component; Object submittedValue;/*from w w w. j a va 2 s. co m*/ Object finalValue = null; if (context != null) { boolean renderResponse = context.getRenderResponse(); // String no = "no"; // String yes = "yes"; // out.println("are we in render response phase? " // + (renderResponse ? yes : no)); boolean hasArg = true; // args.length > 0 && args[0] != null; // if (context != null) { if (hasArg) { Object tempValue = null; Object origProp = null; try { origProp = PropertyUtils.getProperty(bean, prop); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InvocationTargetException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (NoSuchMethodException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } String clientId = component.getClientId(context); assert clientId != null; Map<String, String> requestMap = context.getExternalContext().getRequestParameterMap(); // FIXME: we should be getting the submitted value not the raw request value; Object newValue = requestMap.get(clientId); if (newValue != null) { newValue = getConvertedValue(newValue, component); } else { if (origProp != null) { newValue = origProp; } else { newValue = null; } } try { PropertyUtils.setProperty(bean, prop, newValue); finalValue = PropertyUtils.getProperty(bean, prop); Object a = null; } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchMethodException e) { // TODO Auto-generated catch block e.printStackTrace(); } // } } } return finalValue; }
From source file:org.jbuilt.utils.ValueClosure.java
public void setValue(ELContext elContext, Object value) throws ELException { if (elContext == null) { throw new NullPointerException("ELContext -> null"); }//from w w w.jav a 2 s .co m assert null != context; try { PropertyUtils.setProperty(bean, prop, ((ValueClosure) value).getValue()); } catch (Throwable e) { throw new ELException(e); } }
From source file:org.jbuilt.utils.ValueClosureExpression.java
@Override public void setValue(ELContext elContext, Object value) throws ELException { if (elContext == null) { throw new NullPointerException("ELContext -> null"); }//from w w w .j a v a 2 s . c o m assert null != context; try { PropertyUtils.setProperty(bean, prop, ((ValueClosureExpression) value).getValue()); } catch (Throwable e) { throw new ELException(e); } }
From source file:org.jmesaweb.controller.WorksheetPresidentController.java
protected void saveWorksheetChanges(Worksheet worksheet) { String uniquePropertyName = WorksheetUtils.getUniquePropertyName(worksheet); List<String> uniquePropertyValues = WorksheetUtils.getUniquePropertyValues(worksheet); final Map<String, President> presidents = presidentService.getPresidentsByUniqueIds(uniquePropertyName, uniquePropertyValues);//from w ww.ja v a 2 s . c o m worksheet.processRows(new WorksheetCallbackHandler() { public void process(WorksheetRow worksheetRow) { if (worksheetRow.getRowStatus().equals(WorksheetRowStatus.ADD)) { // would save the new President here } else if (worksheetRow.getRowStatus().equals(WorksheetRowStatus.REMOVE)) { // would delete the President here } else if (worksheetRow.getRowStatus().equals(WorksheetRowStatus.MODIFY)) { Collection<WorksheetColumn> columns = worksheetRow.getColumns(); for (WorksheetColumn worksheetColumn : columns) { String changedValue = worksheetColumn.getChangedValue(); validateColumn(worksheetColumn, changedValue); if (worksheetColumn.hasError()) { continue; } String uniqueValue = worksheetRow.getUniqueProperty().getValue(); President president = presidents.get(uniqueValue); String property = worksheetColumn.getProperty(); try { if (worksheetColumn.getProperty().equals("selected")) { if (changedValue.equals(CheckboxWorksheetEditor.CHECKED)) { PropertyUtils.setProperty(president, property, "y"); } else { PropertyUtils.setProperty(president, property, "n"); } } else { PropertyUtils.setProperty(president, property, changedValue); } } catch (Exception ex) { String msg = "Not able to set the property [" + property + "] when saving worksheet."; throw new RuntimeException(msg); } presidentService.save(president); } } } }); }
From source file:org.jresearch.gossip.list.RecordsData.java
/** * DOCUMENT ME!/*from www . ja v a 2 s . c om*/ * * @param rs * DOCUMENT ME! * @param mapping * DOCUMENT ME! * @param klass * DOCUMENT ME! * * @throws InstantiationException * DOCUMENT ME! * @throws IllegalAccessException * DOCUMENT ME! * @throws InvocationTargetException * DOCUMENT ME! * @throws NoSuchMethodException * DOCUMENT ME! * @throws SQLException * DOCUMENT ME! */ public void fillRecords(ResultSet rs, HashMap mapping, java.lang.Class klass) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SQLException { Set keys = mapping.keySet(); this.records = new ArrayList(); DbDriver dvDriver = DbDriver.getInstance(); while (rs.next()) { Object item = klass.newInstance(); Iterator it = keys.iterator(); while (it.hasNext()) { String key = (String) it.next(); PropertyUtils.setProperty(item, key, dvDriver.mapObjectType(rs.getObject((String) mapping.get(key)))); } this.records.add(item); } }