Example usage for org.springframework.beans.factory.config AutowireCapableBeanFactory AUTOWIRE_BY_NAME

List of usage examples for org.springframework.beans.factory.config AutowireCapableBeanFactory AUTOWIRE_BY_NAME

Introduction

In this page you can find the example usage for org.springframework.beans.factory.config AutowireCapableBeanFactory AUTOWIRE_BY_NAME.

Prototype

int AUTOWIRE_BY_NAME

To view the source code for org.springframework.beans.factory.config AutowireCapableBeanFactory AUTOWIRE_BY_NAME.

Click Source Link

Document

Constant that indicates autowiring bean properties by name (applying to all bean property setters).

Usage

From source file:org.codehaus.groovy.grails.web.context.GrailsConfigUtils.java

/**
 * Executes Grails bootstrap classes/*from  w  w w  .  j a  v  a 2s . co m*/
 *
 * @param application The Grails ApplicationContext instance
 * @param webContext The WebApplicationContext instance
 * @param servletContext The ServletContext instance
 */
public static void executeGrailsBootstraps(GrailsApplication application, WebApplicationContext webContext,
        ServletContext servletContext) {

    PersistenceContextInterceptor interceptor = null;
    String[] beanNames = webContext.getBeanNamesForType(PersistenceContextInterceptor.class);
    if (beanNames.length > 0) {
        interceptor = (PersistenceContextInterceptor) webContext.getBean(beanNames[0]);
    }

    if (interceptor != null) {
        interceptor.init();
    }
    // init the Grails application
    try {
        GrailsClass[] bootstraps = application.getArtefacts(BootstrapArtefactHandler.TYPE);
        for (GrailsClass bootstrap : bootstraps) {
            final GrailsBootstrapClass bootstrapClass = (GrailsBootstrapClass) bootstrap;
            final Object instance = bootstrapClass.getReferenceInstance();
            webContext.getAutowireCapableBeanFactory().autowireBeanProperties(instance,
                    AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
            bootstrapClass.callInit(servletContext);
        }
        if (interceptor != null) {
            interceptor.flush();
        }
    } finally {
        if (interceptor != null) {
            interceptor.destroy();
        }
    }
}

From source file:org.easyrec.plugin.cli.AbstractGeneratorCLI.java

@Override
protected int processCommandLineCall(final String[] args) {
    final Generator<GC, GS> generator = getGenerator();
    super.context.getAutowireCapableBeanFactory().autowireBeanProperties(generator,
            AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);

    List<GC> configurations = new LinkedList<GC>();

    CommandLineParser parser = new PosixParser();
    CommandLine commandLine;/*from w  w  w.  ja  v  a 2s .  c o m*/

    try {
        commandLine = parser.parse(options, args);
    } catch (ParseException e) {
        logger.warn("An error occurred!", e);

        usage();
        return -1;
    }

    boolean doUninstall = commandLine.hasOption('u');

    if (!commandLine.hasOption('t')) {
        List<TenantVO> tenants = tenantService.getAllTenants();

        for (TenantVO tenant : tenants) {
            GC configuration = generator.newConfiguration();
            configuration.setTenantId(tenant.getId());
            configuration.setConfigurationName(String.format("Configuration for tenant %d", tenant.getId()));

            configurations.add(configuration);
        }
    } else {
        String strTenants = commandLine.getOptionValue('t');

        if (strTenants.contains("-")) {
            String[] argParts = strTenants.split("-");

            if (argParts.length != 2) {
                usage();
                return -1;
            }

            int lowerBound = Integer.parseInt(argParts[0]);
            int upperBound = Integer.parseInt(argParts[1]);

            if (lowerBound > upperBound) {
                int tmp = lowerBound;
                lowerBound = upperBound;
                upperBound = tmp;
            }

            for (int i = lowerBound; i <= upperBound; i++) {
                GC configuration = generator.newConfiguration();
                configuration.setTenantId(i);
                configuration.setConfigurationName(String.format("Configuration for tenant %d", i));

                configurations.add(configuration);
            }
        } else if (strTenants.contains(",")) {
            String[] argParts = strTenants.split(",");

            for (String argPart : argParts) {
                int tenant = Integer.parseInt(argPart);

                GC configuration = generator.newConfiguration();
                configuration.setTenantId(tenant);
                configuration.setConfigurationName(String.format("Configuration for tenant %d", tenant));

                configurations.add(configuration);
            }
        } else {
            GC configuration = generator.newConfiguration();
            configuration.setTenantId(Integer.parseInt(strTenants));
            configuration.setConfigurationName(
                    String.format("Configuration for tenant %d", configuration.getTenantId()));

            configurations.add(configuration);
        }
    }

    final ExecutableObserver executableObserver = new ExecutableObserver();
    final PluginObserver pluginObserver = new PluginObserver();

    generator.getExecutableObserverRegistry().addObserver(executableObserver);
    generator.getPluginObserverRegistry().addObserver(pluginObserver);

    generator.install(true);

    for (GC configuration : configurations) {
        generator.initialize();

        generator.setConfiguration(configuration);

        System.out.println("##################################################");
        System.out.println(String.format("[%s] Starting generator with configuration: \"%s\"",
                new Date().toString(), configuration.getConfigurationName()));
        System.out.println("##################################################");

        try {
            generator.execute();
        } catch (Exception e) {
            logger.warn("An error occurred!", e);
        }

        // need to sleep 1s to avoid duplicate keys
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            logger.warn("An error occurred!", e);
        }

        generator.cleanup();
    }

    if (doUninstall)
        generator.uninstall();

    return 0;
}

From source file:org.easyrec.plugin.container.PluginRegistry.java

private void installGenerator(final URI pluginId, final Version version, final PluginVO plugin,
        final ClassPathXmlApplicationContext cax,
        final Generator<GeneratorConfiguration, GeneratorStatistics> generator) {
    cax.getAutowireCapableBeanFactory().autowireBeanProperties(generator,
            AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);

    if (generator.getConfiguration() == null) {
        GeneratorConfiguration generatorConfiguration = generator.newConfiguration();
        generator.setConfiguration(generatorConfiguration);
    }/*from   www .j a  v a  2  s.c o m*/

    if (LifecyclePhase.NOT_INSTALLED.toString().equals(plugin.getState()))
        generator.install(true);
    else
        generator.install(false);

    pluginDAO.updatePluginState(pluginId, version, LifecyclePhase.INSTALLED.toString());

    generator.initialize();
    generators.put(generator.getId(), generator);
    contexts.put(generator.getId(), cax);
    logger.info("registered plugin " + generator.getSourceType());
    pluginDAO.updatePluginState(pluginId, version, LifecyclePhase.INITIALIZED.toString());
}

From source file:org.easyrec.plugin.container.PluginRegistry.java

@SuppressWarnings({ "unchecked" })
public PluginVO checkPlugin(byte[] file) throws Exception {
    PluginVO plugin;/*from   w  w  w .  j a  va  2 s  .  c  o  m*/
    FileOutputStream fos = null;
    URLClassLoader ucl;
    ClassPathXmlApplicationContext cax = null;
    File tmpFile = null;

    try {
        if (file == null)
            throw new IllegalArgumentException("Passed file must not be null!");

        tmpFile = File.createTempFile("plugin", null);
        tmpFile.deleteOnExit();

        fos = new FileOutputStream(tmpFile);
        fos.write(file);
        fos.close();

        // check if plugin is valid
        ucl = new URLClassLoader(new URL[] { tmpFile.toURI().toURL() }, this.getClass().getClassLoader());

        if (ucl.getResourceAsStream(DEFAULT_PLUGIN_CONFIG_FILE) != null) {
            cax = new ClassPathXmlApplicationContext(new String[] { DEFAULT_PLUGIN_CONFIG_FILE }, false,
                    appContext);
            cax.setClassLoader(ucl);
            logger.info("Classloader: " + cax.getClassLoader());
            cax.refresh();

            Map<String, GeneratorPluginSupport> beans = cax.getBeansOfType(GeneratorPluginSupport.class);

            if (beans.isEmpty()) {
                logger.debug("No class implementing a generator could be found. Plugin rejected!");
                throw new Exception("No class implementing a generator could be found. Plugin rejected!");
            }

            Generator<GeneratorConfiguration, GeneratorStatistics> generator = beans.values().iterator().next();

            logger.info(String.format("Plugin successfully validated! class: %s name: %s, id: %s",
                    generator.getClass(), generator.getDisplayName(), generator.getId()));

            cax.getAutowireCapableBeanFactory().autowireBeanProperties(generator,
                    AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);

            plugin = new PluginVO(generator.getDisplayName(), generator.getId().getUri(),
                    generator.getId().getVersion(), LifecyclePhase.NOT_INSTALLED.toString(), file, null);

            if (tmpFile.delete())
                logger.info("tmpFile deleted successfully");

            return plugin;
        } else { // config file not found
            logger.debug("No valid config file found in the supplied .jar file. Plugin rejected!");
            throw new Exception("No valid config file found in the supplied .jar file. Plugin rejected!");
        }
    } catch (Exception e) {
        logger.error("An Exception occurred while checking the plugin!", e);

        throw e;
    } finally {
        if (fos != null)
            fos.close();

        if ((cax != null) && (!cax.isActive()))
            cax.close();

        if (tmpFile != null)
            try {
                if (!tmpFile.delete())
                    logger.warn("could not delete tmpFile");
            } catch (SecurityException se) {
                logger.error("Could not delete temporary file! Please check permissions!", se);
            }
    }
}

From source file:org.projectforge.test.TestConfiguration.java

public <T> T getAndAutowireBean(final String name, final Class<T> requiredType) {
    final T obj = getBean(name, requiredType);
    autowire(obj, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME);
    return obj;/*  w ww  . ja  v  a2 s  .  co m*/
}

From source file:org.projectforge.test.TestConfiguration.java

/**
 * Init and reinitialise context for each run
 *///w w w.  jav  a  2 s .  com
protected void initCtx() throws BeansException {
    if (ctx == null) {
        log.info("Initializing context: "
                + org.projectforge.common.StringHelper.listToString(", ", contextFiles));
        try {
            // Build spring context
            ctx = new ClassPathXmlApplicationContext(contextFiles);
            ctx.getBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME,
                    false);

            final PropertyDataSource ds = ctx.getBean("dataSource", PropertyDataSource.class);
            this.databaseUrl = ds.getUrl();
            final JdbcTemplate jdbc = new JdbcTemplate(ds);
            try {
                jdbc.execute("CHECKPOINT DEFRAG");
            } catch (final org.springframework.jdbc.BadSqlGrammarException ex) {
                // ignore
            }
            final LocalSessionFactoryBean localSessionFactoryBean = (LocalSessionFactoryBean) ctx
                    .getBean("&sessionFactory");
            HibernateUtils.setConfiguration(localSessionFactoryBean.getConfiguration());
        } catch (final Throwable ex) {
            log.error(ex.getMessage(), ex);
            throw new RuntimeException(ex);
        }
    } else {
        // Get a new HibernateTemplate each time
        ctx.getBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
    }
    final Configuration cfg = ctx.getBean("configuration", Configuration.class);
    cfg.setBeanFactory(ctx.getBeanFactory()); // Bean factory need to be set.
}

From source file:org.projectforge.web.meb.SMSReceiverServlet.java

@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    log.debug("Start doPost");
    // https://projectforge.micromata.de/secure/SMSReceiver?key=<key>&date=20101105171233&sender=01701891142&msg=Hallo...
    req.setCharacterEncoding("UTF-8");
    final String key = req.getParameter("key");
    final String expectedKey = ConfigXml.getInstance().getReceiveSmsKey();
    if (StringUtils.isBlank(expectedKey) == true) {
        log.warn(// ww  w.  j av  a  2  s  .c  o  m
                "Servlet call for receiving sms ignored because receiveSmsKey is not given in config.xml file.");
        response(resp, "NOT YET CONFIGURED");
        return;
    }
    if (expectedKey.equals(key) == false) {
        log.warn("Servlet call for receiving sms ignored because receiveSmsKey does not match given key: "
                + key);
        response(resp, "DENIED");
        return;
    }
    final String dateString = req.getParameter("date");
    if (StringUtils.isBlank(dateString) == true) {
        log.warn("Servlet call for receiving sms ignored because parameter 'date' is not given.");
        response(resp, "Missing parameter 'date'.");
        return;
    }
    final String sender = req.getParameter("sender");
    if (StringUtils.isBlank(sender) == true) {
        log.warn("Servlet call for receiving sms ignored because parameter 'sender' is not given.");
        response(resp, "Missing parameter 'sender'.");
        return;
    }
    final String msg = req.getParameter("msg");
    if (StringUtils.isBlank(msg) == true) {
        log.warn("Servlet call for receiving sms ignored because parameter 'msg' is not given.");
        response(resp, "Missing parameter 'msg'.");
        return;
    }
    final Date date = MebDao.parseDate(dateString);
    if (date == null) {
        log.warn("Servlet call for receiving sms ignored because couln't parse parameter 'date'.");
        response(resp, "Unsupported date format.");
        return;
    }
    final ConfigurableListableBeanFactory beanFactory = Configuration.getInstance().getBeanFactory();
    beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
    MebEntryDO entry = new MebEntryDO();
    entry.setDate(date);
    entry.setSender(sender);
    entry.setMessage(msg);
    log.info("Servlet-call: date=[" + date + "], sender=[" + sender + "]");
    mebDao.checkAndAddEntry(entry, "SERVLET");
    response(resp, "OK");
}

From source file:org.projectforge.web.wicket.WicketApplication.java

@Override
protected void init() {
    super.init();
    // Own error page for deployment mode and UserException and AccessException.
    getRequestCycleListeners().add(new AbstractRequestCycleListener() {
        /**/*from ww  w. j ava 2 s. c  o m*/
         * Log only non ProjectForge exceptions.
         * @see org.apache.wicket.request.cycle.AbstractRequestCycleListener#onException(org.apache.wicket.request.cycle.RequestCycle,
         *      java.lang.Exception)
         */
        @Override
        public IRequestHandler onException(final RequestCycle cycle, final Exception ex) {
            // in case of expired session, please redirect to home page
            if (ex instanceof PageExpiredException) {
                return new RenderPageRequestHandler(new PageProvider(getHomePage()));
            }
            final Throwable rootCause = ExceptionHelper.getRootCause(ex);
            // log.error(rootCause.getMessage(), ex);
            // if (rootCause instanceof ProjectForgeException == false) {
            // return super.onException(cycle, ex);
            // }
            // return null;
            if (isDevelopmentSystem() == true) {
                log.error(ex.getMessage(), ex);
                if (rootCause instanceof SQLException) {
                    SQLException next = (SQLException) rootCause;
                    while ((next = next.getNextException()) != null) {
                        log.error(next.getMessage(), next);
                    }
                }
                return super.onException(cycle, ex);
            } else {
                // Show always this error page in production mode:
                return new RenderPageRequestHandler(new PageProvider(new ErrorPage(ex)));
            }
        }
    });

    getApplicationSettings().setDefaultMaximumUploadSize(Bytes.megabytes(100));
    getMarkupSettings().setDefaultMarkupEncoding("utf-8");
    final MyAuthorizationStrategy authStrategy = new MyAuthorizationStrategy();
    getSecuritySettings().setAuthorizationStrategy(authStrategy);
    getSecuritySettings().setUnauthorizedComponentInstantiationListener(authStrategy);
    // Prepend the resource bundle for overwriting some Wicket default localizations (such as StringValidator.*)
    getResourceSettings().getStringResourceLoaders().add(new BundleStringResourceLoader(RESOURCE_BUNDLE_NAME));
    getResourceSettings().setThrowExceptionOnMissingResource(false); // Don't throw MissingResourceException for missing i18n keys.
    getApplicationSettings().setPageExpiredErrorPage(PageExpiredPage.class); // Don't show expired page.
    // getSessionSettings().setMaxPageMaps(20); // Map up to 20 pages per session (default is 5).
    getComponentInstantiationListeners().add(new SpringComponentInjector(this));
    getApplicationSettings().setInternalErrorPage(ErrorPage.class);
    // getRequestCycleSettings().setGatherExtendedBrowserInfo(true); // For getting browser width and height.

    // Select2:
    // final ApplicationSettings select2Settings = ApplicationSettings.get();
    // select2Settings.setIncludeJavascript(false);

    final XmlWebApplicationContext webApplicationContext = (XmlWebApplicationContext) WebApplicationContextUtils
            .getWebApplicationContext(getServletContext());
    final ConfigurableListableBeanFactory beanFactory = webApplicationContext.getBeanFactory();
    beanFactory.autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
    final LocalSessionFactoryBean localSessionFactoryBean = (LocalSessionFactoryBean) beanFactory
            .getBean("&sessionFactory");

    // if ("true".equals(System.getProperty(SYSTEM_PROPERTY_HSQLDB_18_UPDATE)) == true) {
    // try {
    // log.info("Send SHUTDOWN COMPACT to upgrade data-base version:");
    // final DataSource dataSource = (DataSource)beanFactory.getBean("dataSource");
    // dataSource.getConnection().createStatement().execute("SHUTDOWN COMPACT");
    // log.fatal("************ PLEASE RESTART APPLICATION NOW FOR PROPER INSTALLATION !!!!!!!!!!!!!! ************");
    // return;
    // } catch (final SQLException ex) {
    // log.fatal("Data-base SHUTDOWN COMPACT failed: " + ex.getMessage());
    // }
    // }
    final org.hibernate.cfg.Configuration hibernateConfiguration = localSessionFactoryBean.getConfiguration();
    HibernateUtils.setConfiguration(hibernateConfiguration);
    final ServletContext servletContext = getServletContext();
    final String configContextPath = configXml.getServletContextPath();
    String contextPath;
    if (StringUtils.isBlank(configContextPath) == true) {
        contextPath = servletContext.getContextPath();
        configXml.setServletContextPath(contextPath);
    } else {
        contextPath = configContextPath;
    }
    log.info("Using servlet context path: " + contextPath);
    if (configuration.getBeanFactory() == null) {
        configuration.setBeanFactory(beanFactory);
    }
    configuration.setConfigurationDao(configurationDao);
    SystemInfoCache.internalInitialize(systemInfoCache);
    WicketUtils.setContextPath(contextPath);
    UserFilter.initialize(userDao, contextPath);
    if (this.wicketApplicationFilter != null) {
        this.wicketApplicationFilter.setApplication(this);
    } else {
        throw new RuntimeException("this.wicketApplicationFilter is null");
    }
    daoRegistry.init();

    final PluginsRegistry pluginsRegistry = PluginsRegistry.instance();
    pluginsRegistry.set(beanFactory, getResourceSettings());
    pluginsRegistry.set(systemUpdater);
    pluginsRegistry.initialize();

    for (final Map.Entry<String, Class<? extends WebPage>> mountPage : WebRegistry.instance().getMountPages()
            .entrySet()) {
        final String path = mountPage.getKey();
        final Class<? extends WebPage> pageClass = mountPage.getValue();
        mountPage(path, pageClass);
        mountedPages.put(pageClass, path);
    }
    if (isDevelopmentSystem() == true) {
        if (isStripWicketTags() == true) {
            log.info("Strip Wicket tags also in development mode at default (see context.xml).");
            Application.get().getMarkupSettings().setStripWicketTags(true);
        }
        getDebugSettings().setOutputMarkupContainerClassName(true);
    }
    log.info("Default TimeZone is: " + TimeZone.getDefault());
    if ("UTC".equals(TimeZone.getDefault().getID()) == false) {
        for (final String str : UTC_RECOMMENDED) {
            log.fatal(str);
        }
        for (final String str : UTC_RECOMMENDED) {
            System.err.println(str);
        }
    }
    log.info("user.timezone is: " + System.getProperty("user.timezone"));
    cronSetup.initialize();
    log.info(AppVersion.APP_ID + " " + AppVersion.NUMBER + " (" + AppVersion.RELEASE_TIMESTAMP
            + ") initialized.");

    PFUserContext.setUser(DatabaseUpdateDao.__internalGetSystemAdminPseudoUser()); // Logon admin user.
    if (systemUpdater.isUpdated() == false) {
        // Force redirection to update page:
        UserFilter.setUpdateRequiredFirst(true);
    }
    PFUserContext.setUser(null);
    UserXmlPreferencesCache.setInternalInstance(userXmlPreferencesCache);
    LoginHandler loginHandler;
    if (StringUtils.isNotBlank(configXml.getLoginHandlerClass()) == true) {
        loginHandler = (LoginHandler) BeanHelper.newInstance(configXml.getLoginHandlerClass());
    } else {
        loginHandler = new LoginDefaultHandler();
    }
    if (loginHandler == null) {
        log.error("Can't load login handler '" + configXml.getLoginHandlerClass()
                + "'. No login will be possible!");
    } else {
        loginHandler.initialize();
        Login.getInstance().setLoginHandler(loginHandler);
    }
    try {
        StorageClient.getInstance(); // Initialize storage
    } catch (final Exception ex) {
        log.error(ex.getMessage(), ex);
    }
    getPageSettings().setRecreateMountedPagesAfterExpiry(false);

    // initialize ical4j to be more "relaxed"
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_PARSING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_UNFOLDING, true);
    CompatibilityHints.setHintEnabled(CompatibilityHints.KEY_RELAXED_VALIDATION, true);

    // initialize styles compiler
    try {
        final LessWicketApplicationInstantiator lessInstantiator = new LessWicketApplicationInstantiator(this,
                "styles", "projectforge.less", "projectforge.css");
        lessInstantiator.instantiate();
    } catch (final Exception e) {
        log.error("Unable to instantiate wicket less compiler", e);
    }
}

From source file:org.sparkcommerce.core.web.catalog.taglib.GoogleAnalyticsTag.java

@Override
public void doTag() throws JspException, IOException {
    JspWriter out = getJspContext().getOut();
    String webPropertyId = getWebPropertyId();

    if (webPropertyId == null) {
        ServletContext sc = ((PageContext) getJspContext()).getServletContext();
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(sc);
        context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
                AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
    }/*from w  ww.  ja v  a2  s.  c o m*/

    if (webPropertyId.equals("UA-XXXXXXX-X")) {
        LOG.warn(
                "googleAnalytics.webPropertyId has not been overridden in a custom property file. Please set this in order to properly use the Google Analytics tag");
    }

    out.println(analytics(webPropertyId, order));
    super.doTag();
}

From source file:org.springframework.beans.factory.DefaultListableBeanFactoryTests.java

@Test
public void testAutowireBeanByName() {
    DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
    RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
    lbf.registerBeanDefinition("spouse", bd);
    DependenciesBean bean = (DependenciesBean) lbf.autowire(DependenciesBean.class,
            AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, true);
    TestBean spouse = (TestBean) lbf.getBean("spouse");
    assertEquals(spouse, bean.getSpouse());
    assertTrue(BeanFactoryUtils.beanOfType(lbf, TestBean.class) == spouse);
}