Example usage for org.springframework.beans BeanUtils instantiateClass

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

Introduction

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

Prototype

public static <T> T instantiateClass(Class<T> clazz) throws BeanInstantiationException 

Source Link

Document

Instantiate a class using its 'primary' constructor (for Kotlin classes, potentially having default arguments declared) or its default constructor (for regular Java classes, expecting a standard no-arg setup).

Usage

From source file:ei.ne.ke.cassandra.cql3.SimpleEntitySpecification.java

/**
 * {@inheritDoc}/*w w  w. j  a v a2  s  .c o m*/
 */
@Override
public T map(ColumnList<String> columns) {
    T entity = BeanUtils.instantiateClass(entityClazz);
    for (Column<String> column : columns) {
        String normalizedColumnName = EntitySpecificationUtils.normalizeCqlElementName(column.getName());
        AttributeAccessor accessor = attributeAccessors.get(normalizedColumnName);
        if (accessor == null) {
            LOGGER.warn("The CQL3 column {} isn't mapped to any entity attribute.", normalizedColumnName);
            continue;
        }
        EntitySpecificationUtils.deserializeAttribute(column, accessor, entity);
    }
    return entity;
}

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

/**
 * This Hibernate specific code will create shallow copies of the model
 * object//from  w ww . j a  v a2s .  c  o  m
 * 
 * @param dao
 * @param entityModelTemplate
 * @param includeId
 *            true if the id is to be included
 * @return
 */
public static Object shallowCopyModel(DaoSupport dao, Object entityModelTemplate, boolean includeId) {
    ClassMetadata modelMeta = getClassMetadata(dao, entityModelTemplate);
    if (null == modelMeta) {
        return null;
    }
    Object modelCopy = BeanUtils.instantiateClass(entityModelTemplate.getClass());
    if (!includeId) {
        String idName = modelMeta.getIdentifierPropertyName();
        BeanUtils.copyProperties(entityModelTemplate, modelCopy, new String[] { idName });
    } else {
        BeanUtils.copyProperties(entityModelTemplate, modelCopy);
    }
    return modelCopy;
}

From source file:cn.clickvalue.cv2.model.rowmapper.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  v a 2s .  co m
 */
public Object mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    Object mappedObject = BeanUtils.instantiateClass(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = rs.getMetaData();
    int columnCount = rsmd.getColumnCount();
    for (int index = 1; index <= columnCount; index++) {
        String column = lookupColumnName(rsmd, index).toLowerCase();
        PropertyDescriptor pd = (PropertyDescriptor) this.mappedFields.get(column);
        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());
                }
                bw.setPropertyValue(pd.getName(), value);
            } catch (NotWritablePropertyException ex) {
                throw new DataRetrievalFailureException(
                        "Unable to map column " + column + " to property " + pd.getName(), ex);
            }
        }
    }

    return mappedObject;
}

From source file:ua.com.manometer.jasperreports.JasperReportsMultiFormatView.java

/**
 * Locates the format key in the model using the configured discriminator key and uses this
 * key to lookup the appropriate view class from the mappings. The rendering of the
 * report is then delegated to an instance of that view class.
 *///from   w  ww .  j  a  v  a2 s  .c o m
@Override
protected void renderReport(JasperPrint populatedReport, Map<String, Object> model,
        HttpServletResponse response) throws Exception {

    String format = (String) model.get(this.formatKey);
    if (format == null) {
        throw new IllegalArgumentException("No format format found in model");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Rendering report using format mapping key [" + format + "]");
    }

    Class<? extends AbstractJasperReportsView> viewClass = this.formatMappings.get(format);
    if (viewClass == null) {
        throw new IllegalArgumentException("Format discriminator [" + format + "] is not a configured mapping");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Rendering report using view class [" + viewClass.getName() + "]");
    }

    AbstractJasperReportsView view = BeanUtils.instantiateClass(viewClass);
    // Can skip most initialization since all relevant URL processing
    // has been done - just need to convert parameters on the sub view.
    view.setExporterParameters(getExporterParameters());
    view.setConvertedExporterParameters(getConvertedExporterParameters());
    String fileName = (String) model.get("name");
    populateContentDispositionIfNecessary(response, format, fileName);
    view.renderReport(populatedReport, model, response);
}

From source file:com.clican.pluto.common.support.spring.BeanPropertyRowMapper.java

/**
 * Extract the values for all columns in the current row.
 * <p>/*from w ww.j  av  a2  s.  c  o m*/
 * Utilizes public setters and result set metadata.
 * 
 * @see java.sql.ResultSetMetaData
 */
public Object mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    Object mappedObject = BeanUtils.instantiateClass(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).toLowerCase();
        PropertyDescriptor pd = (PropertyDescriptor) this.mappedFields.get(column);
        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());
                }
                bw.setPropertyValue(pd.getName(), value);
                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:ei.ne.ke.cassandra.cql3.CompoundEntitySpecification.java

/**
 * {@inheritDoc}//from   ww w.j av  a2 s .  c  o m
 */
@Override
public T map(ColumnList<String> columns) {
    try {
        T entity = BeanUtils.instantiateClass(entityClazz);
        ID embeddedEntity = BeanUtils.instantiateClass(keyClazz);

        for (Column<String> column : columns) {
            String normalizedColumnName = EntitySpecificationUtils.normalizeCqlElementName(column.getName());
            if (simpleAttributeAccessors.containsKey(normalizedColumnName)) {
                AttributeAccessor accessor = simpleAttributeAccessors.get(normalizedColumnName);
                EntitySpecificationUtils.deserializeAttribute(column, accessor, entity);
            } else if (embeddedAttributeAccessors.containsKey(normalizedColumnName)) {
                AttributeAccessor accessor = embeddedAttributeAccessors.get(normalizedColumnName);
                EntitySpecificationUtils.deserializeAttribute(column, accessor, embeddedEntity);
            } else {
                LOGGER.warn("The CQL3 column {} isn't mapped to any entity field", normalizedColumnName);
            }
        }
        keyField.set(entity, embeddedEntity);
        return entity;
    } catch (IllegalAccessException e) {
        throw new IllegalStateException("Couldn't access field annotated with @EmbeddedId", e);
    }
}

From source file:com.laxser.blitz.web.paramresolver.ServletRequestDataBinder.java

@Override
protected void doBind(MutablePropertyValues mpvs) {
    // book.author.name?book.authorauthor
    PropertyValue[] pvArray = mpvs.getPropertyValues();
    MutablePropertyValues newMpvs = null;
    for (int i = 0; i < pvArray.length; i++) {
        PropertyValue pv = pvArray[i];// ww  w  .  j av a2  s  . co m
        String propertyName = pv.getName();
        int dot = propertyName.indexOf('.');
        while (dot != -1) {
            String field = propertyName.substring(0, dot);
            if (getPropertyAccessor().isWritableProperty(field) && !mpvs.contains(field)) {
                Class<?> fieldType = getPropertyAccessor().getPropertyType(field);
                if (newMpvs == null) {
                    newMpvs = new MutablePropertyValues();
                }
                newMpvs.addPropertyValue(field, BeanUtils.instantiateClass(fieldType));
            }
            dot = propertyName.indexOf('.', dot + 1);
        }
    }
    if (newMpvs == null) {
        super.doBind(mpvs);
    } else {
        newMpvs.addPropertyValues(mpvs);
        super.doBind(newMpvs);
    }
}

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;
    }/*from   w ww  .  j a v  a2s .  co  m*/
    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:at.ac.tuwien.infosys.jcloudscale.test.unit.TestReflectionUtil.java

@Test
public void testGetClassesFromObjects() throws ReflectiveOperationException {
    Class<?>[] classes = getClassesFromObjects(false, 0, 0D, BeanUtils.instantiateClass(Void.class));
    assertArrayEquals(new Class<?>[] { Boolean.class, Integer.class, Double.class, Void.class }, classes);
}