/** * map to bean * 转换过程中,由于属性的类型不同,需要分别转换。 * java 反射机制,转换过程中属性的类型默认都是 String 类型,否则会抛出异常,而 BeanUtils 项目,做了大量转换工作,比 java 反射机制好用 * BeanUtils 的 populate 方法,对 Date 属性转换,支持不好,需要自己编写转换器 * * @param map 待转换的 map * @param bean 满足 bean 格式,且需要有无参的构造方法; bean 属性的名字应该和 map 的 key 相同 * @throws IllegalAccessException * @throws InvocationTargetException */ private static void mapToBean(Map<String, Object> map, Object bean) throws IllegalAccessException, InvocationTargetException { //注册几个转换器 ConvertUtils.register(new SqlDateConverter(null), java.sql.Date.class); ConvertUtils.register(new SqlTimestampConverter(null), java.sql.Timestamp.class); //注册一个类型转换器 解决 common-beanutils 为 Date 类型赋值问题 ConvertUtils.register(new Converter() { // @Override public Object convert(Class type, Object value) { // type : 目前所遇到的数据类型。 value :目前参数的值。 // System.out.println(String.format("value = %s", value)); if (value == null || value.equals("") || value.equals("null")) return null; Date date = null; try { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); date = dateFormat.parse((String) value); } catch (Exception e) { e.printStackTrace(); } return date; } }, Date.class); BeanUtils.populate(bean, map); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{ User user = new User(); HashMap map = new HashMap(); Enumeration names = request.getParameterNames(); while (names.hasMoreElements()) { String name = (String) names.nextElement(); map.put(name, request.getParameterValues(name)); } try{ BeanUtils.populate(user, map); //BAD BeanUtilsBean beanUtl = BeanUtilsBean.getInstance(); beanUtl.populate(user, map); //BAD }catch(Exception e){ e.printStackTrace(); } }
private String getProtectedOxTrustApplicationConfiguration(ApplicationConfiguration oxTrustApplicationConfiguration) { try { ApplicationConfiguration resultOxTrustApplicationConfiguration = (ApplicationConfiguration) BeanUtils.cloneBean(oxTrustApplicationConfiguration); resultOxTrustApplicationConfiguration.setSvnConfigurationStorePassword(HIDDEN_PASSWORD_TEXT); resultOxTrustApplicationConfiguration.setKeystorePassword(HIDDEN_PASSWORD_TEXT); resultOxTrustApplicationConfiguration.setIdpSecurityKeyPassword(HIDDEN_PASSWORD_TEXT); resultOxTrustApplicationConfiguration.setIdpBindPassword(HIDDEN_PASSWORD_TEXT); resultOxTrustApplicationConfiguration.setMysqlPassword(HIDDEN_PASSWORD_TEXT); resultOxTrustApplicationConfiguration.setCaCertsPassphrase(HIDDEN_PASSWORD_TEXT); resultOxTrustApplicationConfiguration.setOxAuthClientPassword(HIDDEN_PASSWORD_TEXT); return jsonService.objectToJson(resultOxTrustApplicationConfiguration); } catch (Exception ex) { log.error("Failed to prepare JSON from ApplicationConfiguration: '{0}'", ex, oxTrustApplicationConfiguration); } return null; }
@Override public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException { User user = this.userService.findByName(name); TzUserDetails userDetails = new TzUserDetails(); if(user == null){ throw new UsernameNotFoundException("用户不存在"); } try { BeanUtils.copyProperties(userDetails,user); } catch (Exception e) { e.printStackTrace(); } logger.info("---->身份验证:"+userDetails.getUsername()+":"+userDetails.getPassword()); return userDetails; }
public static List<ShopProductDto> convert(List<ShopProduct> products,ObjectMapper objectMapper) throws InvocationTargetException, IllegalAccessException { if (products == null) { return null; } List<ShopProductDto> productDtos = new ArrayList(); for (int i = 0; i < products.size(); i++) { ShopProductDto tmp = new ShopProductDto(); BeanUtils.copyProperties(tmp, products.get(i)); try { /*处理图片信息转换*/ tmp.setImgs(tmp.parseImageList(objectMapper)) ; /*处理基础信息转换*/ tmp.parseBaseProperty(objectMapper); /*其他转换操作*/ } catch (IOException e) { e.printStackTrace(); } productDtos.add(tmp); } return productDtos; }
@SuppressWarnings("unchecked") public <T extends IEntity> T createProxyEntity(T entity) throws Exception { EntityProxy entityProxy = createProxy(entity); if (entityProxy != null) { EntityProxyWrapper entityProxyWrapper = new EntityProxyWrapper(entityProxy); AbstractEntity proxyEntity = createProxyEntity(entityProxy); if(proxyEntity!=null) { // 注入对象 数值 BeanUtils.copyProperties(proxyEntity, entity); entityProxy.setCollectFlag(true); if(entityProxyWrapper != null) { proxyEntity.setEntityProxyWrapper(entityProxyWrapper); return (T) proxyEntity; } } } return null; }
/** * * @param retval * @param key * @param value * @throws IllegalAccessException * @throws InvocationTargetException */ private void setProperty(T retval, String key, Object value) throws IllegalAccessException, InvocationTargetException { String property = key2property(key); for (final Field f : this.type.getDeclaredFields()) { final SerializedName annotation = f.getAnnotation(SerializedName.class); if (annotation != null && property.equalsIgnoreCase(annotation.value())) { property = f.getName(); break; } } if (propertyExists(retval, property)) { BeanUtils.setProperty(retval, property, value); } else { LOG.warn(retval.getClass() + " does not support public setter for existing property [" + property + "]"); } }
/** * Checks if the Property Values of the item are valid for the Request. * * @param item * @throws AirtableException * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */ private void checkProperties(T item) throws AirtableException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (propertyExists(item, FIELD_ID) || propertyExists(item, FIELD_CREATED_TIME)) { Field[] attributes = item.getClass().getDeclaredFields(); for (Field attribute : attributes) { String attrName = attribute.getName(); if (FIELD_ID.equals(attrName) || FIELD_CREATED_TIME.equals(attrName)) { if (BeanUtils.getProperty(item, attribute.getName()) != null) { throw new AirtableException("Property " + attrName + " should be null!"); } } else if ("photos".equals(attrName)) { List<Attachment> obj = (List<Attachment>) BeanUtilsBean.getInstance().getPropertyUtils().getProperty(item, "photos"); checkPropertiesOfAttachement(obj); } } } }
/** * Check properties of Attachement objects. * * @param attachements * @throws AirtableException * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */ private void checkPropertiesOfAttachement(List<Attachment> attachements) throws AirtableException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (attachements != null) { for (int i = 0; i < attachements.size(); i++) { if (propertyExists(attachements.get(i), FIELD_ID) || propertyExists(attachements.get(i), "size") || propertyExists(attachements.get(i), "type") || propertyExists(attachements.get(i), "filename")) { final Field[] attributesPhotos = attachements.getClass().getDeclaredFields(); for (Field attributePhoto : attributesPhotos) { final String namePhotoAttribute = attributePhoto.getName(); if (FIELD_ID.equals(namePhotoAttribute) || "size".equals(namePhotoAttribute) || "type".equals(namePhotoAttribute) || "filename".equals(namePhotoAttribute)) { if (BeanUtils.getProperty(attachements.get(i), namePhotoAttribute) != null) { throw new AirtableException("Property " + namePhotoAttribute + " should be null!"); } } } } } } }
/********************************** get *************************************/ @Override public <T> T _get(Class<T> clazz, Long pv) throws Exception { Map<String, Object> param = new HashMap<>(); String tableName = GeneralMapperReflectUtil.getTableName(clazz); String primaryKey = GeneralMapperReflectUtil.getPrimaryKey(clazz); List<String> queryColumn = GeneralMapperReflectUtil.getAllColumns(clazz, false); param.put("_table_", tableName); param.put("_pk_", primaryKey); param.put("_pv_", pv); param.put("_query_column_", queryColumn); Map map = sqlSession.selectOne(Crudable.GET, param); T t = clazz.newInstance(); BeanUtils.populate(t, map); return t; }
public static void setProperties(Object obj, Map map){ Field[] fields = obj.getClass().getDeclaredFields(); for(Field field : fields) { Column column = field.getAnnotation(Column.class); String dbColumnname = null; if ("".equals(column.name())) dbColumnname = field.getName(); else dbColumnname = column.name(); try { Object value = map.get(dbColumnname); if (value != null) { BeanUtils.setProperty(obj, field.getName(), value); } } catch (Exception e) { log.catching(e); } } }
protected Map getConditions(Object param) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { // 静态条件部分 Map props = BeanUtils.describe(param); // new 动态条件部分 add by hekun if (param instanceof DBQueryParam) { DBQueryParam listVO = (DBQueryParam) param; Map queryConditions = listVO.getQueryConditions(); if (queryConditions != null && queryConditions.size() > 0) { // 将静态条件加入动态条件中,重复的动态条件及其值将被覆盖。 for (Iterator keys = props.keySet().iterator(); keys.hasNext(); ) { String key = (String) keys.next(); Object value = props.get(key); if (key.startsWith("_") && value != null) queryConditions.put(key, value); } props = queryConditions; } } return props; }
protected List getOrderedKeyset(Set keys, Object param) throws Exception { List orderedKeyset = new ArrayList(); if (keys.size() > 0) { String firstitems = BeanUtils.getProperty(param, "_firstitems"); String firstitemname = null; if (firstitems != null) { for (StringTokenizer st = new StringTokenizer(firstitems, ","); st .hasMoreTokens(); ) { firstitemname = st.nextToken(); if (keys.contains(firstitemname)) { orderedKeyset.add(firstitemname); } } } for (Iterator it = keys.iterator(); it.hasNext(); ) { String key = (String) it.next(); if (!orderedKeyset.contains(key)) orderedKeyset.add(key); } } return orderedKeyset; }
/** * Edits specified LTI tool consumer */ public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { initServices(); DynaActionForm ltiConsumerForm = (DynaActionForm) form; Integer sid = WebUtil.readIntParam(request, "sid", true); // editing a tool consumer if (sid != null) { ExtServer ltiConsumer = integrationService.getExtServer(sid); BeanUtils.copyProperties(ltiConsumerForm, ltiConsumer); String lessonFinishUrl = ltiConsumer.getLessonFinishUrl() == null ? "-" : ltiConsumer.getLessonFinishUrl(); request.setAttribute("lessonFinishUrl", lessonFinishUrl); // create a tool consumer } else { //do nothing } return mapping.findForward("ltiConsumer"); }
private String formattedPath(Collection<String> pathParams, RequestBean arguments, String path) { final String[] processedPath = {path}; pathParams.forEach(p -> { try { String value; if (isNested(p)) { value = getNestedValue(arguments, p); } else value = BeanUtils.getProperty(arguments, p); processedPath[0] = processedPath[0].replace("{" + p + "}", isNull(value) ? "" : value); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { processedPath[0] = processedPath[0].replace("{" + p + "}", p); } }); return processedPath[0]; }
@Override public boolean isValid(Object value, ConstraintValidatorContext context) { if (value == null) { return true; } try { final String fieldValue = BeanUtils.getProperty(value, fieldName); final String notNullFieldValue = BeanUtils.getProperty(value, notNullFieldName); if (StringUtils.equals(fieldValue, fieldSetValue) && StringUtils.isEmpty(notNullFieldValue)) { context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate(context.getDefaultConstraintMessageTemplate()) .addPropertyNode(notNullFieldName).addConstraintViolation(); return false; } } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new RuntimeException(e); } return true; }
/** * 类实现 Maps --> Bean * @param objClass * @param objMaps */ public static <T> List<T> map2BeanList(List<Map<String, Object>> objMaps, Class<T> objClass) { if (objMaps == null || objClass == null) { return Collections.emptyList(); } List<T> objList = new ArrayList<T>(); try { for(Map<String, Object> mapObj : objMaps) { T obj = objClass.newInstance(); BeanUtils.populate(obj, mapObj); objList.add(obj); } } catch (Exception e) { logger.error(e.getMessage()); } return objList; }
private static <T> T convertWithMethod(Row row, Class<T> clazz) throws IllegalAccessException, InstantiationException, ParseException, InvocationTargetException { Field[] fields = new Field[]{}; Class temp = clazz; while(temp != null){ fields = ArrayUtils.addAll(temp.getDeclaredFields(),fields); temp = temp.getSuperclass(); } Object object = clazz.newInstance(); for (Field field : fields) { ExcelCellField filedExcelAnnotation = getAnnotationCellFiled(field.getAnnotations()); if (filedExcelAnnotation == null) { continue; } Class<?> fieldType = field.getType(); Integer index = filedExcelAnnotation.index(); String propertyName = field.getName(); Object value = getValue(fieldType, row.getCell(index), filedExcelAnnotation); if (value != null) { BeanUtils.setProperty(object, propertyName, value); } } return (T) object; }
@PostMapping("/{id}/edit") public String edit(@PathVariable String id, @RequestParam(required = false) String title, @RequestParam(required = false) String body, @RequestParam(required = false) String tags, HttpServletRequest req) { Post showPost = pc.read(id); Profile authUser = utils.getAuthUser(req); if (!utils.canEdit(showPost, authUser) || showPost == null) { return "redirect:" + req.getRequestURI(); } Post beforeUpdate = null; try { beforeUpdate = (Post) BeanUtils.cloneBean(showPost); } catch (Exception ex) { logger.error(null, ex); } if (!StringUtils.isBlank(title) && title.length() > 10) { showPost.setTitle(title); } if (!StringUtils.isBlank(body)) { showPost.setBody(body); } if (!StringUtils.isBlank(tags) && showPost.isQuestion()) { showPost.setTags(Arrays.asList(StringUtils.split(tags, ","))); } //note: update only happens if something has changed if (!showPost.equals(beforeUpdate)) { showPost.setLasteditby(authUser.getId()); showPost.setLastedited(System.currentTimeMillis()); showPost.update(); utils.addBadgeOnceAndUpdate(authUser, Badge.EDITOR, true); } return "redirect:" + showPost.getPostLink(false, false); }
/** * 将所有记录包装成T类对象,并将所有T类对象放入一个数组中并返回,传入的T类的定义必须符合JavaBean规范, * 因为本函数是调用T类对象的setter器来给对象赋值的 * * @param clazz T类的类对象 * @param listProperties 所有记录 * @return 返回所有被实例化的对象的数组,若没有对象,返回一个空数组 * @throws InstantiationException * @throws IllegalAccessException * @throws InvocationTargetException */ private static <T> List<T> transformMapListToBeanList(Class<T> clazz, List<Map<String, Object>> listProperties) throws InstantiationException, IllegalAccessException, InvocationTargetException { // 存放被实例化的T类对象 T bean = null; // 存放所有被实例化的对象 List<T> list = new ArrayList<T>(); // 将实例化的对象放入List数组中 if (listProperties.size() != 0) { Iterator<Map<String, Object>> iter = listProperties.iterator(); while (iter.hasNext()) { // 实例化T类对象 bean = clazz.newInstance(); // 遍历每条记录的字段,并给T类实例化对象属性赋值 for (Map.Entry<String, Object> entry : iter.next().entrySet()) { BeanUtils.setProperty(bean, entry.getKey(), entry.getValue()); } // 将赋过值的T类对象放入数组中 list.add(bean); } } return list; }
/** * 插入表新列 * * @param dbInfoId * @param columnInfo * @throws Exception */ public void insertColumn(String dbInfoId, ColumnInfo columnInfo) throws Exception { com.bstek.bdf2.core.orm.jdbc.dialect.ColumnInfo dbColumnInfo = new com.bstek.bdf2.core.orm.jdbc.dialect.ColumnInfo(); BeanUtils.copyProperties(dbColumnInfo, columnInfo); String tableName = columnInfo.getTableName(); String columnName = columnInfo.getColumnName(); boolean isprimaryKey = columnInfo.isIsprimaryKey(); List<String> primaryKeys = findTablePrimaryKeys(dbInfoId, tableName); if (isprimaryKey) { primaryKeys.add(columnName); dbColumnInfo.setListPrimaryKey(primaryKeys); String pkName = this.findSqlServerPKIndex(dbInfoId, tableName); log.debug("pkName:" + pkName); if (StringUtils.hasText(pkName)) { dbColumnInfo.setPkName(pkName); } } IDialect dBDialect = getDBDialectByDbInfoId(dbInfoId); String sql = dBDialect.getNewColumnSql(dbColumnInfo); String[] sqls = sql.split(";"); this.updateSql(dbInfoId, sqls); }
protected void injectValue(Object bean, PropertyDescriptor pd) { Method writeMethod = pd.getWriteMethod(); Value valueAnnotate = writeMethod.getAnnotation(Value.class); if (valueAnnotate == null) { return; } String value = valueAnnotate.value(); if (value.startsWith("${") && value.endsWith("}")) { value = value.substring(2, value.length() - 1); value = getProperty(value); } try { BeanUtils.setProperty(bean, pd.getName(), value); } catch (Exception e) { throw new InjectBeanException("Could not inject value: " + writeMethod + "; nested exception is " + e, e); } }
private static void entity2Dto() { EUser u = new EUser(); u.setId(1l); u.setUsername("yoking"); u.setCreationDate(new Date(System.currentTimeMillis())); UserDTO user = new UserDTO(); ConvertUtils.register(new DateStringConverter(), String.class); try { BeanUtils.copyProperties(user, u); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } System.out.println(user); }
private static void dto2Entity() { UserDTO user = new UserDTO(); user.setId(1l); user.setUsername("joking"); user.setCreationDate("2016-04-20"); EUser u = new EUser(); ConvertUtils.register(new DateStringConverter(), Date.class); try { BeanUtils.copyProperties(u, user); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } System.out.println(u); }
public static BatteryInfoReq convert(String str) { if (StringUtils.isBlank(str)) { return null; } BatteryInfoReq req = new BatteryInfoReq(); String[] arr = StringUtils.split(str, "&"); for (int i = 0; i < arr.length; i++) { String[] pair = StringUtils.split(arr[i], "="); try { BeanUtils.setProperty(req, pair[0], pair[1]); } catch (Exception e) { logger.error(ExceptionUtils.getStackTrace(e)); } } return req; }
/*** * 将JSON文本反序列化为主从关系的实体 * @param 泛型T 代表主实体类型 * @param 泛型D 代表从实体类型 * @param jsonString JSON文本 * @param mainClass 主实体类型 * @param detailName 从实体类在主实体类中的属性名称 * @param detailClass 从实体类型 * @return */ public static <T, D> T toBean(String jsonString, Class<T> mainClass, String detailName, Class<D> detailClass) { JSONObject jsonObject = JSONObject.fromObject(jsonString); JSONArray jsonArray = (JSONArray) jsonObject.get(detailName); T mainEntity = JSONUtils.toBean(jsonObject, mainClass); List<D> detailList = JSONUtils.toList(jsonArray, detailClass); try { BeanUtils.setProperty(mainEntity, detailName, detailList); } catch (Exception ex) { throw new RuntimeException("主从关系JSON反序列化实体失败!"); } return mainEntity; }
/*** * 将JSON文本反序列化为主从关系的实体 * @param 泛型T 代表主实体类型 * @param 泛型D1 代表从实体类型 * @param 泛型D2 代表从实体类型 * @param jsonString JSON文本 * @param mainClass 主实体类型 * @param detailName1 从实体类在主实体类中的属性 * @param detailClass1 从实体类型 * @param detailName2 从实体类在主实体类中的属性 * @param detailClass2 从实体类型 * @return */ public static <T, D1, D2> T toBean(String jsonString, Class<T> mainClass, String detailName1, Class<D1> detailClass1, String detailName2, Class<D2> detailClass2) { JSONObject jsonObject = JSONObject.fromObject(jsonString); JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1); JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2); T mainEntity = JSONUtils.toBean(jsonObject, mainClass); List<D1> detailList1 = JSONUtils.toList(jsonArray1, detailClass1); List<D2> detailList2 = JSONUtils.toList(jsonArray2, detailClass2); try { BeanUtils.setProperty(mainEntity, detailName1, detailList1); BeanUtils.setProperty(mainEntity, detailName2, detailList2); } catch (Exception ex) { throw new RuntimeException("主从关系JSON反序列化实体失败!"); } return mainEntity; }
/*** * 将JSON文本反序列化为主从关系的实体 * @param 主实体类型 * @param jsonString JSON文本 * @param mainClass 主实体类型 * @param detailClass 存放了多个从实体在主实体中属性名称和类型 * @return */ @SuppressWarnings("rawtypes") public static <T> T toBean(String jsonString, Class<T> mainClass, HashMap<String, Class> detailClass) { JSONObject jsonObject = JSONObject.fromObject(jsonString); T mainEntity = JSONUtils.toBean(jsonObject, mainClass); for (Object key : detailClass.keySet()) { try { Class value = (Class) detailClass.get(key); BeanUtils.setProperty(mainEntity, key.toString(), value); } catch (Exception ex) { throw new RuntimeException("主从关系JSON反序列化实体失败!"); } } return mainEntity; }
public String toString() { try { StringBuffer sb = new StringBuffer( "{" ); Map properties = BeanUtils.describe( this ); for ( Iterator it = properties.keySet().iterator(); it.hasNext(); ) { Object key = it.next(); Object value = properties.get( key ); sb.append( key.toString() ).append( "=" ).append( value != null ? value.toString() : null ).append( it.hasNext() ? ", " : "") ; } sb.append( "}" ); return sb.toString(); } catch( Exception exc ) { exc.printStackTrace(); return super.toString(); } }
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String idString = request.getParameter("codigo"); idString = StringUtils.defaultString( idString, ( String ) request.getAttribute( "codigoCuaderno" )); if (idString == null || idString.length() == 0) { log.warn("El par�metre codigo �s null!!"); return mapping.findForward("fail"); } Long id = new Long(idString); CuadernoCargaForm cuadernoCargaForm = ( CuadernoCargaForm ) form; CuadernoCargaDelegate delegate = DelegateUtil.getCuadernoCargaDelegate(); CuadernoCarga cuadernoCarga = delegate.obtenerCuadernoCarga( id ); BeanUtils.copyProperties( cuadernoCargaForm, cuadernoCarga ); cuadernoCargaForm.setRawFechaCarga( StringUtil.fechaACadena( cuadernoCarga.getFechaCarga() ) ); request.setAttribute( "cuadernoCarga", cuadernoCarga ); Util.setDevelopperMode( request ); return mapping.findForward( "success" ); }
/** * @ejb.interface-method * @ejb.permission role-name="${role.auto}" * @ejb.permission role-name="${role.todos}" * @param tramitePersistente * @return */ public void backupTramitePersistente( TramitePersistente tramitePersistente ) { try { TramitePersistenteBackup result = new TramitePersistenteBackup(); BeanUtils.copyProperties( result, tramitePersistente ); Set setDocumentos = tramitePersistente.getDocumentos(); for ( Iterator it = setDocumentos.iterator(); it.hasNext(); ) { DocumentoPersistente documento = ( DocumentoPersistente ) it.next(); DocumentoPersistenteBackup backup = new DocumentoPersistenteBackup(); BeanUtils.copyProperties( backup, documento ); result.addDocumentoBackup( backup ); } grabarBackupTramitePersistente ( result ); } catch( Exception exc ) { throw new EJBException( exc ); } }
/** * Devuelve notificacion con informacion exclusiva de aviso * @param notificacionTelematica * @return */ private NotificacionTelematica notificacionSinAbrir(NotificacionTelematica notificacionTelematica) throws Exception { NotificacionTelematica not = new NotificacionTelematica(); BeanUtils.copyProperties(not,notificacionTelematica); // Eliminamos referencia rds a oficio not.setCodigoRdsOficio(0); not.setClaveRdsOficio(null); // Eliminamos documentos not.getDocumentos().clear(); // Eliminamos tramite de subsanacion not.setTramiteSubsanacionDescripcion(null); not.setTramiteSubsanacionIdentificador(null); not.setTramiteSubsanacionVersion(null); not.setTramiteSubsanacionParametros(null); return not; }
@Test public void testMap2Bean() throws Exception { Map<String, Object> map = Maps.newHashMap(); map.put("Username", "jonnyliu"); map.put("Age", 39); User user = new User(); Map map1 = Maps.newHashMap(); map.forEach((x, y) -> { char[] charArray = x.toCharArray(); charArray[0] = Character.toLowerCase(charArray[0]); map1.put(new String(charArray), y); }); BeanUtils.populate(user, map1); System.out.println(user); }
private String getValue(String key, Optional<Object> value) { return value.map(o -> { if (!hasSafeToString(o)) { try { Map<String, String> beanDescription = BeanUtils.describe(value); if (!beanDescription.isEmpty()) { return beanDescription.toString(); } } catch (Exception e) { LOGGER.error("BeanUtils Exception describing attribute {}", key, e); } } return o.toString(); }).orElse("<null>"); }
@Before("aopPoint()") public Object doRoute(JoinPoint jp) throws Throwable { boolean result = true; Method method = this.getMethod(jp); DbRoute dbRoute = method.getAnnotation(DbRoute.class); String routeField = dbRoute.field(); // userId Object[] args = jp.getArgs(); if(args != null && args.length > 0) { for(int i = 0; i < args.length; ++i) { String routeFieldValue = BeanUtils.getProperty(args[i], routeField); if(StringUtils.isNotEmpty(routeFieldValue)) { if("userId".equals(routeField)) { this.dbRouter.route(routeField); } break; } } } return Boolean.valueOf(result); }
public void setField(NamedNodeMap namedNodeMap, String fieldName) { Attr attr = (Attr) namedNodeMap.getNamedItem(fieldName); if (attr != null) { boolean isDefaultValue = !attr.getSpecified(); boolean success = setDefaultFlag(fieldName, isDefaultValue); if (success) { // Json.print(baseInfo, "baseInfo"); Object value = this.toBaseInfoValue(fieldName, attr.getNodeValue()); try { BeanUtils.setProperty(baseInfo, fieldName, value); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } } } }
/*** * 将JSON文本反序列化为主从关系的实体 * * @param <T>泛型T 代表主实体类型 * @param <D1>泛型D1 代表从实体类型 * @param <D2>泛型D2 代表从实体类型 * @param jsonString * JSON文本 * @param mainClass * 主实体类型 * @param detailName1 * 从实体类在主实体类中的属性 * @param detailClass1 * 从实体类型 * @param detailName2 * 从实体类在主实体类中的属性 * @param detailClass2 * 从实体类型 * @return */ public static <T, D1, D2> T toBean(String jsonString, Class<T> mainClass, String detailName1, Class<D1> detailClass1, String detailName2, Class<D2> detailClass2) { JSONObject jsonObject = JSONObject.fromObject(jsonString); JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1); JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2); T mainEntity = JSONHelper.toBean(jsonObject, mainClass); List<D1> detailList1 = JSONHelper.toList(jsonArray1, detailClass1); List<D2> detailList2 = JSONHelper.toList(jsonArray2, detailClass2); try { BeanUtils.setProperty(mainEntity, detailName1, detailList1); BeanUtils.setProperty(mainEntity, detailName2, detailList2); } catch (Exception ex) { throw new RuntimeException("主从关系JSON反序列化实体失败!"); } return mainEntity; }
/*** * 将JSON文本反序列化为主从关系的实体 * * @param <T>泛型T 代表主实体类型 * @param <D1>泛型D1 代表从实体类型 * @param <D2>泛型D2 代表从实体类型 * @param jsonString * JSON文本 * @param mainClass * 主实体类型 * @param detailName1 * 从实体类在主实体类中的属性 * @param detailClass1 * 从实体类型 * @param detailName2 * 从实体类在主实体类中的属性 * @param detailClass2 * 从实体类型 * @param detailName3 * 从实体类在主实体类中的属性 * @param detailClass3 * 从实体类型 * @return */ public static <T, D1, D2, D3> T toBean(String jsonString, Class<T> mainClass, String detailName1, Class<D1> detailClass1, String detailName2, Class<D2> detailClass2, String detailName3, Class<D3> detailClass3) { JSONObject jsonObject = JSONObject.fromObject(jsonString); JSONArray jsonArray1 = (JSONArray) jsonObject.get(detailName1); JSONArray jsonArray2 = (JSONArray) jsonObject.get(detailName2); JSONArray jsonArray3 = (JSONArray) jsonObject.get(detailName3); T mainEntity = JSONHelper.toBean(jsonObject, mainClass); List<D1> detailList1 = JSONHelper.toList(jsonArray1, detailClass1); List<D2> detailList2 = JSONHelper.toList(jsonArray2, detailClass2); List<D3> detailList3 = JSONHelper.toList(jsonArray3, detailClass3); try { BeanUtils.setProperty(mainEntity, detailName1, detailList1); BeanUtils.setProperty(mainEntity, detailName2, detailList2); BeanUtils.setProperty(mainEntity, detailName3, detailList3); } catch (Exception ex) { throw new RuntimeException("主从关系JSON反序列化实体失败!"); } return mainEntity; }
@Override public String getFileName(FileStatus.FileTrackingStatus status) { StringBuilder buff = new StringBuilder(); try { for (String key : keyProperties) { buff.append(BeanUtils.getSimpleProperty(status, key)); } } catch (Throwable t) { RuntimeException rte = new RuntimeException(t.toString(), t); rte.setStackTrace(t.getStackTrace()); throw rte; } buff.append("."); buff.append(extractDateTime(status.getFileName())); return buff.toString(); }