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.codehaus.groovy.grails.orm.hibernate.ConfigurableLocalSessionFactoryBean.java

/**
 * Overrides default behaviour to allow for a configurable configuration class.
 *//*ww w . ja  v a  2 s  .  c  o m*/
@Override
protected Configuration newConfiguration() {
    ClassLoader cl = classLoader != null ? classLoader : Thread.currentThread().getContextClassLoader();
    if (configClass == null) {
        try {
            configClass = cl
                    .loadClass("org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration");
        } catch (Throwable e) {
            // probably not Java 5 or missing some annotation jars, use default
            configClass = DefaultGrailsDomainConfiguration.class;
        }
    }
    Object config = BeanUtils.instantiateClass(configClass);
    if (config instanceof GrailsDomainConfiguration) {
        GrailsDomainConfiguration grailsConfig = (GrailsDomainConfiguration) config;
        grailsConfig.setGrailsApplication(grailsApplication);
        grailsConfig.setSessionFactoryBeanName(sessionFactoryBeanName);
        grailsConfig.setDataSourceName(dataSourceName);
    }
    if (currentSessionContextClass != null) {
        ((Configuration) config).setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS,
                currentSessionContextClass.getName());
        // don't allow Spring's LocaalSessionFactoryBean to override setting
        setExposeTransactionAwareSessionFactory(false);
    }
    return (Configuration) config;
}

From source file:org.codehaus.groovy.grails.web.mapping.DefaultUrlMappingEvaluator.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public List<UrlMapping> evaluateMappings(Class theClass) {
    GroovyObject obj = (GroovyObject) BeanUtils.instantiateClass(theClass);

    if (obj instanceof Script) {
        Script script = (Script) obj;/* w w  w. j  ava 2 s.  c o  m*/
        Binding b = new Binding();

        MappingCapturingClosure closure = new MappingCapturingClosure(script);
        b.setVariable("mappings", closure);
        script.setBinding(b);

        script.run();

        Closure mappings = closure.getMappings();

        Binding binding = script.getBinding();
        return evaluateMappings(script, mappings, binding);
    }

    throw new UrlMappingException("Unable to configure URL mappings for class [" + theClass
            + "]. A URL mapping must be an instance of groovy.lang.Script.");
}

From source file:org.eclipse.gemini.blueprint.extender.internal.support.ExtenderConfiguration.java

protected void addDefaultDependencyFactories() {
    boolean debug = log.isDebugEnabled();

    // default JDK 1.4 processor
    dependencyFactories.add(0, new MandatoryImporterDependencyFactory());

    // load through reflection the dependency and injection processors if running on JDK 1.5 and annotation
    // processing is enabled
    if (processAnnotation) {
        // dependency processor
        Class<?> annotationProcessor = null;
        try {/*from ww w  .j  a  v a  2  s. c om*/
            annotationProcessor = Class.forName(ANNOTATION_DEPENDENCY_FACTORY, false,
                    ExtenderConfiguration.class.getClassLoader());
        } catch (ClassNotFoundException cnfe) {
            log.warn("Spring DM annotation package not found, annotation processing disabled.");
            log.debug("Spring DM annotation package not found, annotation processing disabled.", cnfe);
            return;
        }
        Object processor = BeanUtils.instantiateClass(annotationProcessor);
        Assert.isInstanceOf(OsgiServiceDependencyFactory.class, processor);
        dependencyFactories.add(1, (OsgiServiceDependencyFactory) processor);

        if (debug)
            log.debug("Succesfully loaded annotation dependency processor [" + ANNOTATION_DEPENDENCY_FACTORY
                    + "]");

        // add injection processor (first in line)
        postProcessors.add(0, new OsgiAnnotationPostProcessor());
        log.info("Spring-DM annotation processing enabled");
    } else {
        if (debug) {
            log.debug("Spring-DM annotation processing disabled; [" + ANNOTATION_DEPENDENCY_FACTORY
                    + "] not loaded");
        }
    }

}

From source file:org.eclipse.gemini.blueprint.extender.internal.support.OsgiAnnotationPostProcessor.java

public void postProcessBeanFactory(BundleContext bundleContext, ConfigurableListableBeanFactory beanFactory)
        throws BeansException, OsgiException {

    Bundle bundle = bundleContext.getBundle();
    try {//from  ww w. j a v a2  s. co  m
        // Try and load the annotation code using the bundle classloader
        Class<?> annotationBppClass = bundle.loadClass(ANNOTATION_BPP_CLASS);
        // instantiate the class
        final BeanPostProcessor annotationBeanPostProcessor = (BeanPostProcessor) BeanUtils
                .instantiateClass(annotationBppClass);

        // everything went okay so configure the BPP and add it to the BF
        ((BeanFactoryAware) annotationBeanPostProcessor).setBeanFactory(beanFactory);
        ((BeanClassLoaderAware) annotationBeanPostProcessor)
                .setBeanClassLoader(beanFactory.getBeanClassLoader());
        ((BundleContextAware) annotationBeanPostProcessor).setBundleContext(bundleContext);
        beanFactory.addBeanPostProcessor(annotationBeanPostProcessor);
    } catch (ClassNotFoundException exception) {
        log.info("Spring-DM annotation package could not be loaded from bundle ["
                + OsgiStringUtils.nullSafeNameAndSymName(bundle) + "]; annotation processing disabled...");
        if (log.isDebugEnabled())
            log.debug("Cannot load annotation injection processor", exception);
    }
}

From source file:org.grails.datastore.gorm.jdbc.DataSourceBuilder.java

public DataSource build() {
    Class<? extends DataSource> type = getType();
    DataSource result = BeanUtils.instantiateClass(type);
    maybeGetDriverClassName();//from w w  w .  j  a  va2 s .co  m
    bind(result);
    return result;
}

From source file:org.nextframework.controller.ExtendedBeanWrapper.java

/**
 * Create new BeanWrapperImpl, wrapping a new instance of the specified class.
 * @param clazz class to instantiate and wrap
 */// ww w  .  j  av a2  s .  c  o  m
public ExtendedBeanWrapper(Class clazz) {
    this();
    setWrappedInstance(BeanUtils.instantiateClass(clazz));
}

From source file:org.nextframework.controller.MultiActionController.java

private <E> E getCommand(WebRequestContext request, Class<E> clazz, String name) throws Exception {
    E command = (E) BeanUtils.instantiateClass(clazz);
    onInstantiateNewCommand(command, null, false);
    return command;
}

From source file:org.nextframework.controller.MultiActionController.java

public <E> E instantiateNewSessionCommand(WebRequestContext request, Class<E> clazz, String name) {
    E sessionCommand;//from   w ww  .  j a  v  a 2 s  .  c  om
    sessionCommand = (E) BeanUtils.instantiateClass(clazz);
    request.getSession().setAttribute(name, sessionCommand);
    onInstantiateNewCommand(sessionCommand, name, true);
    return sessionCommand;
}

From source file:org.red5.server.war.MainServlet.java

/**
 * Main entry point for the Red5 Server as a war
 *//*from w  w w.ja v  a2  s  .  co  m*/
// Notification that the web application is ready to process requests
public void contextInitialized(ServletContextEvent sce) {
    System.setProperty("red5.deployment.type", "war");

    if (null != servletContext) {
        return;
    }
    servletContext = sce.getServletContext();
    String prefix = servletContext.getRealPath("/");

    long time = System.currentTimeMillis();

    logger.info("RED5 Server (http://www.osflash.org/red5)");
    logger.info("Loading red5 global context from: " + red5Config);
    logger.info("Path: " + prefix);

    try {
        // Detect root of Red5 configuration and set as system property
        String root;
        String classpath = System.getProperty("java.class.path");
        File fp = new File(prefix + red5Config);
        fp = fp.getCanonicalFile();
        if (!fp.isFile()) {
            // Given file does not exist, search it on the classpath
            String[] paths = classpath.split(System.getProperty("path.separator"));
            for (String element : paths) {
                fp = new File(element + "/" + red5Config);
                fp = fp.getCanonicalFile();
                if (fp.isFile()) {
                    break;
                }
            }
        }
        if (!fp.isFile()) {
            throw new Exception(
                    "could not find configuration file " + red5Config + " on your classpath " + classpath);
        }

        root = fp.getAbsolutePath();
        root = root.replace('\\', '/');
        int idx = root.lastIndexOf('/');
        root = root.substring(0, idx);
        // update classpath
        System.setProperty("java.class.path",
                classpath + File.pathSeparatorChar + root + File.pathSeparatorChar + root + "/classes");
        logger.debug("New classpath: " + System.getProperty("java.class.path"));
        // set configuration root
        System.setProperty("red5.config_root", root);
        logger.info("Setting configuation root to " + root);

        // Setup system properties so they can be evaluated
        Properties props = new Properties();
        props.load(new FileInputStream(root + "/red5.properties"));
        for (Object o : props.keySet()) {
            String key = (String) o;
            if (StringUtils.isNotBlank(key)) {
                System.setProperty(key, props.getProperty(key));
            }
        }

        // Store root directory of Red5
        idx = root.lastIndexOf('/');
        root = root.substring(0, idx);
        if (System.getProperty("file.separator").equals("/")) {
            // Workaround for linux systems
            root = "/" + root;
        }
        System.setProperty("red5.root", root);
        logger.info("Setting Red5 root to " + root);

        Class contextClass = org.springframework.web.context.support.XmlWebApplicationContext.class;
        ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) BeanUtils
                .instantiateClass(contextClass);

        String[] strArray = servletContext.getInitParameter(ContextLoader.CONFIG_LOCATION_PARAM)
                .split("[,\\s]");
        logger.info("Config location files: " + strArray.length);
        applicationContext.setConfigLocations(strArray);
        applicationContext.setServletContext(servletContext);
        applicationContext.refresh();

        // set web application context as an attribute of the servlet
        // context so that it may be located via Springs
        // WebApplicationContextUtils
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                applicationContext);

        ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
        // register default
        // add the context to the parent
        factory.registerSingleton("default.context", applicationContext);

    } catch (Throwable e) {
        logger.error("", e);
    }

    long startupIn = System.currentTimeMillis() - time;
    logger.info("Startup done in: " + startupIn + " ms");

}

From source file:org.shept.org.springframework.web.servlet.mvc.delegation.DelegatingController.java

/**
 * Create a new command object of the given class.
 * <p>This implementation uses <code>BeanUtils.instantiateClass</code>,
 * so commands need to have public no-arg constructors.
 * Subclasses can override this implementation if desired.
 * @throws Exception if the command object could not be instantiated
 * @see org.springframework.beans.BeanUtils#instantiateClass(Class)
 *//* ww w.j av  a 2 s. c om*/
protected Object getCommandObject(HttpServletRequest request, Class clazz) throws Exception {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating new command of class [" + clazz.getName() + "]");
    }
    return BeanUtils.instantiateClass(clazz);
}