Example usage for org.springframework.beans BeanUtils instantiate

List of usage examples for org.springframework.beans BeanUtils instantiate

Introduction

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

Prototype

@Deprecated
public static <T> T instantiate(Class<T> clazz) throws BeanInstantiationException 

Source Link

Document

Convenience method to instantiate a class using its no-arg constructor.

Usage

From source file:org.javelin.sws.ext.bind.internal.model.ComplexTypePattern.java

@Override
public T consumeValue(XMLEventReader eventReader, UnmarshallingContext context) throws XMLStreamException {
    // first create an object to be filled (using PropertyAccessors - direct or bean) according to the content model
    T object = BeanUtils.instantiate(this.getJavaType());

    // the order is dictated by incoming events, not by the mode
    // TODO: create a property to enable strict unmarshalling - dictated by content model
    // only this (ContentModel) pattern iterates over XML Events
    XMLEvent event = null;// www .j av a2 s.  com
    PropertyMetadataValue<T, ?> pmv = null;

    // this loop will only handle first level of start elements and only single end element
    // deeper levels will be handled by nested patterns
    while (true) {
        boolean end = false;
        event = eventReader.peek();
        pmv = null;

        switch (event.getEventType()) {
        case XMLStreamConstants.ATTRIBUTE:
            pmv = this.consumeNestedAttribute(eventReader, context);
            break;
        case XMLStreamConstants.CDATA:
        case XMLStreamConstants.CHARACTERS:
            // TODO: XMLEvent.ENTITY_REFERENCE?
            if (this.simpleContent != null) {
                pmv = this.consumeSimpleContent(eventReader, context);
                break;
            }
        case XMLStreamConstants.COMMENT:
        case XMLStreamConstants.DTD:
        case XMLStreamConstants.SPACE:
        case XMLStreamConstants.ENTITY_DECLARATION:
        case XMLStreamConstants.NOTATION_DECLARATION:
        case XMLStreamConstants.PROCESSING_INSTRUCTION:
            eventReader.nextEvent();
            break;
        case XMLStreamConstants.ENTITY_REFERENCE:
            // TODO: XMLEvent.ENTITY_REFERENCE?
            eventReader.nextEvent();
            break;
        case XMLStreamConstants.START_DOCUMENT:
            // strange
            break;
        case XMLStreamConstants.START_ELEMENT:
            pmv = this.consumeNestedElement(eventReader, context);
            break;
        case XMLStreamConstants.END_ELEMENT:
            // TODO: in mixed content there will be more than one end element it this content model's level
        case XMLStreamConstants.END_DOCUMENT:
            end = true;
            break;
        }

        if (end)
            break;

        if (pmv != null)
            pmv.getMetadata().setValue(object, pmv.getValue());
    }

    return (T) object;
}

From source file:cn.uncode.schedule.quartz.MethodInvokingJobDetailFactoryBean.java

public void afterPropertiesSet() throws ClassNotFoundException, NoSuchMethodException {
    prepare();//from w ww .j a va2s .c o m

    // Use specific name if given, else fall back to bean name.
    String name = (this.name != null ? this.name : this.beanName);

    // Consider the concurrent flag to choose between stateful and stateless job.
    Class<?> jobClass = (this.concurrent ? MethodInvokingJob.class : StatefulMethodInvokingJob.class);

    // Build JobDetail instance.
    if (jobDetailImplClass != null) {
        // Using Quartz 2.0 JobDetailImpl class...
        this.jobDetail = (JobDetail) BeanUtils.instantiate(jobDetailImplClass);
        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this.jobDetail);
        bw.setPropertyValue("name", name);
        bw.setPropertyValue("group", this.group);
        bw.setPropertyValue("jobClass", jobClass);
        bw.setPropertyValue("durability", true);
        ((JobDataMap) bw.getPropertyValue("jobDataMap")).put("methodInvoker", this);
    }

    // Register job listener names.
    if (this.jobListenerNames != null) {
        for (String jobListenerName : this.jobListenerNames) {
            if (jobListenerName != null) {
                throw new IllegalStateException("Non-global JobListeners not supported on Quartz 2 - "
                        + "manually register a Matcher against the Quartz ListenerManager instead");
            }
            //this.jobDetail.addJobListener(jobListenerName);
        }
    }

    postProcessJobDetail(this.jobDetail);
}

From source file:org.shept.persistence.provider.DaoUtils.java

private static Object copyTemplate_Experimental(HibernateDaoSupport dao, Object entityModelTemplate) {
    ClassMetadata modelMeta = getClassMetadata(dao, entityModelTemplate);
    if (null == modelMeta) {
        return null;
    }/*  w  ww .j  a v  a  2 s.  c  om*/
    String idName = modelMeta.getIdentifierPropertyName();
    Object modelCopy = BeanUtils.instantiateClass(entityModelTemplate.getClass());
    BeanUtils.copyProperties(entityModelTemplate, modelCopy, new String[] { idName });

    Type idType = modelMeta.getIdentifierType();
    if (null == idType || !idType.isComponentType()) {
        return modelCopy;
    }

    Object idValue = modelMeta.getPropertyValue(entityModelTemplate, idName, EntityMode.POJO);
    if (null == idValue) {
        return modelCopy;
    }

    Object idCopy = BeanUtils.instantiate(idValue.getClass());
    BeanUtils.copyProperties(idValue, idCopy);

    if (null == idValue || (null != idType)) {
        return modelCopy;
    }

    Method idMth = ReflectionUtils.findMethod(entityModelTemplate.getClass(),
            "set" + StringUtils.capitalize(idName), new Class[] {});
    if (idMth != null) {
        ReflectionUtils.invokeMethod(idMth, modelCopy, idCopy);
    }

    return modelCopy;
}

From source file:com.dexcoder.dal.spring.mapper.JdbcRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData/*from   w w  w .  j  ava  2 s . co m*/
 */
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T mappedObject = BeanUtils.instantiate(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        String field = lowerCaseName(column.replaceAll(" ", ""));
        PropertyDescriptor pd = this.mappedFields.get(field);
        if (pd != null) {
            try {
                Object value = getColumnValue(rs, index, pd);
                if (rowNumber == 0 && logger.isDebugEnabled()) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type ["
                            + ClassUtils.getQualifiedName(pd.getPropertyType()) + "]");
                }
                try {
                    bw.setPropertyValue(pd.getName(), value);
                } catch (TypeMismatchException ex) {
                    if (value == null && this.primitivesDefaultedForNullValue) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("Intercepted TypeMismatchException for row " + rowNumber
                                    + " and column '" + column + "' with null value when setting property '"
                                    + pd.getName() + "' of type ["
                                    + ClassUtils.getQualifiedName(pd.getPropertyType()) + "] on object: "
                                    + mappedObject, ex);
                        }
                    } else {
                        throw ex;
                    }
                }
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column '" + column + "' to property '" + pd.getName() + "'", ex);
            }
        } else {
            // No PropertyDescriptor found
            if (rowNumber == 0 && logger.isDebugEnabled()) {
                logger.debug("No property found for column '" + column + "' mapped to field '" + field + "'");
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException(
                "Given ResultSet does not contain all fields " + "necessary to populate object of class ["
                        + this.mappedClass.getName() + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

From source file:com.mx.core.dao.BeanPropRowMap.java

/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData//from  w ww  .  j  ava 2  s .c  o m
 */
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T mappedObject = BeanUtils.instantiate(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
        if (pd != null) {
            try {
                Object value = getColumnValue(rs, index, pd);
                if (logger.isDebugEnabled() && rowNumber == 0) {
                    //logger.debug("Mapping column '" + column + "' to property '" +
                    //      pd.getName() + "' of type " + pd.getPropertyType());
                }
                try {
                    bw.setPropertyValue(pd.getName(), value);
                } catch (TypeMismatchException e) {
                    if (value == null && primitivesDefaultedForNullValue) {
                        logger.debug("Intercepted TypeMismatchException for row " + rowNumber + " and column '"
                                + column + "' with value " + value + " when setting property '" + pd.getName()
                                + "' of type " + pd.getPropertyType() + " on object: " + mappedObject);
                    } else {
                        throw e;
                    }
                }
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
                + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

From source file:com.insframework.common.spring.jdbc.mapper.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData//w ww  .j  a  v  a2s .  c  o  m
 */
@Override
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T mappedObject = BeanUtils.instantiate(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
        if (pd != null) {
            try {
                Object value = getColumnValue(rs, index, pd);
                if (logger.isDebugEnabled() && rowNumber == 0) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type "
                            + pd.getPropertyType());
                }
                try {
                    //add by guom
                    if (pd.getPropertyType() != null
                            && "java.lang.String".equals(pd.getPropertyType().getName())) {
                        if (value != null) {
                            bw.setPropertyValue(pd.getName(), String.valueOf(value));
                        } else {
                            bw.setPropertyValue(pd.getName(), "");
                        }
                    } else if (pd.getPropertyType() != null
                            && "double".equals(pd.getPropertyType().getName())) {
                        if (value != null) {
                            bw.setPropertyValue(pd.getName(), value);
                        } else {
                            bw.setPropertyValue(pd.getName(), 0d);
                        }
                    } else {
                        bw.setPropertyValue(pd.getName(), value);
                    }

                } catch (TypeMismatchException e) {
                    if (value == null && primitivesDefaultedForNullValue) {
                        logger.info("Intercepted TypeMismatchException for row " + rowNumber + " and column '"
                                + column + "' with value " + value + " when setting property '" + pd.getName()
                                + "' of type " + pd.getPropertyType() + " on object: " + mappedObject);
                    } else {
                        throw e;
                    }
                }
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
                + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

From source file:org.jdal.vaadin.data.ContainerDataSource.java

private BeanItem<T> newItem() {
    T bean = null;/*ww  w  .  j a  v  a 2s .  c o  m*/
    try {
        bean = BeanUtils.instantiate(entityClass);
    } catch (BeanInstantiationException be) {
        log.error(be);
        return null;
    }

    BeanItem<T> newItem = new BeanItem<T>(bean);
    return newItem;
}

From source file:com.duowan.common.spring.jdbc.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData/*from w  w  w.  ja va2 s . co  m*/
 */
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T mappedObject = BeanUtils.instantiate(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
        if (pd != null) {
            try {
                Object value = getColumnValue(rs, index, pd);
                if (logger.isDebugEnabled() && rowNumber == 0) {
                    logger.debug("Mapping column '" + column + "' to property '" + pd.getName() + "' of type "
                            + pd.getPropertyType());
                }
                try {
                    bw.setPropertyValue(pd.getName(), value);
                } catch (TypeMismatchException e) {
                    if (value == null && primitivesDefaultedForNullValue) {
                        logger.debug("Intercepted TypeMismatchException for row " + rowNumber + " and column '"
                                + column + "' with value " + value + " when setting property '" + pd.getName()
                                + "' of type " + pd.getPropertyType() + " on object: " + mappedObject);
                    } else {
                        throw e;
                    }
                }
                if (populatedProperties != null) {
                    populatedProperties.add(pd.getName());
                }
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        }
    }

    if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
        throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields "
                + "necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
    }

    return mappedObject;
}

From source file:org.mybatisorm.annotation.handler.TableHandler.java

public List<ResultMapping> getResultMappingList(Configuration configuration) {
    List<ResultMapping> list = new ArrayList<ResultMapping>();
    for (Field field : getColumnFields()) {
        String columnName = ColumnAnnotation.getName(field);

        if (!"".equals(columnName)) {
            ResultMapping.Builder builder = new ResultMapping.Builder(configuration, field.getName(),
                    columnName, field.getType());
            // add typeHandler
            if (field.isAnnotationPresent(TypeHandler.class)) {
                TypeHandler typeHandlerAnnotation = field.getAnnotation(TypeHandler.class);
                // if (logger.isDebugEnabled()) logger.debug("add typeHandler [" + typeHandlerAnnotation.value().getName() + "] for " + columnName + ":" + typeHandlerAnnotation.jdbcType());
                builder.typeHandler(BeanUtils.instantiate(typeHandlerAnnotation.value()))
                        .jdbcType(typeHandlerAnnotation.jdbcType());

            }//from  w  ww. j  a  v a 2  s.com
            list.add(builder.build());
        }
    }
    return list;
}

From source file:org.jnap.core.mvc.async.AsyncRequestInterceptor.java

/**
 * /*  w  w  w . j  av a2s. co m*/
 * @param listenerTypes
 * @return
 */
protected AtmosphereResourceEventListener[] createListeners(
        Class<? extends AtmosphereResourceEventListener>[] listenerTypes) {
    AtmosphereResourceEventListener[] listeners = null;
    if (listenerTypes != null) {
        listeners = new AtmosphereResourceEventListener[listenerTypes.length];
        AtmosphereResourceEventListener listener = null;
        AutowireCapableBeanFactory autowireCapableBeanFactory = null;
        try {
            autowireCapableBeanFactory = applicationContext.getAutowireCapableBeanFactory();
        } catch (IllegalStateException e) {
            // ignore; listeners will not be inject with spring beans
        }
        for (int i = 0; i < listenerTypes.length; i++) {
            Class<? extends AtmosphereResourceEventListener> listenerType = listenerTypes[i];
            listener = BeanUtils.instantiate(listenerType);
            if (autowireCapableBeanFactory != null) {
                autowireCapableBeanFactory.autowireBean(listener);
            }
            listeners[i] = listener;
        }
    }
    return listeners;
}