Java 类org.apache.commons.beanutils.BeanUtilsBean 实例源码

项目:Android_Code_Arbiter    文件:BeanInjection.java   
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();
    }
}
项目:airtable.java    文件:Table.java   
/**
 * 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);
            }
        }
    }

}
项目:hsweb-framework    文件:FieldFilterDataAccessHandler.java   
/**
 * @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;
}
项目:AwesomeJavaLibraryExamples    文件:CopyFromDifferentObjects.java   
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);
}
项目:common    文件:BeanToBean.java   
/**
 * 把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);
            }
        }
    }
}
项目:StitchRTSP    文件:Input.java   
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;
}
项目:omr    文件:FreemarkerTemplateRules.java   
/**
 * 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;
}
项目:omr    文件:FreemarkerTemplateRules.java   
/**
 * 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;
}
项目:omr    文件:FreemarkerTemplateRules.java   
/**
 * 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;
}
项目:omr    文件:FreemarkerTemplateRules.java   
/**
 * 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;
}
项目:omr    文件:FreemarkerTemplateRules.java   
/**
 * 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;
}
项目:omr    文件:FreemarkerTemplateRules.java   
/**
 * 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;
}
项目:omr    文件:FreemarkerTemplateRules.java   
/**
 * 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;
}
项目:omr    文件:FreemarkerTemplateRules.java   
/**
 * 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;
}
项目:omr    文件:FreemarkerTemplateRules.java   
/**
 * 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;
}
项目:flora-on-server    文件:BeanUtils.java   
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;
}
项目:flora-on-server    文件:BeanUtils.java   
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;
    }
项目:flora-on-server    文件:BeanUtils.java   
/**
 * 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;
}
项目:artifactory    文件:ArtifactoryRestServlet.java   
@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);
}
项目:activemq-artemis    文件:ConnectionFactoryURITest.java   
@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);
}
项目:activemq-artemis    文件:ConnectionFactoryURITest.java   
@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);
}
项目:activemq-artemis    文件:ConnectionFactoryURITest.java   
@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);
}
项目:oscar-old    文件:SunnyBrookImportDemoUtil.java   
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);
}
项目:red5-io    文件:Input.java   
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;
}
项目:red5-mobileconsole    文件:Input.java   
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;
}
项目:airtable.java    文件:Table.java   
/**
 *
 * 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;
}
项目:delivery-sdk-java    文件:StronglyTypedContentItemConverter.java   
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;

}
项目:bootstrap    文件:CsvBeanWriter.java   
/**
 * 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));
    }
}
项目:bootstrap    文件:SystemEntitiesTest.java   
/**
 * 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();
}
项目:jk-util    文件:JKObjectUtil.java   
/**
 * 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);
    }
}
项目:hsweb-framework    文件:JpaAnnotationParser.java   
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;
}
项目:hsweb-framework    文件:FieldFilterDataAccessHandler.java   
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) {

        }
    }
}
项目:hsweb-framework    文件:FieldScopeDataAccessHandler.java   
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;

}
项目:hsweb-framework    文件:AbstractSqlTableMetaDataParser.java   
@Override
public void wrapper(ColumnMetadata instance, int index, String attr, Object value) {
    try {
        BeanUtilsBean.getInstance().setProperty(instance, attr, value);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
项目:shiro-demo    文件:PasswordTest.java   
@Test
public void testHashedCredentialsMatcherWithJdbcRealm(){

    BeanUtilsBean.getInstance().getConvertUtils().register(new EnumConverter(), JdbcRealm.SaltStyle.class);
    //使用testGeneratePassword生成的散列密码
    login("classpath:shiro-jdbc-hashedCredentialsMatcher.ini", "liu", "123");
}
项目:telco-anomaly-detection-spark    文件:CDR.java   
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;
}
项目:venus    文件:CommonsBeanUtilConverter.java   
@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);
    }
}
项目:checkstyle-backport-jre6    文件:AutomaticBean.java   
/**
 * 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());
}
项目:katharsis-framework    文件:MetaAttribute.java   
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);
    }
}
项目:katharsis-framework    文件:MetaAttribute.java   
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);
    }
}