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:com.saysth.commons.quartz.SchedulerFactoryBean.java

public void afterPropertiesSet() throws Exception {
    if (this.dataSource == null && this.nonTransactionalDataSource != null) {
        this.dataSource = this.nonTransactionalDataSource;
    }//from  ww w .j  a va  2s .  c om

    if (this.applicationContext != null && this.resourceLoader == null) {
        this.resourceLoader = this.applicationContext;
    }

    // Create SchedulerFactory instance.
    SchedulerFactory schedulerFactory = (SchedulerFactory) BeanUtils
            .instantiateClass(this.schedulerFactoryClass);

    initSchedulerFactory(schedulerFactory);

    if (this.resourceLoader != null) {
        // Make given ResourceLoader available for SchedulerFactory
        // configuration.
        configTimeResourceLoaderHolder.set(this.resourceLoader);
    }
    if (this.taskExecutor != null) {
        // Make given TaskExecutor available for SchedulerFactory
        // configuration.
        configTimeTaskExecutorHolder.set(this.taskExecutor);
    }
    if (this.dataSource != null) {
        // Make given DataSource available for SchedulerFactory
        // configuration.
        configTimeDataSourceHolder.set(this.dataSource);
    }
    if (this.nonTransactionalDataSource != null) {
        // Make given non-transactional DataSource available for
        // SchedulerFactory configuration.
        configTimeNonTransactionalDataSourceHolder.set(this.nonTransactionalDataSource);
    }

    // Get Scheduler instance from SchedulerFactory.
    try {
        this.scheduler = createScheduler(schedulerFactory, this.schedulerName);
        populateSchedulerContext();

        if (!this.jobFactorySet && !(this.scheduler instanceof RemoteScheduler)) {
            // Use AdaptableJobFactory as default for a local Scheduler,
            // unless when
            // explicitly given a null value through the "jobFactory" bean
            // property.
            this.jobFactory = new AdaptableJobFactory();
        }
        if (this.jobFactory != null) {
            if (this.jobFactory instanceof SchedulerContextAware) {
                ((SchedulerContextAware) this.jobFactory).setSchedulerContext(this.scheduler.getContext());
            }
            this.scheduler.setJobFactory(this.jobFactory);
        }
    }

    finally {
        if (this.resourceLoader != null) {
            configTimeResourceLoaderHolder.remove();
        }
        if (this.taskExecutor != null) {
            configTimeTaskExecutorHolder.remove();
        }
        if (this.dataSource != null) {
            configTimeDataSourceHolder.remove();
        }
        if (this.nonTransactionalDataSource != null) {
            configTimeNonTransactionalDataSourceHolder.remove();
        }
    }

    registerListeners();
    registerJobsAndTriggers();
}

From source file:org.data.support.beans.factory.xml.XmlQueryDefinitionReader.java

/**
 * Create the {@link QueryDefinitionDocumentReader} to use for actually
 * reading query definitions from an XML document.
 * <p>The default implementation instantiates the specified "documentReaderClass".
 * @see #setDocumentReaderClass/*  w w w.  j  a v  a2 s.  c  o  m*/
 */
@SuppressWarnings("unchecked")
protected QueryDefinitionDocumentReader createQueryDefinitionDocumentReader() {
    return QueryDefinitionDocumentReader.class.cast(BeanUtils.instantiateClass(this.documentReaderClass));
}

From source file:org.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean.java

protected GrailsAnnotationConfiguration newConfiguration() throws Exception {
    if (configClass == null) {
        configClass = GrailsAnnotationConfiguration.class;
    }//w w  w.  j  av  a2 s . c om
    GrailsAnnotationConfiguration config = (GrailsAnnotationConfiguration) BeanUtils
            .instantiateClass(configClass);
    config.setApplicationContext(applicationContext);
    config.setGrailsApplication(grailsApplication);
    config.setSessionFactoryBeanName(sessionFactoryBeanName);
    config.setDataSourceName(dataSourceName);
    config.setHibernateEventListeners(hibernateEventListeners);
    if (currentSessionContextClass != null) {
        config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, currentSessionContextClass.getName());
    }
    configureGrailsJdbcTransactionFactory(config);
    config.afterPropertiesSet();
    return config;
}

From source file:com.htmlhifive.sync.resource.AbstractCrudSyncResource.java

/**
 * ???ID???????.// w  w  w.j av  a 2s  . com
 *
 * @param common ?
 * @return 
 */
private T createDeletedItem(ResourceItemCommonData common) {
    Class<T> itemType = getItemType();

    BeanWrapper deletedWrapper = PropertyAccessorFactory
            .forBeanPropertyAccess(BeanUtils.instantiateClass(itemType));
    deletedWrapper.setPropertyValue(getIdFieldName(), common.getTargetItemId());

    return itemType.cast(deletedWrapper.getWrappedInstance());
}

From source file:com.dhcc.framework.web.context.DhccContextLoader.java

/**
 * Customize the {@link ConfigurableWebApplicationContext} created by this
 * ContextLoader after config locations have been supplied to the context
 * but before the context is <em>refreshed</em>.
 * <p>The default implementation {@linkplain #determineContextInitializerClasses(ServletContext)
 * determines} what (if any) context initializer classes have been specified through
 * {@linkplain #CONTEXT_INITIALIZER_CLASSES_PARAM context init parameters} and
 * {@linkplain ApplicationContextInitializer#initialize invokes each} with the
 * given web application context.//from w  w w  .  j  a  va2s  . c o  m
 * <p>Any {@code ApplicationContextInitializers} implementing
 * {@link org.springframework.core.Ordered Ordered} or marked with @{@link
 * org.springframework.core.annotation.Order Order} will be sorted appropriately.
 * @param servletContext the current servlet context
 * @param applicationContext the newly created application context
 * @see #createWebApplicationContext(ServletContext, ApplicationContext)
 * @see #CONTEXT_INITIALIZER_CLASSES_PARAM
 * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext)
 */
protected void customizeContext(ServletContext servletContext,
        ConfigurableWebApplicationContext applicationContext) {
    List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses = determineContextInitializerClasses(
            servletContext);
    if (initializerClasses.size() == 0) {
        // no ApplicationContextInitializers have been declared -> nothing to do
        return;
    }

    Class<?> contextClass = applicationContext.getClass();
    ArrayList<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerInstances = new ArrayList<ApplicationContextInitializer<ConfigurableApplicationContext>>();

    for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
        Class<?> initializerContextClass = GenericTypeResolver.resolveTypeArgument(initializerClass,
                ApplicationContextInitializer.class);
        if (initializerContextClass != null) {
            Assert.isAssignable(initializerContextClass, contextClass,
                    String.format(
                            "Could not add context initializer [%s] as its generic parameter [%s] "
                                    + "is not assignable from the type of application context used by this "
                                    + "context loader [%s]: ",
                            initializerClass.getName(), initializerContextClass.getName(),
                            contextClass.getName()));
        }
        initializerInstances.add(BeanUtils.instantiateClass(initializerClass));
    }

    ConfigurableEnvironment env = applicationContext.getEnvironment();
    if (env instanceof ConfigurableWebEnvironment) {
        ((ConfigurableWebEnvironment) env).initPropertySources(servletContext, null);
    }

    Collections.sort(initializerInstances, new AnnotationAwareOrderComparator());
    for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : initializerInstances) {
        initializer.initialize(applicationContext);
    }
}

From source file:com.katsu.dwm.springframework.Loader.java

public void load(File jar, Properties properties) throws MalformedURLException {
    ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils
            .instantiateClass(XmlWebApplicationContext.class);
    //FIXME//  ww w .ja v  a2 s  .  c  o m
    wac.setId("test-context");
    wac.setParent(applicationContext);
    wac.setServletContext(((XmlWebApplicationContext) applicationContext).getServletContext());
    //wac.setServletConfig(((XmlWebApplicationContext) applicationContext).getServletConfig());
    //wac.setNamespace(((XmlWebApplicationContext) applicationContext).getNamespace());
    wac.setConfigLocation(properties.getProperty(LoaderConst.CONTEXT_LOCATION.getValue()));
    //wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));
    wac.refresh();

    wac.getServletContext().setAttribute("test-context", wac);
}

From source file:com.ms.commons.summer.web.handler.DataBinderUtil.java

/**
 * ?/*from  ww w .ja v a2s .c o m*/
 * 
 * @param method
 * @param model
 * @param request
 * @param response
 * @param c
 * @return
 */
@SuppressWarnings("unchecked")
public static Object[] getArgs(Method method, Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response, Class<?> c) {
    Class<?>[] paramTypes = method.getParameterTypes();
    Object[] args = new Object[paramTypes.length];
    Map<String, Object> argMap = new HashMap<String, Object>(args.length);
    Map<String, String> pathValues = null;
    PathPattern pathPattern = method.getAnnotation(PathPattern.class);
    if (pathPattern != null) {
        String path = request.getRequestURI();
        int index = path.lastIndexOf('.');
        if (index != -1) {
            path = path.substring(0, index);
            String[] patterns = pathPattern.patterns();
            pathValues = getPathValues(patterns, path);
        }
    }
    MapBindingResult errors = new MapBindingResult(argMap, "");
    ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
    for (int i = 0; i < paramTypes.length; i++) {
        Class<?> paramType = paramTypes[i];

        MethodParameter methodParam = new MethodParameter(method, i);
        methodParam.initParameterNameDiscovery(parameterNameDiscoverer);
        GenericTypeResolver.resolveParameterType(methodParam, c.getClass());

        String paramName = methodParam.getParameterName();
        // map
        if (Map.class.isAssignableFrom(paramType)) {
            args[i] = model;
        }
        // HttpServletRequest
        else if (HttpServletRequest.class.isAssignableFrom(paramType)) {
            args[i] = request;
        }
        // HttpServletResponse
        else if (HttpServletResponse.class.isAssignableFrom(paramType)) {
            args[i] = response;
        }
        // HttpSession
        else if (HttpSession.class.isAssignableFrom(paramType)) {
            args[i] = request.getSession();
        }
        // Errors
        else if (Errors.class.isAssignableFrom(paramType)) {
            args[i] = errors;
        }
        // MultipartFile
        else if (MultipartFile.class.isAssignableFrom(paramType)) {
            MultipartFile[] files = resolveMultipartFiles(request, errors, paramName);
            if (files != null && files.length > 0) {
                args[i] = files[0];
            }
        }
        // MultipartFile[]
        else if (MultipartFile[].class.isAssignableFrom(paramType)) {
            args[i] = resolveMultipartFiles(request, errors, paramName);
        } else {
            // ??
            if (BeanUtils.isSimpleProperty(paramType)) {
                SimpleTypeConverter converter = new SimpleTypeConverter();
                Object value;
                // ?
                if (paramType.isArray()) {
                    value = request.getParameterValues(paramName);
                } else {
                    Object[] parameterAnnotations = methodParam.getParameterAnnotations();
                    value = null;
                    if (parameterAnnotations != null && parameterAnnotations.length > 0) {
                        if (pathValues != null && pathValues.size() > 0) {
                            for (Object object : parameterAnnotations) {
                                if (PathVariable.class.isInstance(object)) {
                                    PathVariable pv = (PathVariable) object;
                                    if (StringUtils.isEmpty(pv.value())) {
                                        value = pathValues.get(paramName);
                                    } else {
                                        value = pathValues.get(pv.value());
                                    }
                                    break;
                                }
                            }
                        }
                    } else {
                        value = request.getParameter(paramName);
                    }
                }
                try {
                    args[i] = converter.convertIfNecessary(value, paramType, methodParam);
                    model.put(paramName, args[i]);
                } catch (TypeMismatchException e) {
                    errors.addError(new FieldError(paramName, paramName, e.getMessage()));
                }
            } else {
                // ???POJO
                if (paramType.isArray()) {
                    ObjectArrayDataBinder binder = new ObjectArrayDataBinder(paramType.getComponentType(),
                            paramName);
                    args[i] = binder.bind(request);
                    model.put(paramName, args[i]);
                } else {
                    Object bindObject = BeanUtils.instantiateClass(paramType);
                    SummerServletRequestDataBinder binder = new SummerServletRequestDataBinder(bindObject,
                            paramName);
                    binder.bind(request);
                    BindException be = new BindException(binder.getBindingResult());
                    List<FieldError> fieldErrors = be.getFieldErrors();
                    for (FieldError fieldError : fieldErrors) {
                        errors.addError(fieldError);
                    }
                    args[i] = binder.getTarget();
                    model.put(paramName, args[i]);
                }
            }
        }
    }
    return args;
}

From source file:com.workingmouse.webservice.axis.SpringAxisServlet.java

private ConfigurableWebApplicationContext createContextInstance() {
    return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(getContextClass());
}

From source file:gov.nih.nci.cabig.caaers.domain.repository.ajax.StudySearchableAjaxableDomainObjectRepository.java

/**
 * Find studies./*  w w w .j a v a 2 s  .  co  m*/
 *
 * @param query the query
 * @param type the type
 * @param text the text
 * @param searchInCOPPA the search in coppa
 * @return the list
 */
@Transactional(readOnly = false)
public List<T> findStudies(final AbstractAjaxableDomainObjectQuery query, String type, String text,
        boolean searchInCOPPA) {

    List<Object[]> objects = studyRepository.search(query, type, text, searchInCOPPA);
    Map<Integer, T> existingStudyMap = new LinkedHashMap<Integer, T>();

    for (Object[] o : objects) {

        T studySearchableAjaxableDomainObject = existingStudyMap.get((Integer) o[0]);

        if (studySearchableAjaxableDomainObject == null) {
            studySearchableAjaxableDomainObject = (T) BeanUtils.instantiateClass(getObjectClass());
            studySearchableAjaxableDomainObject.setId((Integer) o[0]);
            studySearchableAjaxableDomainObject.setShortTitle((String) o[1]);
            studySearchableAjaxableDomainObject.setPrimaryIdentifierValue((String) o[2]);
            studySearchableAjaxableDomainObject.setPhaseCode((String) o[4]);
            studySearchableAjaxableDomainObject.setStatus((String) o[5]);
            studySearchableAjaxableDomainObject.setExternalId((String) o[6]);
            //                studySearchableAjaxableDomainObject.setPrimarySponsorCode((String)o[7]);

            existingStudyMap.put(studySearchableAjaxableDomainObject.getId(),
                    studySearchableAjaxableDomainObject);

        } else {
            //update the primary identifier
            //if(BooleanUtils.toBoolean((String)o[3])){
            if (o[3] != null && (Boolean) o[3]) {
                studySearchableAjaxableDomainObject.setPrimaryIdentifierValue((String) o[2]);
            }
        }
    }
    return new ArrayList<T>(existingStudyMap.values());

}

From source file:grails.util.GrailsClassUtils.java

/**
 * Returns the value of the specified property and type from an instance of the specified Grails class
 *
 * @param clazz The name of the class which contains the property
 * @param propertyName The property name
 * @param propertyType The property type
 *
 * @return The value of the property or null if none exists
 *///from   w w  w  .  j av a  2  s. co m
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Object getPropertyValueOfNewInstance(Class clazz, String propertyName, Class<?> propertyType) {
    // validate
    if (clazz == null || !StringUtils.hasText(propertyName)) {
        return null;
    }

    try {
        return getPropertyOrStaticPropertyOrFieldValue(BeanUtils.instantiateClass(clazz), propertyName);
    } catch (BeanInstantiationException e) {
        return null;
    }
}