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:org.springframework.boot.web.client.RestTemplateBuilder.java

private ClientHttpRequestFactory detectRequestFactory() {
    for (Map.Entry<String, String> candidate : REQUEST_FACTORY_CANDIDATES.entrySet()) {
        ClassLoader classLoader = getClass().getClassLoader();
        if (ClassUtils.isPresent(candidate.getKey(), classLoader)) {
            Class<?> factoryClass = ClassUtils.resolveClassName(candidate.getValue(), classLoader);
            return (ClientHttpRequestFactory) BeanUtils.instantiateClass(factoryClass);
        }/* w  ww  .ja  v a  2 s  .c om*/
    }
    return new SimpleClientHttpRequestFactory();
}

From source file:org.springframework.context.annotation.ConfigurationClassParser.java

/**
 * Process the given <code>@PropertySource</code> annotation metadata.
 * @param propertySource metadata for the <code>@PropertySource</code> annotation found
 * @throws IOException if loading a property source failed
 *//*w w w  .  j av a2s.com*/
private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
    String name = propertySource.getString("name");
    if (!StringUtils.hasLength(name)) {
        name = null;
    }
    String encoding = propertySource.getString("encoding");
    if (!StringUtils.hasLength(encoding)) {
        encoding = null;
    }
    String[] locations = propertySource.getStringArray("value");
    Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
    boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");

    Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
    PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class
            ? DEFAULT_PROPERTY_SOURCE_FACTORY
            : BeanUtils.instantiateClass(factoryClass));

    for (String location : locations) {
        try {
            String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);
            Resource resource = this.resourceLoader.getResource(resolvedLocation);
            addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
        } catch (IllegalArgumentException | FileNotFoundException | UnknownHostException ex) {
            // Placeholders not resolvable or resource not found when trying to open it
            if (ignoreResourceNotFound) {
                if (logger.isInfoEnabled()) {
                    logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
                }
            } else {
                throw ex;
            }
        }
    }
}

From source file:org.springframework.data.document.mongodb.convert.SimpleMongoConverter.java

public <S> S read(Class<S> clazz, DBObject source) {

    if (source == null) {
        return null;
    }//from   ww w.ja va  2s .  c om

    Assert.notNull(clazz, "Mapped class was not specified");
    S target = BeanUtils.instantiateClass(clazz);
    MongoBeanWrapper bw = new MongoBeanWrapper(target, conversionService, true);

    for (MongoPropertyDescriptor descriptor : bw.getDescriptors()) {
        String keyToUse = descriptor.getKeyToMap();
        if (source.containsField(keyToUse)) {
            if (descriptor.isMappable()) {
                Object value = source.get(keyToUse);
                if (!isSimpleType(value.getClass())) {
                    if (value instanceof Object[]) {
                        bw.setValue(descriptor,
                                readCollection(descriptor, Arrays.asList((Object[]) value)).toArray());
                    } else if (value instanceof BasicDBList) {
                        bw.setValue(descriptor, readCollection(descriptor, (BasicDBList) value));
                    } else if (value instanceof DBObject) {
                        bw.setValue(descriptor, readCompoundValue(descriptor, (DBObject) value));
                    } else {
                        LOG.warn("Unable to map compound DBObject field " + keyToUse + " to property "
                                + descriptor.getName()
                                + ".  The field value should have been a 'DBObject.class' but was "
                                + value.getClass().getName());
                    }
                } else {
                    bw.setValue(descriptor, value);
                }
            } else {
                LOG.warn("Unable to map DBObject field " + keyToUse + " to property " + descriptor.getName()
                        + ".  Skipping.");
            }
        }
    }

    return target;
}

From source file:org.springframework.data.document.web.bind.annotation.support.HandlerMethodInvoker.java

private WebDataBinder resolveModelAttribute(String attrName, MethodParameter methodParam,
        ExtendedModelMap implicitModel, NativeWebRequest webRequest, Object handler) throws Exception {

    // Bind request parameter onto object...
    String name = attrName;/*from ww w  .  j  a  v  a 2s.c  om*/
    if ("".equals(name)) {
        name = Conventions.getVariableNameForParameter(methodParam);
    }
    Class<?> paramType = methodParam.getParameterType();
    Object bindObject;
    if (implicitModel.containsKey(name)) {
        bindObject = implicitModel.get(name);
    } else if (this.methodResolver.isSessionAttribute(name, paramType)) {
        bindObject = this.sessionAttributeStore.retrieveAttribute(webRequest, name);
        if (bindObject == null) {
            raiseSessionRequiredException("Session attribute '" + name + "' required - not found in session");
        }
    } else {
        bindObject = BeanUtils.instantiateClass(paramType);
    }
    WebDataBinder binder = createBinder(webRequest, bindObject, name);
    initBinder(handler, name, binder, webRequest);
    return binder;
}

From source file:org.springframework.data.jdbc.support.oracle.BeanPropertyStructMapper.java

/**
* Extract the values for all attributes in the struct.
* <p>Utilizes public setters and result set metadata.
* @see java.sql.ResultSetMetaData/* w w w  .  j a  v  a 2  s.  c  o  m*/
*/
public T fromStruct(STRUCT struct) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T mappedObject = BeanUtils.instantiateClass(this.mappedClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
    initBeanWrapper(bw);

    ResultSetMetaData rsmd = struct.getDescriptor().getMetaData();
    Object[] attr = struct.getAttributes();
    int columnCount = rsmd.getColumnCount();
    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 = attr[index - 1];
                if (logger.isDebugEnabled()) {
                    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:org.springframework.faces.mvc.bind.ReverseDataBinder.java

/**
 * Find a default editor for the given type. This code is based on <tt>TypeConverterDelegate.findDefaultEditor</tt>
 * from Spring 2.5.6.//  www .  ja  v  a2  s  .c om
 * @param requiredType the type to find an editor for
 * @param descriptor the JavaBeans descriptor for the property
 * @return the corresponding editor, or <code>null</code> if none
 * 
 * @author Juergen Hoeller
 * @author Rob Harrop
 */
protected PropertyEditor findDefaultEditor(PropertyEditorRegistrySupport propertyEditorRegistrySupport,
        Object targetObject, Class requiredType, PropertyDescriptor descriptor) {

    PropertyEditor editor = null;
    if (descriptor != null) {
        if (JdkVersion.isAtLeastJava15()) {
            editor = descriptor.createPropertyEditor(targetObject);
        } else {
            Class editorClass = descriptor.getPropertyEditorClass();
            if (editorClass != null) {
                editor = (PropertyEditor) BeanUtils.instantiateClass(editorClass);
            }
        }
    }

    if (editor == null && requiredType != null) {
        // No custom editor -> check default editors.
        editor = propertyEditorRegistrySupport.getDefaultEditor(requiredType);
        if (editor == null && !String.class.equals(requiredType)) {
            // No BeanWrapper default editor -> check standard JavaBean editor.
            editor = BeanUtils.findEditorByConvention(requiredType);
            if (editor == null && !unknownEditorTypes.containsKey(requiredType)) {
                // Global PropertyEditorManager fallback...
                editor = PropertyEditorManager.findEditor(requiredType);
                if (editor == null) {
                    // Regular case as of Spring 2.5
                    unknownEditorTypes.put(requiredType, Boolean.TRUE);
                }
            }
        }
    }
    return editor;
}

From source file:org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.java

/**
 * Configure an existing {@link ObjectMapper} instance with this builder's
 * settings. This can be applied to any number of {@code ObjectMappers}.
 * @param objectMapper the ObjectMapper to configure
 *///from www .j a  va 2s  .  c  om
public void configure(ObjectMapper objectMapper) {
    Assert.notNull(objectMapper, "ObjectMapper must not be null");

    if (this.findModulesViaServiceLoader) {
        // Jackson 2.2+
        objectMapper.registerModules(ObjectMapper.findModules(this.moduleClassLoader));
    } else if (this.findWellKnownModules) {
        registerWellKnownModulesIfAvailable(objectMapper);
    }

    if (this.modules != null) {
        for (Module module : this.modules) {
            // Using Jackson 2.0+ registerModule method, not Jackson 2.2+ registerModules
            objectMapper.registerModule(module);
        }
    }
    if (this.moduleClasses != null) {
        for (Class<? extends Module> module : this.moduleClasses) {
            objectMapper.registerModule(BeanUtils.instantiateClass(module));
        }
    }

    if (this.dateFormat != null) {
        objectMapper.setDateFormat(this.dateFormat);
    }
    if (this.locale != null) {
        objectMapper.setLocale(this.locale);
    }
    if (this.timeZone != null) {
        objectMapper.setTimeZone(this.timeZone);
    }

    if (this.annotationIntrospector != null) {
        objectMapper.setAnnotationIntrospector(this.annotationIntrospector);
    }
    if (this.propertyNamingStrategy != null) {
        objectMapper.setPropertyNamingStrategy(this.propertyNamingStrategy);
    }
    if (this.defaultTyping != null) {
        objectMapper.setDefaultTyping(this.defaultTyping);
    }
    if (this.serializationInclusion != null) {
        objectMapper.setSerializationInclusion(this.serializationInclusion);
    }

    if (this.filters != null) {
        objectMapper.setFilterProvider(this.filters);
    }

    for (Class<?> target : this.mixIns.keySet()) {
        objectMapper.addMixIn(target, this.mixIns.get(target));
    }

    if (!this.serializers.isEmpty() || !this.deserializers.isEmpty()) {
        SimpleModule module = new SimpleModule();
        addSerializers(module);
        addDeserializers(module);
        objectMapper.registerModule(module);
    }

    customizeDefaultFeatures(objectMapper);
    for (Object feature : this.features.keySet()) {
        configureFeature(objectMapper, feature, this.features.get(feature));
    }

    if (this.handlerInstantiator != null) {
        objectMapper.setHandlerInstantiator(this.handlerInstantiator);
    } else if (this.applicationContext != null) {
        objectMapper.setHandlerInstantiator(
                new SpringHandlerInstantiator(this.applicationContext.getAutowireCapableBeanFactory()));
    }
}

From source file:org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.java

@SuppressWarnings("unchecked")
private void registerWellKnownModulesIfAvailable(ObjectMapper objectMapper) {
    try {//w  w w  . j  a  v a 2s . c o  m
        Class<? extends Module> jdk8Module = (Class<? extends Module>) ClassUtils
                .forName("com.fasterxml.jackson.datatype.jdk8.Jdk8Module", this.moduleClassLoader);
        objectMapper.registerModule(BeanUtils.instantiateClass(jdk8Module));
    } catch (ClassNotFoundException ex) {
        // jackson-datatype-jdk8 not available
    }

    try {
        Class<? extends Module> javaTimeModule = (Class<? extends Module>) ClassUtils
                .forName("com.fasterxml.jackson.datatype.jsr310.JavaTimeModule", this.moduleClassLoader);
        objectMapper.registerModule(BeanUtils.instantiateClass(javaTimeModule));
    } catch (ClassNotFoundException ex) {
        // jackson-datatype-jsr310 not available
    }

    // Joda-Time present?
    if (ClassUtils.isPresent("org.joda.time.LocalDate", this.moduleClassLoader)) {
        try {
            Class<? extends Module> jodaModule = (Class<? extends Module>) ClassUtils
                    .forName("com.fasterxml.jackson.datatype.joda.JodaModule", this.moduleClassLoader);
            objectMapper.registerModule(BeanUtils.instantiateClass(jodaModule));
        } catch (ClassNotFoundException ex) {
            // jackson-datatype-joda not available
        }
    }

    // Kotlin present?
    if (KotlinDetector.isKotlinPresent()) {
        try {
            Class<? extends Module> kotlinModule = (Class<? extends Module>) ClassUtils
                    .forName("com.fasterxml.jackson.module.kotlin.KotlinModule", this.moduleClassLoader);
            objectMapper.registerModule(BeanUtils.instantiateClass(kotlinModule));
        } catch (ClassNotFoundException ex) {
            logger.warn("For Jackson Kotlin classes support please add "
                    + "\"com.fasterxml.jackson.module:jackson-module-kotlin\" to the classpath");
        }
    }
}

From source file:org.springframework.jdbc.core.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 .ja  va  2 s.com
 */
@Override
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
    Assert.state(this.mappedClass != null, "Mapped class was not specified");
    T 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<>() : null);

    for (int index = 1; index <= columnCount; index++) {
        String column = JdbcUtils.lookupColumnName(rsmd, index);
        String field = lowerCaseName(column.replaceAll(" ", ""));
        PropertyDescriptor pd = (this.mappedFields != null ? this.mappedFields.get(field) : null);
        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:org.springframework.mock.web.MockAsyncContext.java

@Override
public <T extends AsyncListener> T createListener(Class<T> clazz) throws ServletException {
    return BeanUtils.instantiateClass(clazz);
}