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:com.sun.faces.mock.MockResultSet.java
public void updateObject(String columnName, Object value) throws SQLException { if ((row <= 0) || (row > beans.length)) { throw new SQLException("Invalid row number " + row); }//w w w .j av a 2 s .c o m try { PropertyUtils.setSimpleProperty(beans[row - 1], columnName, value); } catch (Exception e) { throw new SQLException(e.getMessage()); } }
From source file:gov.nih.nci.caarray.application.permissions.PermissionsManagementServiceBean.java
private void convertToLikeProperty(User u, User newUser, PropertyDescriptor pd) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (pd.getPropertyType().equals(String.class)) { final String value = (String) PropertyUtils.getSimpleProperty(newUser, pd.getName()); if (value != null) { PropertyUtils.setSimpleProperty(newUser, pd.getName(), value + "%"); }/* w w w . jav a 2 s .c o m*/ } }
From source file:com.panemu.tiwulfx.form.BaseControl.java
/** * Set value entered to this input control to the passed obj on * corresponding property name.//from w w w .j a v a2s .c o m * * @param obj */ public void pullValue(Object obj) { try { if (propertyName != null && !propertyName.trim().isEmpty()) { PropertyUtils.setSimpleProperty(obj, propertyName, this.getValue()); } else { System.out.println("Warning: propertyName is not set for " + getId()); } } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { RuntimeException ex2 = new RuntimeException("Error when pulling " + propertyName + ".", ex); throw ex2; } }
From source file:com.bstek.dorado.data.config.definition.DataTypeDefinition.java
protected void injectResourceString(EntityDataType dataType, String key, String resourceString) throws Exception { Object object = dataType;// www. j a v a 2s.c om ResourceInjection resourceInjection = object.getClass().getAnnotation(ResourceInjection.class); String[] sections = StringUtils.split(key, "."); int len = sections.length; for (int i = 0; i < len; i++) { String section = sections[i]; boolean isObject = section.charAt(0) == '#'; if (isObject) { section = section.substring(1); if (resourceInjection == null) { throwInvalidResourceKey(key); } String methodName = resourceInjection.subObjectMethod(); if (StringUtils.isEmpty(methodName)) { throwInvalidResourceKey(key); } object = MethodUtils.invokeExactMethod(object, methodName, new String[] { section }); if (object == null) { break; } resourceInjection = object.getClass().getAnnotation(ResourceInjection.class); if (i == len - 1) { String[] defaultProperties; if (resourceInjection == null) { defaultProperties = DEFAULT_PROPERTIES; } else { defaultProperties = resourceInjection.defaultProperty(); } boolean found = false; for (String property : defaultProperties) { if (PropertyUtils.isWriteable(object, property)) { // if (PropertyUtils.getSimpleProperty(object, // property) == null) { PropertyUtils.setSimpleProperty(object, property, resourceString); // } found = true; break; } } if (!found) { throwInvalidResourceKey(key); } } } else { if (i == len - 1) { if (PropertyUtils.getSimpleProperty(object, section) == null) { PropertyUtils.setSimpleProperty(object, section, resourceString); } } else { object = PropertyUtils.getSimpleProperty(object, section); } } } }
From source file:com.sqewd.open.dal.core.persistence.db.EntityHelper.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public static Object getColumnValue(final ResultSet rs, final StructAttributeReflect attr, final AbstractEntity entity, final AbstractJoinGraph gr, final Stack<KeyValuePair<Class<?>>> path) throws Exception { Object value = null;/* w w w. j a va2 s. co m*/ KeyValuePair<String> alias = gr.getAliasFor(path, attr.Column, 0); String tabprefix = alias.getKey(); if (EnumPrimitives.isPrimitiveType(attr.Field.getType())) { EnumPrimitives prim = EnumPrimitives.type(attr.Field.getType()); switch (prim) { case ECharacter: String sv = rs.getString(tabprefix + "." + attr.Column); if (!rs.wasNull()) { PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), sv.charAt(0)); } break; case EShort: short shv = rs.getShort(tabprefix + "." + attr.Column); if (!rs.wasNull()) { PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), shv); } break; case EInteger: int iv = rs.getInt(tabprefix + "." + attr.Column); if (!rs.wasNull()) { PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), iv); } break; case ELong: long lv = rs.getLong(tabprefix + "." + attr.Column); if (!rs.wasNull()) { PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), lv); } break; case EFloat: float fv = rs.getFloat(tabprefix + "." + attr.Column); if (!rs.wasNull()) { PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), fv); } break; case EDouble: double dv = rs.getDouble(tabprefix + "." + attr.Column); if (!rs.wasNull()) { PropertyUtils.setSimpleProperty(entity, attr.Field.getName(), dv); } break; default: throw new Exception("Unsupported Data type [" + prim.name() + "]"); } } else if (attr.Convertor != null) { // TODO : Not supported at this time. value = rs.getString(tabprefix + "." + attr.Column); } else if (attr.Field.getType().equals(String.class)) { value = rs.getString(tabprefix + "." + attr.Column); if (rs.wasNull()) { value = null; } } else if (attr.Field.getType().equals(Date.class)) { long lvalue = rs.getLong(tabprefix + "." + attr.Column); if (!rs.wasNull()) { Date dt = new Date(lvalue); value = dt; } } else if (attr.Field.getType().isEnum()) { String svalue = rs.getString(tabprefix + "." + attr.Column); if (!rs.wasNull()) { Class ecls = attr.Field.getType(); value = Enum.valueOf(ecls, svalue); } } else if (attr.Reference != null) { Class<?> rt = Class.forName(attr.Reference.Class); Object obj = rt.newInstance(); if (!(obj instanceof AbstractEntity)) throw new Exception("Unsupported Entity type [" + rt.getCanonicalName() + "]"); AbstractEntity rentity = (AbstractEntity) obj; if (path.size() > 0) { path.peek().setKey(attr.Column); } KeyValuePair<Class<?>> cls = new KeyValuePair<Class<?>>(); cls.setValue(rentity.getClass()); path.push(cls); setEntity(rentity, rs, gr, path); value = rentity; path.pop(); } return value; }
From source file:net.mojodna.searchable.AbstractSearcher.java
/** * Search the index with the specified query. * /* w ww. j a v a2 s . c o m*/ * @param query Query to use. * @param filter Filter to use. * @param searcher Lucene Searcher to perform the search with. * @param offset Offset to begin result set at. * @param count Number of results to return. * @param sort Sort to use. * @return ResultSet containing results. * @throws SearchException * @throws IOException */ protected ResultSet doSearch(final Query query, final Filter filter, final Searcher searcher, final Integer offset, final Integer count, final Sort sort) throws SearchException, IOException { // execute the search log.debug("Searching with query: " + query.toString()); final Hits hits = searcher.search(query, filter, sort); // create a container for results final List<Result> results = new LinkedList<Result>(); // instantiate and initialize the ResultSet final ResultSetImpl rs = new ResultSetImpl(hits.length()); rs.setQuery(query); final int numResults; if (null != count) numResults = Math.min(offset + count, hits.length()); else numResults = hits.length(); rs.setOffset(offset); // loop through results starting at offset and stopping after numResults for (int i = offset; i < numResults; i++) { final Document doc = hits.doc(i); Result result = null; // load the class name final String className = doc.get(TYPE_FIELD_NAME); try { // attempt to instantiate an instance of the specified class try { if (null != className) { final Object o = Class.forName(className).newInstance(); if (o instanceof Result) { log.debug("Created new instance of: " + className); result = (Result) o; } } } catch (final ClassNotFoundException e) { // class was invalid, or something } // fall back to a GenericResult as a container if (null == result) result = new GenericResult(); if (result instanceof Searchable) { // special handling for searchables final String idField = SearchableBeanUtils.getIdPropertyName(((Searchable) result).getClass()); // attempt to load the id and set the id property on the Searchable appropriately final String id = doc.get(ID_FIELD_NAME); final Field idClass = doc.getField(ID_TYPE_FIELD_NAME); if (null != id) { log.debug("Setting id to '" + id + "' of type " + idClass.stringValue()); try { final Object idValue = ConvertUtils.convert(id, Class.forName(idClass.stringValue())); PropertyUtils.setSimpleProperty(result, idField, idValue); } catch (final ClassNotFoundException e) { log.warn("Id type was not a class that could be found: " + idClass.stringValue()); } } else { log.warn("Id value was null."); } } else { final GenericResult gr = new GenericResult(); gr.setId(doc.get(ID_FIELD_NAME)); gr.setType(doc.get(TYPE_FIELD_NAME)); result = gr; } // load stored fields and put them in the Result final Map<String, String> storedFields = new HashMap<String, String>(); final Enumeration fields = doc.fields(); while (fields.hasMoreElements()) { final Field f = (Field) fields.nextElement(); // exclude private fields if (!PRIVATE_FIELD_NAMES.contains(f.name()) && !f.name().startsWith(IndexSupport.SORTABLE_PREFIX)) storedFields.put(f.name(), f.stringValue()); } result.setStoredFields(storedFields); } catch (final Exception e) { throw new SearchException("Could not reconstitute resultant object.", e); } result.setRanking(i); result.setScore(hits.score(i)); results.add(result); } rs.setResults(results); searcher.close(); return rs; }
From source file:com.projity.util.ClassUtils.java
public static boolean setSimpleProperty(Object bean, String name, Object value) { try {//from ww w . j a v a 2 s. c o m PropertyUtils.setSimpleProperty(bean, name, value); return true; } catch (Exception e) { //claur // TODO Auto-generated catch block e.printStackTrace(); } return false; }
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 .ja v a2 s . co 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.sun.faces.config.ManagedBeanFactory.java
protected void setPropertiesIntoBean(Object bean, int beanType, ManagedBeanBean managedBean) { Object value = null;/*from ww w. j a v a 2 s .c om*/ String propertyClass = null, propertyName = null, strValue = null; int propertyType = -1; Class valueClass = null; ManagedPropertyBean[] properties = managedBean.getManagedProperties(); if (null == properties) { // a bean is allowed to have no properties return; } // iterate over the properties and load each into the bean for (int i = 0, len = properties.length; i < len; i++) { // skip null properties or properties without names if (null == properties[i] || null == (propertyName = properties[i].getPropertyName())) { continue; } // determine what kind of property we have try { // this switch statement sets the "value" local variable // and tries to set it into the bean. switch (propertyType = getPropertyType(properties[i])) { case TYPE_IS_LIST: setArrayOrListPropertiesIntoBean(bean, properties[i]); break; case TYPE_IS_MAP: setMapPropertiesIntoBean(bean, properties[i]); break; case TYPE_IS_SIMPLE: // if the config bean has no managed-property-class // defined if (null == (propertyClass = properties[i].getPropertyClass())) { // look at the bean property if (null == (valueClass = PropertyUtils.getPropertyType(bean, propertyName))) { // if the bean property class can't be // determined, use the fallback. valueClass = getValueClassConsideringPrimitives(propertyClass); } } else { // the config has a managed-property-class // defined valueClass = getValueClassConsideringPrimitives(propertyClass); } strValue = properties[i].getValue(); if (Util.isVBExpression(strValue)) { value = evaluateValueBindingGet(strValue); } else if (null == strValue && properties[i].isNullValue()) { value = null; } else { value = strValue; } // convert the value if necessary value = getConvertedValueConsideringPrimitives(value, valueClass); PropertyUtils.setSimpleProperty(bean, propertyName, value); break; default: Util.doAssert(false); } } catch (FacesException fe) { throw fe; } catch (Exception ex) { // if the property happens to be attribute on // UIComponent then bean introspection set will fail. if (TYPE_IS_UICOMPONENT == beanType) { setComponentAttribute(bean, propertyName, value); } else { // then this is a real exception to rethrow Object[] obj = new Object[1]; obj[0] = propertyName; throw new FacesException( Util.getExceptionMessageString(Util.ERROR_SETTING_BEAN_PROPERTY_ERROR_MESSAGE_ID, obj), ex); } } } }
From source file:com.panemu.tiwulfx.table.TableControl.java
/** * Paste text on clipboard. Doesn't work on READ mode. *//* w w w. j av a2 s . c om*/ public void paste() { if (mode.get() == Mode.READ) { return; } final Clipboard clipboard = Clipboard.getSystemClipboard(); if (clipboard.hasString()) { final String text = clipboard.getString(); if (text != null) { List<TablePosition> cells = tblView.getSelectionModel().getSelectedCells(); if (cells.isEmpty()) { return; } TablePosition cell = cells.get(0); List<TableColumn<R, ?>> lstColumn = getLeafColumns(); TableColumn startColumn = null; for (TableColumn clm : lstColumn) { if (clm instanceof BaseColumn && clm == cell.getTableColumn()) { startColumn = (BaseColumn) clm; break; } } if (startColumn == null) { return; } int rowIndex = cell.getRow(); String[] arrString = text.split("\n"); boolean stopPasting = false; for (String line : arrString) { if (stopPasting) { break; } R item = null; if (rowIndex < tblView.getItems().size()) { item = tblView.getItems().get(rowIndex); } else if (mode.get() == Mode.EDIT) { /** * Will ensure the content display to TEXT_ONLY because * there is no way to update cell editors value (in * agile editing mode) */ tblView.getSelectionModel().clearSelection(); return;//stop pasting as it already touched last row } if (!lstChangedRow.contains(item)) { if (mode.get() == Mode.INSERT) { //means that selected row is not new row. Let's create new row createNewRow(rowIndex); item = tblView.getItems().get(rowIndex); } else { lstChangedRow.add(item); } } showRow(rowIndex); /** * Handle multicolumn paste */ String[] stringCellValues = line.split("\t"); TableColumn toFillColumn = startColumn; tblView.getSelectionModel().select(rowIndex, toFillColumn); for (String stringCellValue : stringCellValues) { if (toFillColumn == null) { break; } if (toFillColumn instanceof BaseColumn && toFillColumn.isEditable() && toFillColumn.isVisible()) { try { Object oldValue = toFillColumn.getCellData(item); Object newValue = ((BaseColumn) toFillColumn).convertFromString(stringCellValue); PropertyUtils.setSimpleProperty(item, ((BaseColumn) toFillColumn).getPropertyName(), newValue); if (mode.get() == Mode.EDIT) { ((BaseColumn) toFillColumn).addRecordChange(item, oldValue, newValue); } } catch (Exception ex) { MessageDialog.Answer answer = MessageDialogBuilder.error(ex) .message("msg.paste.error", stringCellValue, toFillColumn.getText()) .buttonType(MessageDialog.ButtonType.YES_NO) .yesOkButtonText("continue.pasting").noButtonText("stop") .show(getScene().getWindow()); if (answer == MessageDialog.Answer.NO) { stopPasting = true; break; } } } tblView.getSelectionModel().selectRightCell(); TablePosition nextCell = tblView.getSelectionModel().getSelectedCells().get(0); if (nextCell.getTableColumn() instanceof BaseColumn && nextCell.getTableColumn() != toFillColumn) { toFillColumn = (BaseColumn) nextCell.getTableColumn(); } else { toFillColumn = null; } } rowIndex++; } refresh(); /** * Will ensure the content display to TEXT_ONLY because there is * no way to update cell editors value (in agile editing mode) */ tblView.getSelectionModel().clearSelection(); } } }