/** * 将bean装换为一个map(能将枚举转换为int) * * @param bean * @return */ @SuppressWarnings({"unchecked", "rawtypes"}) public static Map buildMap(Object bean) { if (bean == null) { return null; } try { Map map = describe(bean); PropertyDescriptor[] pds = BEANUTILSBEAN.getPropertyUtils().getPropertyDescriptors(bean); for (PropertyDescriptor pd : pds) { Class type = pd.getPropertyType(); if (type.isEnum()) { Object value = BEANUTILSBEAN.getPropertyUtils().getSimpleProperty(bean, pd.getName()); Enum enums = EnumUtils.valueOf(type, String.valueOf(value)); map.put(pd.getName(), enums == null ? -1 : enums.ordinal()); } else if (type == java.util.Date.class) { // 防止是Timestamp Object value = BEANUTILSBEAN.getPropertyUtils().getSimpleProperty(bean, pd.getName()); if (value != null) { Calendar cal = Calendar.getInstance(); cal.setTime((java.util.Date) value); map.put(pd.getName(), cal.getTime()); } } } return map; } catch (Throwable e) { LOGGER.error("BeanUtil 创建Map失败:", e); throw new RuntimeException(e); } }
// 从DbUnit的EXCEL数据集文件创建多个bean public static <T> T createBean(Class testClass, String file, String tableName, Class<T> clazz) throws Exception { BeanUtilsBean beanUtils = createBeanUtils(); List<Map<String, Object>> propsList = createProps(testClass, file, tableName); T bean = clazz.newInstance(); beanUtils.populate(bean, propsList.get(0)); return bean; }
public OverrideUpdateAgentRequest(UpdateAgentRequest request) throws ServiceException { BeanUtilsBean ub = BeanUtils.getUtilBean(); try { ub.copyProperties(this, request); this.xmlData = new XMLData(); } catch (IllegalAccessException e) { throw new ServiceException(UAR001, e); } catch (InvocationTargetException e) { throw new ServiceException(UAR001, e); } }
// 从DbUnit的EXCEL数据集文件创建多个bean public static <T> List<T> createBeans( Class testClass, String file, String tableName, Class<T> clazz) throws Exception { BeanUtilsBean beanUtils = createBeanUtils(); List<Map<String, Object>> propsList = createProps(testClass, file, tableName); List<T> beans = new ArrayList<T>(); for (Map<String, Object> props : propsList) { T bean = clazz.newInstance(); beanUtils.populate(bean, props); beans.add(bean); } return beans; }
@SuppressWarnings("rawtypes") protected void fillConfiguration( WebApplicationConfiguration conf, BeanUtilsBean beanUtil, String key, String value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Class cls = PropertyUtils.getPropertyType(conf, key); if (cls.isArray()) { String[] values = value.split(","); beanUtil.setProperty(conf, key, values); } else { beanUtil.setProperty(conf, key, value); } }
/** * 拷贝属性给对象(类型宽松) * * @param bean * @param name 属性名 * @param value 属性值 */ @SuppressWarnings({"unchecked", "rawtypes"}) public static void copyProperty(Object bean, String name, Object value) { try { Class propertyClazz = BEANUTILSBEAN.getPropertyUtils().getPropertyType(bean, name); if (propertyClazz.isEnum() && value instanceof Integer) { // 属性枚举型 目标值是整型 value = EnumUtils.getEnum(propertyClazz, (Integer) value); } BEANUTILSBEAN.copyProperty(bean, name, value); } catch (Throwable e) { LOGGER.error("BeanUtil 对象属性赋值出错:", e); throw new RuntimeException(e); } }
private void copyPartialProperties(Podcast verifyPodcastExistenceById, Podcast podcast) { BeanUtilsBean notNull = new NullAwareBeanUtilsBean(); try { notNull.copyProperties(verifyPodcastExistenceById, podcast); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
/** {@inheritDoc} */ @Override public Platform updateDetached(Platform platform) { Platform dbObject = findByID(platform.getPlatformId()); try { BeanUtilsBean beanUtils = new NullBeanUtils(); beanUtils.copyProperties(dbObject, platform); return (Platform) this.getHibernateTemplate().merge(dbObject); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; }
public ActionForward printQuestionnaireAnswer( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // TODO : this is only available after questionnaire is saved ? ActionForward forward = mapping.findForward(Constants.MAPPING_BASIC); Map<String, Object> reportParameters = new HashMap<String, Object>(); ProtocolFormBase protocolForm = (ProtocolFormBase) form; ProtocolBase protocol = protocolForm.getActionHelper().getProtocol(); final int answerHeaderIndex = this.getSelectedLine(request); String methodToCall = (String) request.getAttribute(KRADConstants.METHOD_TO_CALL_ATTRIBUTE); String formProperty = StringUtils.substringBetween(methodToCall, ".printQuestionnaireAnswer.", ".line"); QuestionnaireHelperBase helper = (QuestionnaireHelperBase) BeanUtilsBean.getInstance().getPropertyUtils().getProperty(form, formProperty); AnswerHeader answerHeader = helper.getAnswerHeaders().get(answerHeaderIndex); // TODO : a flag to check whether to print answer or not // for release 3 : if questionnaire questions has answer, then print answer. reportParameters.put( QuestionnaireConstants.QUESTIONNAIRE_SEQUENCE_ID_PARAMETER_NAME, answerHeader.getQuestionnaire().getQuestionnaireSeqIdAsInteger()); reportParameters.put("template", answerHeader.getQuestionnaire().getTemplate()); reportParameters.put("coeusModuleSubItemCode", answerHeader.getModuleSubItemCode()); AttachmentDataSource dataStream = getQuestionnairePrintingService().printQuestionnaireAnswer(protocol, reportParameters); if (dataStream.getData() != null) { streamToResponse(dataStream, response); forward = null; } return forward; }
// revise BeanUtils describe method do not copy data type public static Map describe(Object bean) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (bean == null) { return (new java.util.HashMap()); } Map description = new HashMap(); if (bean instanceof DynaBean) { DynaProperty[] descriptors = ((DynaBean) bean).getDynaClass().getDynaProperties(); for (int i = 0; i < descriptors.length; i++) { String name = descriptors[i].getName(); description.put(name, org.apache.commons.beanutils.BeanUtils.getProperty(bean, name)); } } else { PropertyDescriptor[] descriptors = BeanUtilsBean.getInstance().getPropertyUtils().getPropertyDescriptors(bean); Class clazz = bean.getClass(); for (int i = 0; i < descriptors.length; i++) { String name = descriptors[i].getName(); if (MethodUtils.getAccessibleMethod(clazz, descriptors[i].getReadMethod()) != null) { description.put(name, PropertyUtils.getNestedProperty(bean, name)); } } } return (description); }
/** * 获取系统设置 * * @return 系统设置 */ public static Setting get() { Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME); net.sf.ehcache.Element cacheElement = cache.get(Setting.CACHE_KEY); Setting setting; if (cacheElement != null) { setting = (Setting) cacheElement.getObjectValue(); } else { setting = new Setting(); try { File shopxxXmlFile = new ClassPathResource(CommonAttributes.SHOPXX_XML_PATH).getFile(); Document document = new SAXReader().read(shopxxXmlFile); List<Element> elements = document.selectNodes("/shopxx/setting"); for (Element element : elements) { String name = element.attributeValue("name"); String value = element.attributeValue("value"); try { beanUtils.setProperty(setting, name, value); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting)); } return setting; }
/** * 璁剧疆瀵硅薄鎸囧畾鍚嶇О鐨勫睘鎬х殑锟� * * @param object 瀵硅薄 * @param name 鍙傛暟鍚嶇О * @param value 鍙傛暟鐨勶拷?? */ public static void setProperty(Object object, String name, Object value) { try { beanUtilsBean.setProperty(object, name, value); } catch (Exception e) { throw new RuntimeException("Could not setProperty[" + name + "]", e); } }
/** * 克隆对象 * * @param bean 需要克隆的对象 * @return {@link Object} 克隆后的对象 */ public static Object cloneBean(Object bean) { try { return BEANUTILSBEAN.cloneBean(bean); } catch (Throwable e) { LOGGER.error("BeanUtil 对象克隆出错:", e); throw new RuntimeException(e); } }
/** {@inheritDoc} */ @Override public ProcessingRelationship updateDetached(ProcessingRelationship processingRelationship) { ProcessingRelationship dbObject = findByProcessings( processingRelationship.getProcessingByParentId(), processingRelationship.getProcessingByChildId()); try { BeanUtilsBean beanUtils = new NullBeanUtils(); beanUtils.copyProperties(dbObject, processingRelationship); return (ProcessingRelationship) this.getHibernateTemplate().merge(dbObject); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return null; }
/** * 给对象属性赋值 * * @param bean * @param name 属性名 * @param value 属性值 */ public static void setProperty(Object bean, String name, Object value) { try { BEANUTILSBEAN.setProperty(bean, name, value); } catch (Throwable e) { LOGGER.error("BeanHelper 给对象属性赋值出错:", e); throw new RuntimeException(e); } }
/** * 获取对象属性值 * * @param bean * @param name * @return */ public static Object getProperty(Object bean, String name) { try { return BEANUTILSBEAN.getPropertyUtils().getSimpleProperty(bean, name); } catch (Throwable e) { LOGGER.error("BeanHelper 获取对象属性值出错:", e); throw new RuntimeException(e); } }
/** * Implements the Contextualizable interface using bean introspection. * * @param aContext {@inheritDoc} * @throws CheckstyleException {@inheritDoc} * @see Contextualizable */ public final void contextualize(Context aContext) throws CheckstyleException { final BeanUtilsBean beanUtils = createBeanUtilsBean(); // TODO: debug log messages final Collection<String> attributes = aContext.getAttributeNames(); for (final String key : attributes) { final Object value = aContext.get(key); try { beanUtils.copyProperty(this, key, value); } catch (final InvocationTargetException e) { // TODO: log.debug("The bean " + this.getClass() // + " is not interested in " + value) throw new CheckstyleException( "cannot set property " + key + " to value " + value + " in bean " + this.getClass().getName(), e); } catch (final IllegalAccessException e) { throw new CheckstyleException( "cannot access " + key + " in " + this.getClass().getName(), e); } catch (final IllegalArgumentException e) { throw new CheckstyleException( "illegal value '" + value + "' for property '" + key + "' of bean " + this.getClass().getName(), e); } catch (final ConversionException e) { throw new CheckstyleException( "illegal value '" + value + "' for property '" + key + "' of bean " + this.getClass().getName(), e); } } }
/** * 将bean装换为一个map(不能将枚举转换为int) * * @param bean * @return */ @SuppressWarnings({"rawtypes"}) public static Map describe(Object bean) { try { return BEANUTILSBEAN.describe(bean); } catch (Throwable e) { LOGGER.error("BeanUtil 对象克隆出错:", e); throw new RuntimeException(e); } }
/** * @param clazz * @param propertyName * @return */ public static PropertyDescriptor getPropertyDescriptor(Class clazz, String propertyName) { PropertyDescriptor[] descriptors = BeanUtilsBean.getInstance().getPropertyUtils().getPropertyDescriptors(clazz); if (descriptors != null) { for (PropertyDescriptor descriptor : descriptors) { if (propertyName.equals(descriptor.getName())) return descriptor; } } return null; }
/** configure. */ static void configureBeanUtils() { BeanUtilsBean beanUtilsBean = BeanUtilsBean.getInstance(); if (beanUtilsBean.getClass() != BeanUtilsBean.class) { throw new IllegalStateException( "Someone has already switched the default org.apache.commons.beanutils.BeanUtilsBean instance"); //$NON-NLS-1$ } if (beanUtilsBean.getConvertUtils().getClass() != ConvertUtilsBean.class) { throw new IllegalStateException( "Someone has already switched the default org.apache.commons.beanutils.ConvertUtilsBean instance"); //$NON-NLS-1$ } BeanUtilsBean.setInstance(new BeanUtilsBean(new EnumAwareConvertUtilsBean())); DateTimeConverter dtConverter = new DateConverter(); dtConverter.setPattern(Bo2UtilsEnvironment.getIsoDateFormatPattern()); ConvertUtils.register(dtConverter, java.util.Date.class); }
public static void copy(Object dest, Object src) { Field[] fields = src.getClass().getFields(); for (Field field : fields) { try { BeanUtilsBean.getInstance().setProperty(dest, field.getName(), field.get(src)); } catch (Exception e) { e.printStackTrace(); } } }
/** {@inheritDoc} 安静的拷贝属性,如果属性非法或其他错误则记录日志 */ public boolean populateValue( final Object target, String entityName, final String attr, final Object value) { try { if (attr.indexOf('.') > -1) initProperty(target, entityName, Strings.substringBeforeLast(attr, ".")); beanUtils.copyProperty(target, attr, value); return true; } catch (Exception e) { logger.warn( "copy property failure:[class:" + entityName + " attr:" + attr + " value:" + value + "]:", e); return false; } }
@Override public WebappService clone() { try { return (WebappService) BeanUtilsBean.getInstance().cloneBean(this); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InstantiationException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw new RuntimeException(e); } catch (NoSuchMethodException e) { throw new RuntimeException(e); } }
/** * 设置系统设置 * * @param setting 系统设置 */ public static void set(Setting setting) { try { File shopxxXmlFile = new ClassPathResource(CommonAttributes.SHOPXX_XML_PATH).getFile(); Document document = new SAXReader().read(shopxxXmlFile); List<Element> elements = document.selectNodes("/shopxx/setting"); for (Element element : elements) { try { String name = element.attributeValue("name"); String value = beanUtils.getProperty(setting, name); Attribute attribute = element.attribute("value"); attribute.setValue(value); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } } FileOutputStream fileOutputStream = null; XMLWriter xmlWriter = null; try { OutputFormat outputFormat = OutputFormat.createPrettyPrint(); outputFormat.setEncoding("UTF-8"); outputFormat.setIndent(true); outputFormat.setIndent(" "); outputFormat.setNewlines(true); fileOutputStream = new FileOutputStream(shopxxXmlFile); xmlWriter = new XMLWriter(fileOutputStream, outputFormat); xmlWriter.write(document); } catch (Exception e) { e.printStackTrace(); } finally { if (xmlWriter != null) { try { xmlWriter.close(); } catch (IOException e) { } } IOUtils.closeQuietly(fileOutputStream); } Ehcache cache = cacheManager.getEhcache(Setting.CACHE_NAME); cache.put(new net.sf.ehcache.Element(Setting.CACHE_KEY, setting)); } catch (Exception e) { e.printStackTrace(); } }
private void setValue(final String attr, final Object value, final Object target) { try { beanUtils.copyProperty(target, attr, value); } catch (Exception e) { logger.error( "copy property failure:[class:" + target.getClass().getName() + " attr:" + attr + " value:" + value + "]:", e); } }
// to be used in DAOImpl.update only public static void copySimpleProperties(ModelObject dest, ModelObject orig) { try { PropertyDescriptor srcDescriptors[] = BeanUtilsBean.getInstance().getPropertyUtils().getPropertyDescriptors(dest); for (PropertyDescriptor pd : srcDescriptors) { String name = pd.getName(); if ("class".equals(name)) { continue; } if ("id".equals(name)) { // TODO hardcoded. for update, never change Id field continue; } Class type = pd.getPropertyType(); debug("copySimpleProperties-- name=" + name + ", type=" + type); if (Collection.class.isAssignableFrom(type)) { Field field = dest.getClass().getDeclaredField(name); if (MyPropertyUtil.isFieldCollectionOfModel(field)) { // ingore collection of Model continue; } else { PropertyUtils.setProperty(dest, name, PropertyUtils.getProperty(orig, name)); } } else if (ModelObject.class.isAssignableFrom(type)) { // we do not support editing of associated object at this point // nor pointing to another associated object continue; } else { PropertyUtils.setProperty(dest, name, PropertyUtils.getProperty(orig, name)); } } } catch (Exception e) { throw new RuntimeException(e); } }
/** * This takes into account objects that breaks the JavaBean convention and have as getter for * Boolean objects an "isXXX" method. * * @param dest * @param orig */ public static void copyProperties(Object dest, Object orig) { try { if (orig != null && dest != null) { BeanUtils.copyProperties(dest, orig); PropertyUtils putils = new PropertyUtils(); PropertyDescriptor origDescriptors[] = putils.getPropertyDescriptors(orig); for (int i = 0; i < origDescriptors.length; i++) { String name = origDescriptors[i].getName(); if ("class".equals(name)) { continue; // No point in trying to set an object's class } Class propertyType = origDescriptors[i].getPropertyType(); if (!Boolean.class.equals(propertyType) && !(Boolean.class.equals(propertyType))) continue; if (!putils.isReadable(orig, name)) { // because of bad convention Method m = orig.getClass() .getMethod("is" + name.substring(0, 1).toUpperCase() + name.substring(1), null); Object value = m.invoke(orig, null); if (m != null && putils.isWriteable(dest, name)) { BeanUtilsBean.getInstance().copyProperty(dest, name, value); } } } } } catch (Exception e) { throw new DJException( "Could not copy properties for shared object: " + orig + ", message: " + e.getMessage(), e); } }
// 검색조건을 세션에 저장한다. public void sessionToSearchParam(HttpServletRequest request, Object newCommand) throws Exception { // 하나의 화면에서 여러게 리스트를 사용할경우 를 위해서 커맨드 객체를 맵에 저장한다. Map<String, Object> commandMap = (Map<String, Object>) request.getSession().getAttribute("SEARCH_CMD_MAP"); if (commandMap == null) { commandMap = new HashMap<String, Object>(); } String newCommandName = newCommand.getClass().getName(); Object oldCommand = commandMap.get(newCommandName); // newCommandName 이름으로된 command 객체가 session 영역에서 참조한다. // org.apache.commons.beanutils.ConversionException: No value specified for 'Date' BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0); // 리스트 페이지에서 검색 if ("".equals(request.getParameter("searching"))) { commandMap.put(newCommandName, newCommand); request.getSession().setAttribute("SEARCH_CMD_MAP", commandMap); } else if (request.getParameter("pageIndex") != null) { // 리스트페이지에서 페이징 버튼 클릭시. if (commandMap.containsKey( newCommandName)) { // new 이름과 old 이름이 같으면(new 객체이름으로 등록된 command 객체가 있다면.) String ignorePropertyValue = BeanUtils.getProperty(newCommand, "pageIndex"); BeanUtils.copyProperties(newCommand, oldCommand); BeanUtils.setProperty(newCommand, "pageIndex", ignorePropertyValue); } commandMap.put(newCommandName, newCommand); request.getSession().setAttribute("SEARCH_CMD_MAP", commandMap); } else if ("".equals(request.getParameter("searchUse")) || "".equals(request.getAttribute("searchUse"))) { // 읽기 화면이나 업데이트화면 에서 리스트페이지 이동 버튼 클릭시 if (commandMap.containsKey(newCommandName)) { BeanUtils.copyProperties(newCommand, oldCommand); } } else { request.getSession().removeAttribute("SEARCH_CMD_MAP"); } }
/** * @param clazz * @param propertyName * @return */ public static PropertyDescriptor[] getPropertyDescriptors(Class clazz) { return BeanUtilsBean.getInstance().getPropertyUtils().getPropertyDescriptors(clazz); }
/** * @param clazz * @param propertyName * @return */ public static PropertyDescriptor[] getPropertyDescriptors(Object bean) { return BeanUtilsBean.getInstance().getPropertyUtils().getPropertyDescriptors(bean.getClass()); }