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(); } }
/** * 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); } } } }
/** * @param accesses 不可操作的字段 * @param params 参数上下文 * @return true * @see BeanUtilsBean * @see org.apache.commons.beanutils.PropertyUtilsBean */ protected boolean doUpdateAccess(FieldFilterDataAccessConfig accesses, AuthorizingContext params) { Object supportParam = params.getParamContext().getParams().values().stream() .filter(param -> (param instanceof Entity) || (param instanceof Model) || (param instanceof Map)) .findAny() .orElse(null); if (null != supportParam) { for (String field : accesses.getFields()) { try { //设置值为null,跳过修改 BeanUtilsBean.getInstance() .getPropertyUtils() .setProperty(supportParam, field, null); } catch (Exception e) { logger.warn("can't set {} null", field, e); } } } else { logger.warn("doUpdateAccess skip ,because can not found any support entity in param!"); } return true; }
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException { BeanUtilsBean utilsBean = BeanUtilsBean2.getInstance(); utilsBean.getConvertUtils().register(false, false, 0); BeanOne one = new BeanOne(); one.setPropertyOne("One"); one.setPropertyTwo("Two"); one.setPropertyThree(3L); one.setPropertyFour(4); //this is a string in BeanTwo BeanTwo two = new BeanTwo(); utilsBean.copyProperties(two, one); BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0); System.out.println(two); }
/** * 把srcObj的值拷贝到destObj * * @param obj * @param obj1 * @throws Exception */ public void BTB(Object srcBean, Object destBean) { BeanUtilsBean beanUtils = new BeanUtilsBean(); PropertyDescriptor[] origDescriptors = beanUtils.getPropertyUtils().getPropertyDescriptors(srcBean); for (int i = 0; i < origDescriptors.length; i++) { String name = origDescriptors[i].getName(); if ("class".equals(name)) { continue; } if (beanUtils.getPropertyUtils().isReadable(srcBean, name) && beanUtils.getPropertyUtils().isWriteable(srcBean, name)) { try { Object value = beanUtils.getPropertyUtils().getSimpleProperty(srcBean, name); if (value != null) { beanUtils.copyProperty(destBean, name, value); } } catch (Exception e) { logger.error("BTB():error:e:"+e.getMessage(),e); } } } }
protected Type getPropertyType(Object instance, String propertyName) { try { if (instance != null) { Field field = instance.getClass().getField(propertyName); return field.getGenericType(); } else { // instance is null for anonymous class, use default type } } catch (NoSuchFieldException e1) { try { BeanUtilsBean beanUtilsBean = BeanUtilsBean.getInstance(); PropertyUtilsBean propertyUtils = beanUtilsBean.getPropertyUtils(); PropertyDescriptor propertyDescriptor = propertyUtils.getPropertyDescriptor(instance, propertyName); return propertyDescriptor.getReadMethod().getGenericReturnType(); } catch (Exception e2) { // nothing } } catch (Exception e) { // ignore other exceptions } // return Object class type by default return Object.class; }
/** * Verifica se as propriedades especificadas no map regexRules batem com as propriedades da JavaClass informada. * * @param javaClass * @return */ protected boolean isGenerateRegex(final JavaClass javaClass) { final Set<String> keys = this.regexRules.keySet(); // itera todas as chaves for (final String keyProp : keys) { String jcPropValue; try { jcPropValue = BeanUtilsBean.getInstance().getProperty(javaClass, keyProp); } catch (final Exception e) { // se a propriedade não existe sai do for break; } final String regexRule = this.regexRules.get(keyProp); // se o valor encontrado é diferente do valor esperado não roda do template if (jcPropValue != null && !jcPropValue.matches(regexRule)) { this.log.warn(FreemarkerTemplateRules.mf.format("rules.regexmap", this.template.getName(), javaClass.getName(), keyProp, jcPropValue, regexRule)); return false; } } return true; }
/** * Verifica se as propriedades especificadas no map regexRules batem com as propriedades da JavaClass informada. * * @param javaClass * @return */ protected boolean isGenerateRegex(final JavaClass javaClass) { final Set<String> keys = this.regexRules.keySet(); // itera todas as chaves for (final String keyProp : keys) { String jcPropValue; try { jcPropValue = BeanUtilsBean.getInstance().getProperty(javaClass, keyProp); } catch (final Exception e) { // se a propriedade n�o existe sai do for break; } final String regexRule = this.regexRules.get(keyProp); // se o valor encontrado � diferente do valor esperado n�o roda do template if (jcPropValue != null && !jcPropValue.matches(regexRule)) { this.log.warn(FreemarkerTemplateRules.mf.format("rules.regexmap", this.template.getName(), javaClass.getName(), keyProp, jcPropValue, regexRule)); return false; } } return true; }
/** * Verifica se as propriedades especificadas no map regexRules batem com as propriedades da JavaClass informada. * * @param javaClass * @return */ protected boolean isGenerateRegex(JavaClass javaClass) { Set<String> keys = this.regexRules.keySet(); // itera todas as chaves for (String keyProp : keys) { String jcPropValue; try { jcPropValue = BeanUtilsBean.getInstance().getProperty(javaClass, keyProp); } catch (Exception e) { // se a propriedade não existe sai do for break; } String regexRule = this.regexRules.get(keyProp); // se o valor encontrado é diferente do valor esperado não roda do template if (jcPropValue != null && !jcPropValue.matches(regexRule)) { log.warn(mf.format("rules.regexmap", this.template.getName(), javaClass.getName(), keyProp, jcPropValue, regexRule)); return false; } } return true; }
public static BeanUtilsBean createBeanUtilsNull() { BeanUtilsBean out = new BeanUtilsBean(); IntegerConverter iconverter = new IntegerConverter(null); LongConverter longConverter = new LongConverter(null); FloatConverter floatConverter = new FloatConverter(null); DoubleConverter doubleConverter = new DoubleConverter(null); NumericIntervalConverter numericIntervalConverter = new NumericIntervalConverter(null); AbundanceConverter abundanceConverter = new AbundanceConverter(null); //ArrayConverter arrayConverter = new ArrayConverter(String[].class, new StringConverter(null)); ArrayConverter arrayConverter = new ArrayConverter(Integer[].class, iconverter); out.getConvertUtils().register(iconverter, Integer.class); out.getConvertUtils().register(longConverter, Long.class); out.getConvertUtils().register(floatConverter, Float.class); out.getConvertUtils().register(doubleConverter, Double.class); out.getConvertUtils().register(arrayConverter, Integer[].class); out.getConvertUtils().register(numericIntervalConverter, NumericInterval.class); out.getConvertUtils().register(abundanceConverter, Abundance.class); //beanUtilsNull.getConvertUtils().register(arrayConverter, String[].class); return out; }
public static BeanUtilsBean createBeanUtilsNullSafeHTML() { BeanUtilsBean out = new BeanUtilsBean(); IntegerConverter iconverter = new IntegerConverter(null); LongConverter longConverter = new LongConverter(null); ArrayConverter arrayConverter = new ArrayConverter(Integer[].class, iconverter); SafeHTMLStringConverter stringConverter = new SafeHTMLStringConverter(null); NumericIntervalConverter numericIntervalConverter = new NumericIntervalConverter(null); AbundanceConverter abundanceConverter = new AbundanceConverter(null); out.getConvertUtils().register(iconverter, Integer.class); out.getConvertUtils().register(longConverter, Long.class); // beanUtilsNullSafeHTML.getConvertUtils().register(floatConverter, Float.class); // beanUtilsNullSafeHTML.getConvertUtils().register(doubleConverter, Double.class); out.getConvertUtils().register(arrayConverter, Integer[].class); out.getConvertUtils().register(stringConverter, SafeHTMLString.class); out.getConvertUtils().register(numericIntervalConverter, NumericInterval.class); out.getConvertUtils().register(abundanceConverter, Abundance.class); return out; }
/** * Updates a oldBean with all non-null values in the newBean. * @param cls * @param ignoreProperties * @param oldBean * @param newBean * @param <T> * @return * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws FloraOnException * @throws InstantiationException */ public static <T extends DiffableBean> T updateBean(Class<T> cls, Collection<String> ignoreProperties, T oldBean, T newBean) throws IllegalAccessException , InvocationTargetException, NoSuchMethodException, FloraOnException, InstantiationException { BeanMap propertyMap = new BeanMap(oldBean); // we assume beans are the same class! so we take the first as a model PropertyUtilsBean propUtils = new PropertyUtilsBean(); BeanUtilsBean bub = createBeanUtilsNull(); T out = cls.newInstance(); for (Object propNameObject : propertyMap.keySet()) { String propertyName = (String) propNameObject; if(ignoreProperties != null && ignoreProperties.contains(propertyName)) continue; System.out.println("PROP: " + propertyName); Object newProperty; newProperty = propUtils.getProperty(newBean, propertyName); if(newProperty == null) bub.setProperty(out, propertyName, propUtils.getProperty(oldBean, propertyName)); else bub.setProperty(out, propertyName, newProperty); // TODO: nested beans } return out; }
@SuppressWarnings({"unchecked"}) @Override public void init(ServletConfig config) throws ServletException { this.config = config; BlockingQueue<Filter> waiters = (BlockingQueue<Filter>) config.getServletContext() .getAttribute(APPLICATION_CONTEXT_LOCK_KEY); if (waiters != null) { waiters.add(this); } else { //Servlet 2.5 lazy filter initing delayedInit(); } // register the bean utils converter to fail if encounters a type mismatch between the destination // and the original, see RTFACT-3610 BeanUtilsBean instance = BeanUtilsBean2.getInstance(); instance.getConvertUtils().register(true, false, 0); }
@Test public void testTCPURI() throws Exception { TransportConfiguration tc = new TransportConfiguration(NettyConnectorFactory.class.getName()); HashMap<String, Object> params = new HashMap<>(); params.put("host", "localhost1"); params.put("port", 61617); TransportConfiguration tc2 = new TransportConfiguration(NettyConnectorFactory.class.getName(), params); HashMap<String, Object> params2 = new HashMap<>(); params2.put("host", "localhost2"); params2.put("port", 61618); TransportConfiguration tc3 = new TransportConfiguration(NettyConnectorFactory.class.getName(), params2); ActiveMQConnectionFactory connectionFactoryWithHA = ActiveMQJMSClient.createConnectionFactoryWithHA(JMSFactoryType.CF, tc, tc2, tc3); URI tcp = parser.createSchema("tcp", connectionFactoryWithHA); ActiveMQConnectionFactory factory = parser.newObject(tcp, null); BeanUtilsBean bean = new BeanUtilsBean(); checkEquals(bean, connectionFactoryWithHA, factory); }
@Test public void testJGroupsFileURI() throws Exception { DiscoveryGroupConfiguration discoveryGroupConfiguration = new DiscoveryGroupConfiguration(); JGroupsFileBroadcastEndpointFactory endpointFactory = new JGroupsFileBroadcastEndpointFactory().setChannelName("channel-name").setFile("channel-file.xml"); discoveryGroupConfiguration.setName("foo").setRefreshTimeout(12345).setDiscoveryInitialWaitTimeout(5678).setBroadcastEndpointFactory(endpointFactory); ActiveMQConnectionFactory connectionFactoryWithHA = ActiveMQJMSClient.createConnectionFactoryWithHA(discoveryGroupConfiguration, JMSFactoryType.CF); URI tcp = parser.createSchema("jgroups", connectionFactoryWithHA); ActiveMQConnectionFactory factory = parser.newObject(tcp, null); DiscoveryGroupConfiguration dgc = factory.getDiscoveryGroupConfiguration(); Assert.assertNotNull(dgc); BroadcastEndpointFactory befc = dgc.getBroadcastEndpointFactory(); Assert.assertNotNull(befc); Assert.assertTrue(befc instanceof JGroupsFileBroadcastEndpointFactory); Assert.assertEquals(dgc.getName(), "foo"); Assert.assertEquals(dgc.getDiscoveryInitialWaitTimeout(), 5678); Assert.assertEquals(dgc.getRefreshTimeout(), 12345); JGroupsFileBroadcastEndpointFactory fileBroadcastEndpointFactory = (JGroupsFileBroadcastEndpointFactory) befc; Assert.assertEquals(fileBroadcastEndpointFactory.getFile(), "channel-file.xml"); Assert.assertEquals(fileBroadcastEndpointFactory.getChannelName(), "channel-name"); BeanUtilsBean bean = new BeanUtilsBean(); checkEquals(bean, connectionFactoryWithHA, factory); }
@Test public void testJGroupsPropertiesURI() throws Exception { DiscoveryGroupConfiguration discoveryGroupConfiguration = new DiscoveryGroupConfiguration(); JGroupsPropertiesBroadcastEndpointFactory endpointFactory = new JGroupsPropertiesBroadcastEndpointFactory().setChannelName("channel-name").setProperties("param=val,param2-val2"); discoveryGroupConfiguration.setName("foo").setRefreshTimeout(12345).setDiscoveryInitialWaitTimeout(5678).setBroadcastEndpointFactory(endpointFactory); ActiveMQConnectionFactory connectionFactoryWithHA = ActiveMQJMSClient.createConnectionFactoryWithHA(discoveryGroupConfiguration, JMSFactoryType.CF); URI tcp = parser.createSchema("jgroups", connectionFactoryWithHA); ActiveMQConnectionFactory factory = parser.newObject(tcp, null); DiscoveryGroupConfiguration dgc = factory.getDiscoveryGroupConfiguration(); Assert.assertNotNull(dgc); BroadcastEndpointFactory broadcastEndpointFactory = dgc.getBroadcastEndpointFactory(); Assert.assertNotNull(broadcastEndpointFactory); Assert.assertTrue(broadcastEndpointFactory instanceof JGroupsPropertiesBroadcastEndpointFactory); Assert.assertEquals(dgc.getName(), "foo"); Assert.assertEquals(dgc.getDiscoveryInitialWaitTimeout(), 5678); Assert.assertEquals(dgc.getRefreshTimeout(), 12345); JGroupsPropertiesBroadcastEndpointFactory propertiesBroadcastEndpointFactory = (JGroupsPropertiesBroadcastEndpointFactory) broadcastEndpointFactory; Assert.assertEquals(propertiesBroadcastEndpointFactory.getProperties(), "param=val,param2-val2"); Assert.assertEquals(propertiesBroadcastEndpointFactory.getChannelName(), "channel-name"); BeanUtilsBean bean = new BeanUtilsBean(); checkEquals(bean, connectionFactoryWithHA, factory); }
public void updateDemo(Demographic demoFromFile, Demographic demoFromDB) throws Exception { class NullAwareBeanUtilsBean extends BeanUtilsBean { @Override public void copyProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException { if(value==null || value.toString().trim().length()==0) return; super.copyProperty(bean, name, value); } } new NullAwareBeanUtilsBean().copyProperties(demoFromDB, demoFromFile); DemographicDao demographicDao = (DemographicDao) SpringUtils.getBean("demographicDao"); demographicDao.save(demoFromDB); }
/** * * Filter the Fields of the PostRecord Object. Id and created Time are set * to null so Object Mapper doesent convert them to JSON. * * @param item * @return * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException */ private T filterFields(T item) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { final Field[] attributes = item.getClass().getDeclaredFields(); for (Field attribute : attributes) { String attrName = attribute.getName(); if ((FIELD_ID.equals(attrName) || FIELD_CREATED_TIME.equals(attrName)) && (BeanUtils.getProperty(item, attrName) != null)) { BeanUtilsBean.getInstance().getPropertyUtils().setProperty(item, attrName, null); } } return item; }
private static Type getType(Object bean, Field field) { //Because of type erasure, we will find the setter method and get the generic types off it's arguments PropertyUtilsBean propertyUtils = BeanUtilsBean.getInstance().getPropertyUtils(); PropertyDescriptor propertyDescriptor = null; try { propertyDescriptor = propertyUtils.getPropertyDescriptor(bean, field.getName()); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { handleReflectionException(e); } if (propertyDescriptor == null) { //Likely no accessors logger.debug("Property descriptor for object {} with field {} is null", bean, field); return null; } Method writeMethod = propertyUtils.getWriteMethod(propertyDescriptor); if (writeMethod == null) { logger.debug("No write method for property {}", propertyDescriptor); return null; } Type[] actualTypeArguments = ((ParameterizedType) writeMethod.getGenericParameterTypes()[0]).getActualTypeArguments(); Type type = (Map.class.isAssignableFrom(field.getType())) ? actualTypeArguments[1] : actualTypeArguments[0]; logger.debug("Got type {} from object {}, field {}", type, bean, field); return type; }
/** * Write a field */ private void writeField(final Object o, final String header) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException, IOException { final String value = BeanUtilsBean.getInstance().getProperty(o, header); if (value != null) { writer.write(StringEscapeUtils.escapeCsv(value)); } }
/** * Test entity getter/setter and toString. */ private <T> void testEntity(final Class<T> clazz) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException { final T entity = clazz.newInstance(); if (entity instanceof Auditable) { @SuppressWarnings("unchecked") final Auditable<?, ?, Date> auditable = (Auditable<?, ?, Date>) entity; auditable.setLastModifiedDate(new Date()); auditable.setCreatedDate(new Date()); } BeanUtilsBean.getInstance().cloneBean(entity).toString(); }
/** * Populate. * * @param instance * the instance * @param values * the values */ public static void populate(Object instance, Map<String, Object> values) { try { BeanUtilsBean beanUtilBean = new BeanUtilsBean(); for (String key : values.keySet()) { Object value = values.get(key); beanUtilBean.setProperty(instance, key, value); } } catch (Exception e) { JKExceptionUtil.handle(e); } }
public static RDBTableMetaData parseMetaDataFromEntity(Class entityClass) { Table table = AnnotationUtils.findAnnotation(entityClass, Table.class); if (table == null) { return null; } RDBTableMetaData tableMetaData = new RDBTableMetaData(); tableMetaData.setName(table.name()); PropertyDescriptor[] descriptors = BeanUtilsBean.getInstance() .getPropertyUtils() .getPropertyDescriptors(entityClass); for (PropertyDescriptor descriptor : descriptors) { Column column = getAnnotation(entityClass, descriptor, Column.class); if (column == null) { continue; } RDBColumnMetaData columnMetaData = new RDBColumnMetaData(); columnMetaData.setName(column.name()); columnMetaData.setAlias(descriptor.getName()); columnMetaData.setLength(column.length()); columnMetaData.setPrecision(column.precision()); columnMetaData.setJavaType(descriptor.getPropertyType()); JDBCType type = jdbcTypeMapping.get(descriptor.getPropertyType()); if (type == null) { type = jdbcTypeConvert.stream() .map(func -> func.apply(entityClass, descriptor)) .filter(Objects::nonNull) .findFirst() .orElse(JDBCType.OTHER); } columnMetaData.setJdbcType(type); tableMetaData.addColumn(columnMetaData); } return tableMetaData; }
protected void setObjectPropertyNull(Object obj, Set<String> fields) { if (null == obj) { return; } for (String field : fields) { try { BeanUtilsBean.getInstance().getPropertyUtils().setProperty(obj, field, null); } catch (Exception ignore) { } } }
protected boolean propertyInScope(Object obj, String property, Set<Object> scope) { if (null == obj) { return false; } try { Object value = BeanUtilsBean.getInstance().getProperty(obj, property); if (null != value) { return scope.contains(value); } } catch (Exception ignore) { logger.warn("can not get property {} from {},{}", property, obj, ignore.getMessage()); } return true; }
@Override public void wrapper(ColumnMetadata instance, int index, String attr, Object value) { try { BeanUtilsBean.getInstance().setProperty(instance, attr, value); } catch (Exception e) { e.printStackTrace(); } }
@Test public void testHashedCredentialsMatcherWithJdbcRealm(){ BeanUtilsBean.getInstance().getConvertUtils().register(new EnumConverter(), JdbcRealm.SaltStyle.class); //使用testGeneratePassword生成的散列密码 login("classpath:shiro-jdbc-hashedCredentialsMatcher.ini", "liu", "123"); }
public static CDR stringToCDR(String jsonStr) { CDR cdr = new CDR(); try { Map<String, Object> jsonMap = new ObjectMapper().readValue(jsonStr, new TypeReference<Map<String, String>>(){}); jsonMap.put("state", State.valueOf((String) jsonMap.get("state"))); BeanUtilsBean.getInstance().getConvertUtils().register(false, false, 0); BeanUtils.populate(cdr, jsonMap); } catch (IllegalAccessException | InvocationTargetException | IOException e) { throw new IllegalArgumentException("Can not convert record document"); } return cdr; }
@SuppressWarnings("unchecked") @Override public Object convert(Object value, Type type) throws ConvertException { Object object = null; try { if (type instanceof Class) { Class clazz = (Class) type; if (value instanceof Map && !clazz.isPrimitive()) { object = new HashMap(); BeanUtils.populate(object, (Map) (value)); } return BeanUtilsBean.getInstance().getConvertUtils().convert(value, clazz); } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Class rawType = ((Class) parameterizedType.getRawType()); if (Map.class.isAssignableFrom(rawType)) { object = new HashMap(); } else if (List.class.isAssignableFrom(rawType)) { object = new LinkedList(); } else if (rawType.isAssignableFrom(value.getClass()) && rawType.isInterface()) { return value; } else { object = reflectionProvider.newInstance(rawType); } if (value instanceof Map) { BeanUtils.populate(object, (Map) (value)); } else { BeanUtils.copyProperties(object, value); } } return object; } catch (Exception e) { throw new ConvertException(value + " can not convert to " + type); } }
/** * Creates a BeanUtilsBean that is configured to use * type converters that throw a ConversionException * instead of using the default value when something * goes wrong. * * @return a configured BeanUtilsBean */ private static BeanUtilsBean createBeanUtilsBean() { final ConvertUtilsBean cub = new ConvertUtilsBean(); registerIntegralTypes(cub); registerCustomTypes(cub); return new BeanUtilsBean(cub, new PropertyUtilsBean()); }
public Object getValue(Object dataObject) { PropertyUtilsBean utils = BeanUtilsBean.getInstance().getPropertyUtils(); try { return utils.getNestedProperty(dataObject, getName()); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new IllegalStateException("cannot access field " + getName() + " for " + dataObject.getClass().getName(), e); } }
public void setValue(Object dataObject, Object value) { PropertyUtilsBean utils = BeanUtilsBean.getInstance().getPropertyUtils(); try { utils.setNestedProperty(dataObject, getName(), value); } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { throw new IllegalStateException("cannot access field " + getName() + " for " + dataObject.getClass().getName(), e); } }