Example usage for org.springframework.beans BeanWrapperImpl setPropertyValue

List of usage examples for org.springframework.beans BeanWrapperImpl setPropertyValue

Introduction

In this page you can find the example usage for org.springframework.beans BeanWrapperImpl setPropertyValue.

Prototype

@Override
    public void setPropertyValue(String propertyName, @Nullable Object value) throws BeansException 

Source Link

Usage

From source file:cn.guoyukun.spring.jpa.entity.search.utils.SearchableConvertUtils.java

private static Object getConvertedValue(final BeanWrapperImpl beanWrapper, final String searchProperty,
        final String entityProperty, final Object value) {

    Object newValue;/*from   w w  w .j  a  v a  2s  .  c o m*/
    try {

        beanWrapper.setPropertyValue(entityProperty, value);
        newValue = beanWrapper.getPropertyValue(entityProperty);
    } catch (InvalidPropertyException e) {
        throw new InvalidSearchPropertyException(searchProperty, entityProperty, e);
    } catch (Exception e) {
        throw new InvalidSearchValueException(searchProperty, entityProperty, value, e);
    }

    return newValue;
}

From source file:com.predic8.membrane.annot.bean.MCUtil.java

@SuppressWarnings("unchecked")
public static <T> T clone(T object, boolean deep) {
    try {/* w w w  .ja v  a2s . c  o m*/
        if (object == null)
            throw new InvalidParameterException("'object' must not be null.");

        Class<? extends Object> clazz = object.getClass();

        MCElement e = clazz.getAnnotation(MCElement.class);
        if (e == null)
            throw new IllegalArgumentException("'object' must be @MCElement-annotated.");

        BeanWrapperImpl dst = new BeanWrapperImpl(clazz);
        BeanWrapperImpl src = new BeanWrapperImpl(object);

        for (Method m : clazz.getMethods()) {
            if (!m.getName().startsWith("set"))
                continue;
            String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
            MCAttribute a = m.getAnnotation(MCAttribute.class);
            if (a != null) {
                dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
            }
            MCChildElement c = m.getAnnotation(MCChildElement.class);
            if (c != null) {
                if (deep) {
                    dst.setPropertyValue(propertyName, cloneInternal(src.getPropertyValue(propertyName), deep));
                } else {
                    dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
                }
            }
            MCOtherAttributes o = m.getAnnotation(MCOtherAttributes.class);
            if (o != null) {
                dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
            }
            MCTextContent t = m.getAnnotation(MCTextContent.class);
            if (t != null) {
                dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
            }
        }

        return (T) dst.getRootInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:kr.okplace.job.launch.DefaultJobLoader.java

public void setProperty(String path, String value) {
    int index = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(path);
    BeanWrapperImpl wrapper = createBeanWrapper(path, index);
    String key = path.substring(index + 1);
    wrapper.setPropertyValue(key, value);
}

From source file:com.emc.ecs.sync.service.VdcEditorTest.java

@Test
public void testBeanWrapperWithList() {
    EcsS3Source source = new EcsS3Source();
    BeanWrapperImpl wrapper = new BeanWrapperImpl(source);

    wrapper.registerCustomEditor(Vdc.class, new VdcEditor());

    wrapper.setPropertyValue("vdcs", Arrays.asList("foo(1.1.1.1,2.2.2.2)", "bar(3.3.3.3,4.4.4.4)"));

    Assert.assertEquals(2, source.getVdcs().size());
    Vdc foo = source.getVdcs().get(0);/*from w  w  w  .  j a v a  2  s. c  o m*/
    Assert.assertEquals("foo", foo.getName());
    Assert.assertEquals(2, foo.getHosts().size());
    Assert.assertEquals("1.1.1.1", foo.getHosts().get(0).getName());
    Assert.assertEquals("2.2.2.2", foo.getHosts().get(1).getName());
    Vdc bar = source.getVdcs().get(1);
    Assert.assertEquals("bar", bar.getName());
    Assert.assertEquals(2, bar.getHosts().size());
    Assert.assertEquals("3.3.3.3", bar.getHosts().get(0).getName());
    Assert.assertEquals("4.4.4.4", bar.getHosts().get(1).getName());
}

From source file:com.fmguler.ven.QueryMapper.java

protected void mapRecursively(ResultSet rs, Set columns, String tableName, Class objectClass, List parentList) {
    try {//from www .  j a v a  2 s.  c  om
        if (!columns.contains(tableName + "_id"))
            return; //this object does not exist in the columns
        Object id = rs.getObject(tableName + "_id");
        if (id == null)
            return; //this object exists in the columns but null, probably because of left join

        //create bean wrapper for the object class
        BeanWrapperImpl wr = new BeanWrapperImpl(objectClass); //already caches class introspection (CachedIntrospectionResults.forClass())
        wr.setPropertyValue("id", id); //set the id property
        Object object = wr.getWrappedInstance();
        boolean map = true;

        //check if this object exists in the parent list (since SQL joins are cartesian products, do not create new object if this row is just the same as previous)
        for (Iterator it = parentList.iterator(); it.hasNext();) {
            Object objectInList = (Object) it.next();
            if (objectIdEquals(objectInList, id)) {
                wr.setWrappedInstance(objectInList); //already exists in the list, use that instance
                map = false; // and do not map again
                break;
            }
        }
        if (map)
            parentList.add(object); //could not find in the parent list, add the new object

        PropertyDescriptor[] pdArr = wr.getPropertyDescriptors();
        for (int i = 0; i < pdArr.length; i++) {
            PropertyDescriptor pd = pdArr[i];
            Class fieldClass = pd.getPropertyType(); //field class
            String fieldName = Convert.toDB(pd.getName()); //field name
            Object fieldValue = wr.getPropertyValue(pd.getName());
            String columnName = tableName + "_" + fieldName;

            //database class (primitive property)
            if (map && dbClasses.contains(fieldClass)) {
                if (columns.contains(columnName)) {
                    if (debug)
                        System.out.println(">>field is found: " + columnName);
                    wr.setPropertyValue(pd.getName(), rs.getObject(columnName));
                } else {
                    if (debug)
                        System.out.println("--field not found: " + columnName);
                }
                continue; //if this is a primitive property, it cannot be an object or list
            }

            //many to one association (object property)
            if (fieldClass.getPackage() != null && domainPackages.contains(fieldClass.getPackage().getName())) {
                if (columns.contains(columnName + "_id")) {
                    if (debug)
                        System.out.println(">>object is found " + columnName);
                    List list = new ArrayList(1); //we know there will be single result
                    if (!map)
                        list.add(fieldValue); //otherwise we cannot catch one to many assc. (lists) of many to one (object) assc.
                    mapRecursively(rs, columns, columnName, fieldClass, list);
                    if (list.size() > 0)
                        wr.setPropertyValue(pd.getName(), list.get(0));
                } else {
                    if (debug)
                        System.out.println("--object not found: " + columnName);
                }
            }

            //one to many association (list property)
            if (fieldValue instanceof List) { //Note: here recurring row's list property is mapped and add to parent's list
                if (columns.contains(columnName + "_id")) {
                    Class elementClass = VenList.findElementClass((List) fieldValue);
                    if (debug)
                        System.out.println(">>list is found " + columnName);
                    mapRecursively(rs, columns, columnName, elementClass, (List) fieldValue);
                } else {
                    if (debug)
                        System.out.println("--list not found: " + columnName);
                }
            }
        }
    } catch (Exception ex) {
        System.out.println("Ven - error while mapping row, table: " + tableName + " object class: "
                + objectClass + " error: " + ex.getMessage());
        if (debug) {
            ex.printStackTrace();
        }
    }
}

From source file:io.spring.initializr.generator.ProjectRequest.java

/**
 * Initializes this instance with the defaults defined in the specified
 * {@link InitializrMetadata}.//w  w w  .  j a v a2 s  .  c  om
 * @param metadata the initializr metadata
 */
public void initialize(InitializrMetadata metadata) {
    BeanWrapperImpl bean = new BeanWrapperImpl(this);
    metadata.defaults().forEach((key, value) -> {
        if (bean.isWritableProperty(key)) {
            // We want to be able to infer a package name if none has been
            // explicitly set
            if (!key.equals("packageName")) {
                bean.setPropertyValue(key, value);
            }
        }
    });
}

From source file:com.siberhus.tdfl.mapping.BeanWrapLineMapper.java

private Object getPropertyValue(Object bean, String nestedName) {
    BeanWrapperImpl wrapper = new BeanWrapperImpl(bean);
    Object nestedValue = wrapper.getPropertyValue(nestedName);
    if (nestedValue == null) {
        try {//  w w  w  . j ava  2s.  co m
            nestedValue = wrapper.getPropertyType(nestedName).newInstance();
            wrapper.setPropertyValue(nestedName, nestedValue);
        } catch (InstantiationException e) {
            ReflectionUtils.handleReflectionException(e);
        } catch (IllegalAccessException e) {
            ReflectionUtils.handleReflectionException(e);
        }
    }
    return nestedValue;
}

From source file:com.emc.ecs.sync.service.SyncJobService.java

@SuppressWarnings("unchecked")
protected <T extends SyncPlugin> T createPlugin(PluginConfig pluginConfig, SyncConfig syncConfig,
        Class<T> clazz) {//from w  w w .java 2  s .  co  m
    try {
        T plugin = (T) Class.forName(pluginConfig.getPluginClass()).newInstance();
        BeanWrapperImpl wrapper = new BeanWrapperImpl(plugin);

        // register property converters
        wrapper.registerCustomEditor(Date.class,
                new CustomDateEditor(new SimpleDateFormat(ISO_8601_FORMAT), true));
        wrapper.registerCustomEditor(Vdc.class, new VdcEditor());

        // set custom properties
        for (Map.Entry<String, String> prop : pluginConfig.getCustomProperties().entrySet()) {
            wrapper.setPropertyValue(prop.getKey(), prop.getValue());
        }
        // set custom list properties
        for (Map.Entry<String, List<String>> listProp : pluginConfig.getCustomListProperties().entrySet()) {
            wrapper.setPropertyValue(listProp.getKey(), listProp.getValue());
        }

        copyProperties(syncConfig, plugin); // set common properties

        return plugin;
    } catch (ClassCastException e) {
        throw new ConfigurationException(
                pluginConfig.getPluginClass() + " does not extend " + clazz.getSimpleName());
    } catch (BeansException e) {
        throw new ConfigurationException("could not set property on plugin " + pluginConfig.getPluginClass(),
                e);
    } catch (Throwable t) {
        throw new ConfigurationException("could not create plugin instance " + pluginConfig.getPluginClass(),
                t);
    }
}

From source file:com.smhdemo.common.datasource.generate.factory.custom.CustomDataSourceFactory.java

@SuppressWarnings("rawtypes")
@Override/*w w  w  .  j  a  v  a 2  s . c  o  m*/
public DataSourceServiceable createService(Base alqcDataSource) {
    if (!(alqcDataSource instanceof Custom)) {
        logger.error("Custom??");
        throw new BaseRuntimeException("Custom??", new Object[] { alqcDataSource.getClass() });
    }
    Custom customDataSource = (Custom) alqcDataSource;

    // ???
    String serviceClassName = customDataSource.getServiceClass();
    DataSourceServiceable service;
    try {
        Class serviceClass = Class.forName(serviceClassName);
        service = (DataSourceServiceable) serviceClass.newInstance();
    } catch (Exception e) {
        logger.error("?Custom??", e);
        BaseRuntimeException ex = new BaseRuntimeException("?Custom??", e);
        ex.setArgs(new Object[] { serviceClassName });
        throw ex;
    }
    try {
        // Spring??
        BeanWrapperImpl bw = new BeanWrapperImpl(service);
        // CustomDataSourceDefinition
        CustomDataSourceDefinition def = getDefinitionByServiceClass(serviceClassName);
        // "propertyMap"?
        Map<String, Object> propMap = new HashMap<String, Object>();
        // ?
        Iterator pdi = def.getPropertyDefinitions().iterator();
        while (pdi.hasNext()) {
            Map pd = (Map) pdi.next();
            String name = (String) pd.get(CustomDataSourceDefinition.PARAM_NAME);
            Object deflt = pd.get(CustomDataSourceDefinition.PARAM_DEFAULT);
            Object value = customDataSource.getPropertyMap().get(name);
            if (value == null && deflt != null) {
                value = deflt;
            }
            // ?
            if (value != null) {
                if (bw.isWritableProperty(name)) {
                    bw.setPropertyValue(name, value);
                }
                propMap.put(name, value);
            }
        }
        if (bw.isWritableProperty(PROPERTY_MAP)) {
            bw.setPropertyValue(PROPERTY_MAP, propMap);
        }

    } catch (Exception e) {
        logger.error("Custom??", e);
        BaseRuntimeException ex = new BaseRuntimeException("Custom??", e);
        ex.setArgs(new Object[] { serviceClassName });
        throw ex;
    }

    return service;
}