Example usage for org.springframework.beans BeanWrapperImpl BeanWrapperImpl

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

Introduction

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

Prototype

public BeanWrapperImpl() 

Source Link

Document

Create a new empty BeanWrapperImpl.

Usage

From source file:org.jdbcluster.dao.Dao.java

/**
 * creates new instance of a Dao using given Dao class
 * @param daoClass class of Object to create
 * @return created dao instance/*  www.  j  a va  2  s . c  o m*/
 */
public static Object newInstance(Class<?> daoClass) {
    Object dao = JDBClusterUtil.createClassObject(daoClass);
    //get property of DAO and initial value from jdbcluster.dao.conf.xml
    HashMap<String, String> hm;
    synchronized (classToPropsMap) {
        hm = classToPropsMap.get(daoClass);
        if (hm == null)
            hm = putCacheMap(daoClass);
    }

    BeanWrapper beanWrapper = new BeanWrapperImpl();
    beanWrapper.setWrappedInstance(dao);

    for (String prop : hm.keySet()) {
        String value = hm.get(prop);
        //get property of DAO
        Class<?> propClass = beanWrapper.getPropertyType(prop);
        //convert to Type if necessary
        Object o = beanWrapper.convertIfNecessary(value, propClass);
        //set the value of the predefined property read from jdbcluster.dao.conf.xml
        beanWrapper.setPropertyValue(new PropertyValue(prop, o));
    }
    return dao;
}

From source file:org.impalaframework.extension.mvc.annotation.collector.ModelArgumentCollectorTest.java

public void testGetArgument() {
    ModelArgumentCollector collector = new ModelArgumentCollector();
    ExtendedModelMap implicitModel = new ExtendedModelMap();
    assertSame(implicitModel,//  ww w. ja va 2s .  co m
            collector.getArgument(createMock(NativeWebRequest.class), implicitModel, new BeanWrapperImpl()));
}

From source file:hsa.awp.common.util.StaticInitializerBeanFactoryPostProcessor.java

/**
 * Initializes a new {@link StaticInitializerBeanFactoryPostProcessor} and instantiates a new {@link BeanWrapperImpl}.
 *//*from  w ww  .ja  v  a 2  s .  co m*/
public StaticInitializerBeanFactoryPostProcessor() {

    bri = new BeanWrapperImpl();
}

From source file:org.impalaframework.extension.mvc.annotation.handler.ServletHandlerMethodInvoker.java

public TypeConverter getTypeConverter() {
    TypeConverter typeConverter = new BeanWrapperImpl();
    return typeConverter;
}

From source file:com.opensymphony.able.action.JpaCrudActionBeanTest.java

@Test
public void testIntrospection() throws Exception {
    Person bug = new Person();

    DataBinder binder = new DataBinder(bug);
    MutablePropertyValues propertyValues = new MutablePropertyValues();
    propertyValues.addPropertyValue("id", "123456");
    binder.bind(propertyValues);//from   w w w. ja  v  a 2  s.  c om

    Assert.assertEquals(new Integer(123456), bug.getId());

    TypeConverter typeConverter = new BeanWrapperImpl();
    Object value = typeConverter.convertIfNecessary("123456", Integer.class);
    Assert.assertEquals(new Integer(123456), value);
}

From source file:com.aw.support.collection.ListUtils.java

public static <E> List<E> sort(List<E> list, Comparator comparator) {
    final BeanWrapperImpl wrap1 = new BeanWrapperImpl();
    final BeanWrapperImpl wrap2 = new BeanWrapperImpl();
    List<E> sortedList = new ArrayList<E>(list);
    //        Comparator<E> comparator2 = new Comparator<E>() {
    //            public int compare(E o1, E o2) {
    //                wrap1.setWrappedInstance(o1);
    //                wrap2.setWrappedInstance(o2);
    //                Comparable value1 = (Comparable) wrap1.getPropertyValue(propertyName);
    //                Comparable value2 = (Comparable) wrap2.getPropertyValue(propertyName);
    //                int retVal;
    //                if (value1 != null && value2 != null)
    //                    retVal = value1.compareTo(value2);
    //                else if (value1 != null)
    //                    retVal = 1;
    //                else if (value2 != null)
    //                    retVal = -1;
    //                else retVal = 0;
    //                return reverse ? -1 * retVal : retVal; //ambos son null
    //            }
    //        };// w w  w . j a v a  2  s .c o  m
    Collections.sort(sortedList, comparator);
    return sortedList;
}

From source file:com.aw.swing.mvp.binding.component.support.ColumnInfo.java

private BeanWrapper getRow(Object object) {
    if (object instanceof Object[])
        return null;
    if (row == null) {
        row = new BeanWrapperImpl();
    }//  w ww .j a v  a2  s  .c o  m
    row = new BeanWrapperImpl(object);
    row.registerCustomEditor(Date.class,
            new CustomDateEditor(DateFormatter.DATE_FORMATTER.getDateFormat(), true));

    if (isEditable() && hasNumberFormatter()) {
        Class type = row.getPropertyDescriptor(fieldName).getPropertyType();
        NumberFormat numberFormat = ((NumberFormatter) formatter).getFormat();
        row.registerCustomEditor(null, fieldName, new CustomNumberEditor(type, numberFormat, true));
    }
    return row;
}

From source file:com.aw.support.collection.ListUtils.java

public static StringBuffer concatenarSepPorStr(Collection cols, String propertyName, String sep,
        String enclosingStr) {//from ww w . j  a  v a  2s .c  o m
    StringBuffer colsStr = new StringBuffer();
    BeanWrapper wrap = new BeanWrapperImpl();
    for (Iterator iterator = cols.iterator(); iterator.hasNext();) {
        Object col = iterator.next();
        if (propertyName != null) {
            wrap = new BeanWrapperImpl(col);
            col = wrap.getPropertyValue(propertyName);
        }
        if (enclosingStr != null)
            colsStr.append(enclosingStr);
        colsStr.append(col);
        if (enclosingStr != null)
            colsStr.append(enclosingStr);
        if (iterator.hasNext())
            colsStr.append(sep);
    }
    return colsStr;
}

From source file:org.springframework.beans.factory.support.AbstractBeanFactory.java

/**
 * Convert the given value into the specified target type,
 * using a default BeanWrapper instance.
 * @param value the original value//  w w w . j a va2 s. c o  m
 * @param targetType the target type
 * @return the converted value, matching the target type
 * @throws org.springframework.beans.TypeMismatchException if type conversion failed
 * @see #doTypeConversionIfNecessary(Object, Class, org.springframework.beans.BeanWrapperImpl)
 */
protected Object doTypeConversionIfNecessary(Object value, Class targetType) throws TypeMismatchException {
    BeanWrapperImpl bw = new BeanWrapperImpl();
    initBeanWrapper(bw);
    return doTypeConversionIfNecessary(value, targetType, bw);
}

From source file:org.springframework.beans.factory.support.ConstructorResolver.java

/**
 * "autowire constructor" (with constructor arguments by type) behavior.
 * Also applied if explicit constructor argument values are specified,
 * matching all remaining arguments with beans from the bean factory.
 * <p>This corresponds to constructor injection: In this mode, a Spring
 * bean factory is able to host components that expect constructor-based
 * dependency resolution./*ww  w  .  j a va 2  s  . c  om*/
 * @param beanName the name of the bean
 * @param mbd the merged bean definition for the bean
 * @param chosenCtors chosen candidate constructors (or {@code null} if none)
 * @param explicitArgs argument values passed in programmatically via the getBean method,
 * or {@code null} if none (-> use constructor argument values from bean definition)
 * @return a BeanWrapper for the new instance
 */
public BeanWrapper autowireConstructor(final String beanName, final RootBeanDefinition mbd,
        @Nullable Constructor<?>[] chosenCtors, @Nullable final Object[] explicitArgs) {

    BeanWrapperImpl bw = new BeanWrapperImpl();
    this.beanFactory.initBeanWrapper(bw);

    Constructor<?> constructorToUse = null;
    ArgumentsHolder argsHolderToUse = null;
    Object[] argsToUse = null;

    if (explicitArgs != null) {
        argsToUse = explicitArgs;
    } else {
        Object[] argsToResolve = null;
        synchronized (mbd.constructorArgumentLock) {
            constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
            if (constructorToUse != null && mbd.constructorArgumentsResolved) {
                // Found a cached constructor...
                argsToUse = mbd.resolvedConstructorArguments;
                if (argsToUse == null) {
                    argsToResolve = mbd.preparedConstructorArguments;
                }
            }
        }
        if (argsToResolve != null) {
            argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve, true);
        }
    }

    if (constructorToUse == null) {
        // Need to resolve the constructor.
        boolean autowiring = (chosenCtors != null
                || mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
        ConstructorArgumentValues resolvedValues = null;

        int minNrOfArgs;
        if (explicitArgs != null) {
            minNrOfArgs = explicitArgs.length;
        } else {
            ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
            resolvedValues = new ConstructorArgumentValues();
            minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
        }

        // Take specified constructors, if any.
        Constructor<?>[] candidates = chosenCtors;
        if (candidates == null) {
            Class<?> beanClass = mbd.getBeanClass();
            try {
                candidates = (mbd.isNonPublicAccessAllowed() ? beanClass.getDeclaredConstructors()
                        : beanClass.getConstructors());
            } catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                        "Resolution of declared constructors on bean Class [" + beanClass.getName()
                                + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed",
                        ex);
            }
        }
        AutowireUtils.sortConstructors(candidates);
        int minTypeDiffWeight = Integer.MAX_VALUE;
        Set<Constructor<?>> ambiguousConstructors = null;
        LinkedList<UnsatisfiedDependencyException> causes = null;

        for (Constructor<?> candidate : candidates) {
            Class<?>[] paramTypes = candidate.getParameterTypes();

            if (constructorToUse != null && argsToUse.length > paramTypes.length) {
                // Already found greedy constructor that can be satisfied ->
                // do not look any further, there are only less greedy constructors left.
                break;
            }
            if (paramTypes.length < minNrOfArgs) {
                continue;
            }

            ArgumentsHolder argsHolder;
            if (resolvedValues != null) {
                try {
                    String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length);
                    if (paramNames == null) {
                        ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
                        if (pnd != null) {
                            paramNames = pnd.getParameterNames(candidate);
                        }
                    }
                    argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
                            getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
                } catch (UnsatisfiedDependencyException ex) {
                    if (logger.isTraceEnabled()) {
                        logger.trace(
                                "Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
                    }
                    // Swallow and try next constructor.
                    if (causes == null) {
                        causes = new LinkedList<>();
                    }
                    causes.add(ex);
                    continue;
                }
            } else {
                // Explicit arguments given -> arguments length must match exactly.
                if (paramTypes.length != explicitArgs.length) {
                    continue;
                }
                argsHolder = new ArgumentsHolder(explicitArgs);
            }

            int typeDiffWeight = (mbd.isLenientConstructorResolution()
                    ? argsHolder.getTypeDifferenceWeight(paramTypes)
                    : argsHolder.getAssignabilityWeight(paramTypes));
            // Choose this constructor if it represents the closest match.
            if (typeDiffWeight < minTypeDiffWeight) {
                constructorToUse = candidate;
                argsHolderToUse = argsHolder;
                argsToUse = argsHolder.arguments;
                minTypeDiffWeight = typeDiffWeight;
                ambiguousConstructors = null;
            } else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
                if (ambiguousConstructors == null) {
                    ambiguousConstructors = new LinkedHashSet<>();
                    ambiguousConstructors.add(constructorToUse);
                }
                ambiguousConstructors.add(candidate);
            }
        }

        if (constructorToUse == null) {
            if (causes != null) {
                UnsatisfiedDependencyException ex = causes.removeLast();
                for (Exception cause : causes) {
                    this.beanFactory.onSuppressedException(cause);
                }
                throw ex;
            }
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Could not resolve matching constructor "
                            + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
        } else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                    "Ambiguous constructor matches found in bean '" + beanName + "' "
                            + "(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): "
                            + ambiguousConstructors);
        }

        if (explicitArgs == null) {
            argsHolderToUse.storeCache(mbd, constructorToUse);
        }
    }

    try {
        final InstantiationStrategy strategy = this.beanFactory.getInstantiationStrategy();
        Object beanInstance;

        if (System.getSecurityManager() != null) {
            final Constructor<?> ctorToUse = constructorToUse;
            final Object[] argumentsToUse = argsToUse;
            beanInstance = AccessController
                    .doPrivileged(
                            (PrivilegedAction<Object>) () -> strategy.instantiate(mbd, beanName,
                                    this.beanFactory, ctorToUse, argumentsToUse),
                            this.beanFactory.getAccessControlContext());
        } else {
            beanInstance = strategy.instantiate(mbd, beanName, this.beanFactory, constructorToUse, argsToUse);
        }

        bw.setBeanInstance(beanInstance);
        return bw;
    } catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Bean instantiation via constructor failed", ex);
    }
}