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.appverse.web.framework.backend.persistence.services.integration.impl.live.JPAPersistenceService.java
@Override public long persist(final T bean) throws Exception { logger.trace(PersistenceMessageBundle.MSG_DAO_PERSIST); long beanId = -1; try {/*from w w w.j av a2 s. c o m*/ beanId = (Long) PropertyUtils.getProperty(bean, this.BEAN_PK_NAME); } catch (final Exception ex) { logger.error(PersistenceMessageBundle.MSG_DAO_PERSIST_IDNOTFOUND, getClass().getName()); throw new PersistenceException(PersistenceMessageBundle.MSG_DAO_PERSIST_IDNOTFOUND); } if (beanId == 0) { // new em.persist(bean); beanId = (Long) PropertyUtils.getProperty(bean, this.BEAN_PK_NAME); } else { Object jpaProviderDelegate = em.getDelegate(); /* The following treatment is specific for Hibernate. * There is no problem with detached objects but at the moment that a JPA entity is attached to the * hibernate session, the version is cached. Does not matter that we override the cached version value * with the one coming from the business layer (the one kept in an object passed from a front end, * for instance, to check if the bean is stale or not) that the version kept when Hibernate generates the * update query is the one from the cache. * This implies that the version id's always match and so no OptimisticLockException is thrown. * EclipseLink handles this properly. Hibernate and JPA doc says that the application should not modify * the @Version annotated fields but in practice is quite common to retrieve an entity from the session * (it will be attached) and then override only the data that has been changed in the front end before * saving. * Even though detaching the object might have a small impact in performance we prefer to ensure that persist * method support properly JPA optimistic locking when JPA Provider is Hibernate. * The reason why we don't use "instance of" here is because depending on the Appverse Web persistence * module you are using (Hibernate or EclipseLink) you will have one classes or another but never both at * the same time, so using "instance of" is not a solution. * Another improvement that has been considered is to check if the annotation @Version is present * in one field or method of the class but this would imply using reflexion and visit every method * to see if the annotation is present or not. We think depending on the case this can affect performance * even more than detaching directly the object always before saving with Hibernate. */ if (jpaProviderDelegate.getClass().getName().contains("hibernate")) { em.detach(bean); } // update em.merge(bean); } PropertyUtils.setProperty(bean, this.BEAN_PK_NAME, beanId); return beanId; }
From source file:org.bbreak.excella.core.tag.excel2java.ObjectsParser.java
/** * ?/* w w w . j a v a2 s. c o m*/ * * @param sheet * @param tagCell ??? * @param data BookController?parseBook(), parseSheet()?<BR> * SheetParser?parseSheet?????<BR> * TagParser??????<BR> * @return ? * @throws ParseException */ @Override public List<Object> parse(Sheet sheet, Cell tagCell, Object data) throws ParseException { List<Object> resultList = new ArrayList<Object>(); Class<?> clazz = null; // int tagRowIdx = tagCell.getRowIndex(); // int propertyRowIdx; // int valueRowFromIdx; // int valueRowToIdx = sheet.getLastRowNum(); try { Map<String, String> paramDef = TagUtil.getParams(tagCell.getStringCellValue()); clazz = Class.forName(paramDef.get(PARAM_CLASS)); // ? propertyRowIdx = TagUtil.adjustValue(tagRowIdx, paramDef, PARAM_PROPERTY_ROW, DEFAULT_PROPERTY_ROW_ADJUST); if (propertyRowIdx < 0 || propertyRowIdx > sheet.getLastRowNum()) { throw new ParseException(tagCell, "?" + PARAM_PROPERTY_ROW); } // ? valueRowFromIdx = TagUtil.adjustValue(tagRowIdx, paramDef, PARAM_DATA_ROW_FROM, DEFAULT_VALUE_ROW_FROM_ADJUST); if (valueRowFromIdx < 0 || valueRowFromIdx > sheet.getLastRowNum()) { throw new ParseException(tagCell, "?" + PARAM_DATA_ROW_FROM); } // ? valueRowToIdx = TagUtil.adjustValue(tagRowIdx, paramDef, PARAM_DATA_ROW_TO, valueRowToIdx - tagRowIdx); if (valueRowToIdx > sheet.getLastRowNum() || valueRowToIdx < 0) { throw new ParseException(tagCell, "?" + PARAM_DATA_ROW_TO); } // ??? if (valueRowFromIdx > valueRowToIdx) { throw new ParseException(tagCell, "?" + PARAM_DATA_ROW_FROM + "," + PARAM_DATA_ROW_TO); } } catch (Exception e) { if (e instanceof ParseException) { throw (ParseException) e; } else { throw new ParseException(tagCell, e); } } // ??? Map<Integer, Class<?>> propertyClassMap = new HashMap<Integer, Class<?>>(); // ???? Map<Integer, String> propertyNameMap = new HashMap<Integer, String>(); // ?? Map<String, List<ObjectsPropertyParser>> customPropertyParserMap = new HashMap<String, List<ObjectsPropertyParser>>(); // ?? List<Integer> targetColNums = new ArrayList<Integer>(); Row propertyRow = sheet.getRow(propertyRowIdx); if (propertyRow == null) { // ?null?? return resultList; } int firstCellNum = propertyRow.getFirstCellNum(); int lastCellNum = propertyRow.getLastCellNum(); for (int cellCnt = firstCellNum; cellCnt < lastCellNum; cellCnt++) { Cell cell = propertyRow.getCell(cellCnt); if (cell == null) { continue; } try { String propertyName = cell.getStringCellValue(); if (propertyName.startsWith(BookController.COMMENT_PREFIX)) { continue; } Object obj = clazz.newInstance(); Class<?> propertyClass = PropertyUtils.getPropertyType(obj, propertyName); if (propertyClass != null) { propertyClassMap.put(cellCnt, propertyClass); propertyNameMap.put(cellCnt, propertyName); targetColNums.add(cellCnt); } else { // ???? for (ObjectsPropertyParser parser : customPropertyParsers) { if (parser.isParse(sheet, cell)) { List<ObjectsPropertyParser> propertyParsers = customPropertyParserMap.get(propertyName); if (propertyParsers == null) { propertyParsers = new ArrayList<ObjectsPropertyParser>(); } // ??????? if (!propertyParsers.contains(parser)) { propertyParsers.add(parser); } customPropertyParserMap.put(propertyName, propertyParsers); if (!targetColNums.contains(cellCnt)) { propertyNameMap.put(cellCnt, propertyName); targetColNums.add(cellCnt); } } } } } catch (Exception e) { throw new ParseException(cell, e); } } if (targetColNums.size() > 0) { // ???? // ?? for (int rowCnt = valueRowFromIdx; rowCnt <= valueRowToIdx; rowCnt++) { Row dataRow = sheet.getRow(rowCnt); if (dataRow == null) { continue; } Object obj; try { obj = clazz.newInstance(); for (Integer colCnt : targetColNums) { Cell cell = dataRow.getCell(colCnt); try { Class<?> propertyClass = propertyClassMap.get(colCnt); String propertyName = propertyNameMap.get(colCnt); // ? if (customPropertyParserMap.containsKey(propertyName)) { List<ObjectsPropertyParser> propertyParsers = customPropertyParserMap .get(propertyName); Map<String, String> params = TagUtil.getParams(propertyName); Object cellValue = PoiUtil.getCellValue(cell); // ?? for (ObjectsPropertyParser propertyParser : propertyParsers) { propertyParser.parse(obj, cellValue, TagUtil.getTag(propertyName), params); } } else { Object value = null; if (cell != null) { value = PoiUtil.getCellValue(cell, propertyClass); } PropertyUtils.setProperty(obj, propertyName, value); } } catch (Exception e) { throw new ParseException(cell, e); } } } catch (Exception e) { if (e instanceof ParseException) { throw (ParseException) e; } else { throw new ParseException(tagCell, e); } } resultList.add(obj); } } return resultList; }
From source file:org.bbreak.excella.trans.tag.sheet2java.SheetToJavaExecuter.java
/** * ??????<BR>/*from w ww .j a v a2s .c o m*/ * ???????<BR> * * @param targetSheet ? * @param targetColumnInfoList * @return * @throws ParseException */ protected List<Object> parseTargetSheet(Sheet targetSheet, SheetToJavaParseInfo sheetInfo, List<SheetToJavaSettingInfo> targetColumnInfoList) throws ParseException { // ?? List<Object> results = new ArrayList<Object>(); int logicalRowNum = sheetInfo.getLogicalNameRowNum() - 1; int valueStartRowNum = sheetInfo.getValueRowNum() - 1; int valueEndRowNum = targetSheet.getLastRowNum(); // ????index? Map<String, Integer> colLogicalNameMap = new HashMap<String, Integer>(); // colLogicalNameMap? Row row = targetSheet.getRow(logicalRowNum); if (row != null) { // ????? int firstColIdx = row.getFirstCellNum(); int lastColIdx = row.getLastCellNum(); for (int colIdx = firstColIdx; colIdx <= lastColIdx; colIdx++) { Cell cell = row.getCell(colIdx); if (cell != null) { try { // ??? String logicalCellValue = cell.getStringCellValue(); if (!logicalCellValue.startsWith(BookController.COMMENT_PREFIX)) { colLogicalNameMap.put(logicalCellValue, colIdx); } } catch (Exception e) { throw new ParseException(cell, e); } } } } // ????????????? List<Class<?>> classList = new ArrayList<Class<?>>(); // ?SettingInfo? Map<Class<?>, List<SheetToJavaSettingInfo>> settingInfoListMap = new HashMap<Class<?>, List<SheetToJavaSettingInfo>>(); // ??????? Map<Class<?>, List<String>> uniquePropertyListMap = new HashMap<Class<?>, List<String>>(); for (SheetToJavaSettingInfo settingInfo : targetColumnInfoList) { // ?? Class<?> clazz = settingInfo.getClazz(); List<SheetToJavaSettingInfo> settingInfoList = settingInfoListMap.get(clazz); if (settingInfoList == null) { // ????????? settingInfoList = new ArrayList<SheetToJavaSettingInfo>(); } List<String> uniquePropertyList = uniquePropertyListMap.get(clazz); if (uniquePropertyList == null) { // ????????? uniquePropertyList = new ArrayList<String>(); } // ?? settingInfoList.add(settingInfo); if (settingInfo.isUnique()) { uniquePropertyList.add(settingInfo.getPropertyName()); } // ??? if (!classList.contains(clazz)) { classList.add(clazz); } // ?? settingInfoListMap.put(clazz, settingInfoList); uniquePropertyListMap.put(clazz, uniquePropertyList); } // ??? for (Class<?> clazz : classList) { // ?? List<Object> objList = new ArrayList<Object>(); Object obj = null; try { // ??? for (int valueRowIdx = valueStartRowNum; valueRowIdx <= valueEndRowNum; valueRowIdx++) { Row valueRow = targetSheet.getRow(valueRowIdx); if (valueRow == null) { continue; } boolean isProcessRow = true; for (SheetToJavaListener propertyListener : sheetToJavaListeners) { if (!propertyListener.preProcessRow(valueRow)) { isProcessRow = false; } } if (!isProcessRow) { continue; } obj = Class.forName(clazz.getName()).newInstance(); // ??? List<SheetToJavaSettingInfo> settingInfoList = settingInfoListMap.get(clazz); for (SheetToJavaSettingInfo settingInfo : settingInfoList) { // ?? String propertyName = settingInfo.getPropertyName(); // Object value = settingInfo.getValue(); // ? Object settingValue = value; Cell valueCell = null; if (value instanceof String) { // ?? String settingValueStr = (String) value; if (settingValueStr.startsWith(TAG_PREFIX)) { // ?? if (settingValueStr.startsWith(TAG_LOGICAL_NAME_PREFIX)) { // ????? String logicalKey = TagUtil.getParam(settingValueStr, LNAME_TAG_PARAM_PREFIX, LNAME_TAG_PARAM_SUFFIX); Integer logicalKeyCol = colLogicalNameMap.get(logicalKey); if (logicalKeyCol == null) { Cell errorCell = null; for (SheetToJavaSettingInfo columnInfo : targetColumnInfoList) { if (columnInfo.getValue().equals(settingValueStr)) { errorCell = columnInfo.getValueCell(); } } throw new ParseException(errorCell, "????:" + logicalKey); } valueCell = valueRow.getCell(logicalKeyCol); if (valueCell != null) { Class<?> propertyClass = PropertyUtils.getPropertyType(obj, settingInfo.getPropertyName()); try { settingValue = PoiUtil.getCellValue(valueCell, propertyClass); } catch (RuntimeException e) { throw new ParseException(valueCell, "???????(" + propertyClass + ")", e); } } else { // ?null?? settingValue = null; valueCell = null; } } else { // ????? // ?? parseCustomProperty(valueCell, colLogicalNameMap, obj, valueRow, settingValueStr); // ?? continue; } } } // try { // ????? for (SheetToJavaListener propertyListener : sheetToJavaListeners) { propertyListener.preSetProperty(valueCell, obj, propertyName, settingValue); } PropertyUtils.setProperty(obj, propertyName, settingValue); // ???? for (SheetToJavaListener propertyListener : sheetToJavaListeners) { propertyListener.postSetProperty(valueCell, obj, propertyName, settingValue); } } catch (ParseException parseEx) { throw parseEx; } catch (RuntimeException e) { throw new ParseException(valueCell, "??????(" + propertyName + "=" + settingValue + "[" + settingValue.getClass().getCanonicalName() + "]" + ")", e); } } for (SheetToJavaListener propertyListener : sheetToJavaListeners) { if (!propertyListener.postProcessRow(valueRow, obj)) { isProcessRow = false; } } if (!isProcessRow) { continue; } List<String> uniquePropertyList = uniquePropertyListMap.get(clazz); if (!isDuplicateObj(obj, objList, uniquePropertyList)) { // ??????? objList.add(obj); } } // ???? results.addAll(objList); } catch (ParseException parseEx) { throw parseEx; } catch (Exception e) { throw new ParseException(e.toString()); } } return results; }
From source file:org.beanfuse.entity.Model.java
public static Object newInstance(Class clazz, Serializable id) { Object entity = getEntityType(clazz).newInstance(); try {/*from www .jav a 2s . c o m*/ PropertyUtils.setProperty(entity, "id", id); } catch (Exception e) { logger.error("initialize {} with id {} error", clazz, id); } return entity; }
From source file:org.beanfuse.model.EntityUtils.java
/** * <pre>/*from www . j ava 2s . c o m*/ * merge???(orig)????.? * ?????.?component ?entity? * ?id?0,???null. * * ?????.???(Set)? * ?????(hibernate)? * orig??dest added at * ? * </pre> * * @deprecated * @see EntityUtil#evictEmptyProperty * @param dest * @param orig * ?dest */ public static void merge(Object dest, Object orig) { String attr = ""; try { Set attrs = PropertyUtils.describe(orig).keySet(); attrs.remove("class"); for (Iterator it = attrs.iterator(); it.hasNext();) { attr = (String) it.next(); if (!PropertyUtils.isWriteable(orig, attr)) { continue; } Object value = PropertyUtils.getProperty(orig, attr); if (null != value) { if (value instanceof Component) { Object savedValue = PropertyUtils.getProperty(dest, attr); if (null == savedValue) { PropertyUtils.setProperty(dest, attr, value); } else { merge(savedValue, value); } } else if (value instanceof Collection) { continue; } else if (value instanceof Entity) { Serializable key = (Serializable) PropertyUtils.getProperty(value, ((Entity) value).key()); if (null == key) { continue; } else if (new EmptyKeyPredicate().evaluate(key)) { PropertyUtils.setProperty(dest, attr, null); } else { PropertyUtils.setProperty(dest, attr, value); } } else { PropertyUtils.setProperty(dest, attr, value); } } } } catch (Exception e) { logger.error("meger error", e); if (logger.isDebugEnabled()) { logger.debug( "error occur in reflection of attr:" + attr + " of entity " + dest.getClass().getName()); } return; } }
From source file:org.beanfuse.security.monitor.SecurityFilter.java
public void init(FilterConfig cfg) throws ServletException { Enumeration en = cfg.getInitParameterNames(); while (en.hasMoreElements()) { String property = (String) en.nextElement(); Object value = cfg.getInitParameter(property); try {/*from w w w.j a v a 2 s.c o m*/ PropertyUtils.setProperty(this, property, value); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } // ???? if (StringUtils.isEmpty(resourceExtractorClassName)) { resourceExtractorClassName = SimpleResourceExtractor.class.getName(); } try { resourceExtractor = (ResourceExtractor) Class.forName(resourceExtractorClassName).newInstance(); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } if (StringUtils.isEmpty(expiredPath)) { expiredPath = loginFailPath; } freeResources.add(resourceExtractor.extract(loginFailPath)); freeResources.add(resourceExtractor.extract(expiredPath)); freeResources.add(resourceExtractor.extract(noAuthorityPath)); logger.info("Filter {} configured successfully with free resources {}", cfg.getFilterName(), freeResources); }
From source file:org.beangle.ems.dictionary.service.impl.ImporterCodeGenListener.java
public void onItemFinish(TransferResult tr) { try {/*from w w w . ja v a 2 s . c o m*/ String code = (String) PropertyUtils.getProperty((Entity<?>) transfer.getCurrent(), codeAttrName); if (!codeGenerator.isValidCode(code)) { code = codeGenerator.gen(new CodeFixture((Entity<?>) transfer.getCurrent())); PropertyUtils.setProperty(transfer.getCurrent(), codeAttrName, code); } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.beangle.model.entity.Model.java
public static <T> T newInstance(final Class<T> clazz, final Serializable id) { @SuppressWarnings("unchecked") T entity = (T) getEntityType(clazz).newInstance(); try {/*w ww .j ava2 s . co m*/ PropertyUtils.setProperty(entity, "id", id); } catch (Exception e) { logger.error("initialize {} with id {} error", clazz, id); } return entity; }
From source file:org.beangle.model.entity.populator.ConvertPopulatorBean.java
/** * ?<br>/*from w w w . j a v a 2s.c o m*/ * a.b.c,?a a.b a.b.c??? * * @param attr * @param target * @return ??? */ public ObjectAndType initProperty(final Object target, String entityName, final String attr) { Object propObj = target; Object property = null; int index = 0; String[] attrs = StringUtils.split(attr, "."); Type type = Model.getType(entityName); while (index < attrs.length) { try { property = PropertyUtils.getProperty(propObj, attrs[index]); Type propertyType = type.getPropertyType(attrs[index]); // ? if (null == propertyType) { logger.error("Cannot find property type [{}] of {}", attrs[index], propObj.getClass()); throw new RuntimeException( "Cannot find property type " + attrs[index] + " of " + propObj.getClass().getName()); } if (null == property) { property = propertyType.newInstance(); PropertyUtils.setProperty(propObj, attrs[index], property); } index++; propObj = property; type = propertyType; } catch (Exception e) { throw new RuntimeException(e); } } return new ObjectAndType(property, type); }
From source file:org.beangle.model.entity.populator.ConvertPopulatorBean.java
/** * params([attr(string)->value(object)]<br> * <br>//ww w . ja va2 s . c o m * paramsidnullnull.<br> * ??idparams null? * * @param params * @param entity */ public Object populate(Object entity, String entityName, Map<String, Object> params) { Type type = Model.getType(entityName); for (final Map.Entry<String, Object> paramEntry : params.entrySet()) { String attr = paramEntry.getKey(); Object value = paramEntry.getValue(); if (value instanceof String) { if (StringUtils.isEmpty((String) value)) { value = null; } else if (TRIM_STR) { value = ((String) value).trim(); } } // if (null != type && type.isEntityType() && attr.equals(((EntityType) type).getIdPropertyName())) { if (ValidEntityKeyPredicate.INSTANCE.evaluate(value)) { setValue(attr, value, entity); } else { try { PropertyUtils.setProperty(entity, attr, null); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } continue; } // if (-1 == attr.indexOf('.')) { setValue(attr, value, entity); } else { String parentAttr = StringUtils.substring(attr, 0, attr.lastIndexOf('.')); try { ObjectAndType ot = initProperty(entity, entityName, parentAttr); if (null == ot) { logger.error("error attr:[" + attr + "] value:[" + value + "]"); continue; } // if (ot.getType().isEntityType()) { String foreignKey = ((EntityType) ot.getType()).getIdPropertyName(); if (attr.endsWith("." + foreignKey)) { if (null == value) { setValue(parentAttr, null, entity); } else { Object foreignValue = PropertyUtils.getProperty(entity, attr); // ? if (null != foreignValue) { if (!foreignValue.toString().equals(value.toString())) { setValue(parentAttr, null, entity); initProperty(entity, entityName, parentAttr); setValue(attr, value, entity); } } else { setValue(attr, value, entity); } } } else { setValue(attr, value, entity); } } else { setValue(attr, value, entity); } } catch (Exception e) { logger.error("error attr:[" + attr + "] value:[" + value + "]", e); } } if (logger.isDebugEnabled()) { logger.debug("populate attr:[" + attr + "] value:[" + value + "]"); } } return entity; }