List of usage examples for org.springframework.context ConfigurableApplicationContext getBean
Object getBean(String name) throws BeansException;
From source file:org.fao.geonet.guiservices.csw.Set2.java
private void saveCswCapabilitiesInfo(MultiValueMap parameters) throws Exception { final ConfigurableApplicationContext context = ApplicationContextHolder.get(); LanguageRepository languageRepository = context.getBean(LanguageRepository.class); CswCapabilitiesInfoFieldRepository cswCapabilitiesInfoFieldRepository = context .getBean(CswCapabilitiesInfoFieldRepository.class); final List<Language> langs = languageRepository.findAll(); for (Language lang : langs) { CswCapabilitiesInfo cswCapInfo = cswCapabilitiesInfoFieldRepository .findCswCapabilitiesInfo(lang.getId()); String langId = lang.getId(); if (parameters.get("csw.title_" + langId) != null) { String title = (String) ((LinkedList) parameters.get("csw.title_" + langId)).get(0); if (StringUtils.isNotEmpty(title)) { cswCapInfo.setTitle(title); }// w w w . ja v a 2s . co m } if (parameters.get("csw.abstract_" + langId) != null) { String abs = (String) ((LinkedList) parameters.get("csw.abstract_" + langId)).get(0); if (StringUtils.isNotEmpty(abs)) { cswCapInfo.setAbstract(abs); } } if (parameters.get("csw.fees_" + langId) != null) { String fees = (String) ((LinkedList) parameters.get("csw.fees_" + langId)).get(0); if (StringUtils.isNotEmpty(fees)) { cswCapInfo.setFees(fees); } } if (parameters.get("csw.accessConstraints_" + langId) != null) { String accessConstraints = (String) ((LinkedList) parameters.get("csw.accessConstraints_" + langId)) .get(0); if (StringUtils.isNotEmpty(accessConstraints)) { cswCapInfo.setAccessConstraints(accessConstraints); } } // Save item cswCapabilitiesInfoFieldRepository.save(cswCapInfo); } }
From source file:org.fao.geonet.OgpAppHandler.java
/** * Inits the engine, loading all needed data. *///from www . j a v a 2s .co m public Object start(Element config, ServiceContext context) throws Exception { context.setAsThreadLocal(); this._applicationContext = context.getApplicationContext(); ApplicationContextHolder.set(this._applicationContext); logger = context.getLogger(); // If an error occur during logger configuration // Continue starting the application with // a logger initialized with the default log4j.xml. try { LogUtils.refreshLogConfiguration(); } catch (OperationAbortedEx e) { logger.error("Error while setting log configuration. " + "Check the setting in the database for logger configuration file."); logger.error(e.getMessage()); } ConfigurableListableBeanFactory beanFactory = context.getApplicationContext().getBeanFactory(); ServletPathFinder finder = new ServletPathFinder(this._applicationContext.getBean(ServletContext.class)); appPath = finder.getAppPath(); String baseURL = context.getBaseUrl(); String webappName = baseURL.substring(1); // TODO : if webappName is "". ie no context final SystemInfo systemInfo = _applicationContext.getBean(SystemInfo.class); String version = systemInfo.getVersion(); String subVersion = systemInfo.getSubVersion(); logger.info("Initializing GeoNetwork " + version + "." + subVersion + " ..."); // Get main service config handler @SuppressWarnings("unchecked") List<Element> serviceConfigElems = config.getChildren(); ServiceConfig handlerConfig = new ServiceConfig(serviceConfigElems); // Init configuration directory final GeonetworkDataDirectory dataDirectory = _applicationContext.getBean(GeonetworkDataDirectory.class); dataDirectory.init(webappName, appPath, handlerConfig, context.getServlet()); // Get config handler properties String systemDataDir = handlerConfig.getMandatoryValue(Geonet.Config.SYSTEM_DATA_DIR); String thesauriDir = handlerConfig.getMandatoryValue(Geonet.Config.CODELIST_DIR); String luceneDir = handlerConfig.getMandatoryValue(Geonet.Config.LUCENE_DIR); String luceneConfigXmlFile = handlerConfig.getMandatoryValue(Geonet.Config.LUCENE_CONFIG); logger.info("Data directory: " + systemDataDir); setProps(appPath, handlerConfig); importDatabaseData(context); // Status actions class - load it String statusActionsClassName = handlerConfig.getMandatoryValue(Geonet.Config.STATUS_ACTIONS_CLASS); @SuppressWarnings("unchecked") Class<StatusActions> statusActionsClass = (Class<StatusActions>) Class.forName(statusActionsClassName); JeevesJCS.setConfigFilename(appPath.resolve("WEB-INF/classes/cache.ccf")); // force caches to be config'd so shutdown hook works correctly JeevesJCS.getInstance(Processor.XLINK_JCS); JeevesJCS.getInstance(XmlResolver.XMLRESOLVER_JCS); //------------------------------------------------------------------------ //--- initialize settings subsystem logger.info(" - Setting manager..."); SettingManager settingMan = this._applicationContext.getBean(SettingManager.class); //--- initialize ThreadUtils with setting manager and rm props final DataSource dataSource = context.getBean(DataSource.class); Connection conn = null; try { conn = dataSource.getConnection(); ThreadUtils.init(conn.getMetaData().getURL(), settingMan); } finally { if (conn != null) { conn.close(); } } //------------------------------------------------------------------------ //--- initialize Z39.50 logger.info(" - Z39.50..."); boolean z3950Enable = settingMan.getValueAsBool("system/z3950/enable", false); String z3950port = settingMan.getValue("system/z3950/port"); logger.info(" - Z39.50 is enabled: " + z3950Enable); if (z3950Enable) { // build Z3950 repositories file first from template URL url = getClass().getClassLoader().getResource(Geonet.File.JZKITCONFIG_TEMPLATE); if (Repositories.build(url, context)) { logger.info(" Repositories file built from template."); try { ConfigurableApplicationContext appContext = context.getApplicationContext(); // to have access to the GN context in spring-managed objects ContextContainer cc = (ContextContainer) appContext.getBean("ContextGateway"); cc.setSrvctx(context); if (!z3950Enable) { logger.info(" Server is Disabled."); } else { logger.info(" Server is Enabled."); Server.init(z3950port, appContext); } } catch (Exception e) { logger.error( " Repositories file init FAILED - Z3950 server disabled and Z3950 client services (remote search, " + "harvesting) may not work. Error is:" + e.getMessage()); e.printStackTrace(); } } else { logger.error( " Repositories file builder FAILED - Z3950 server disabled and Z3950 client services (remote search, " + "harvesting) may not work."); } } //------------------------------------------------------------------------ //--- initialize SchemaManager logger.info(" - Schema manager..."); Path schemaPluginsDir = dataDirectory.getSchemaPluginsDir(); Path schemaCatalogueFile = dataDirectory.getConfigDir().resolve(Geonet.File.SCHEMA_PLUGINS_CATALOG); boolean createOrUpdateSchemaCatalog = handlerConfig .getMandatoryValue(Geonet.Config.SCHEMA_PLUGINS_CATALOG_UPDATE).equals("true"); logger.info(" - Schema plugins directory: " + schemaPluginsDir); logger.info(" - Schema Catalog File : " + schemaCatalogueFile); SchemaManager schemaMan = _applicationContext.getBean(SchemaManager.class); schemaMan.configure(_applicationContext, appPath, dataDirectory.getResourcesDir(), schemaCatalogueFile, schemaPluginsDir, context.getLanguage(), handlerConfig.getMandatoryValue(Geonet.Config.PREFERRED_SCHEMA), createOrUpdateSchemaCatalog); //------------------------------------------------------------------------ //--- initialize search and editing logger.info(" - Search..."); boolean logSpatialObject = "true" .equalsIgnoreCase(handlerConfig.getMandatoryValue(Geonet.Config.STAT_LOG_SPATIAL_OBJECTS)); boolean logAsynch = "true".equalsIgnoreCase(handlerConfig.getMandatoryValue(Geonet.Config.STAT_LOG_ASYNCH)); logger.info(" - Log spatial object: " + logSpatialObject); logger.info(" - Log in asynch mode: " + logAsynch); String luceneTermsToExclude = ""; luceneTermsToExclude = handlerConfig.getMandatoryValue(Geonet.Config.STAT_LUCENE_TERMS_EXCLUDE); LuceneConfig lc = _applicationContext.getBean(LuceneConfig.class); lc.configure(luceneConfigXmlFile); logger.info(" - Lucene configuration is:"); logger.info(lc.toString()); try { _applicationContext.getBean(DataStore.class); } catch (NoSuchBeanDefinitionException e) { DataStore dataStore = createShapefileDatastore(luceneDir); _applicationContext.getBeanFactory().registerSingleton("dataStore", dataStore); //--- no datastore for spatial indexing means that we can't continue if (dataStore == null) { throw new IllegalArgumentException( "GeoTools datastore creation failed - check logs for more info/exceptions"); } } String maxWritesInTransactionStr = handlerConfig.getMandatoryValue(Geonet.Config.MAX_WRITES_IN_TRANSACTION); int maxWritesInTransaction = SpatialIndexWriter.MAX_WRITES_IN_TRANSACTION; try { maxWritesInTransaction = Integer.parseInt(maxWritesInTransactionStr); } catch (NumberFormatException nfe) { logger.error( "Invalid config parameter: maximum number of writes to spatial index in a transaction (maxWritesInTransaction)" + ", Using " + maxWritesInTransaction + " instead."); nfe.printStackTrace(); } SettingInfo settingInfo = context.getBean(SettingInfo.class); searchMan = _applicationContext.getBean(SearchManager.class); searchMan.init(logAsynch, logSpatialObject, luceneTermsToExclude, maxWritesInTransaction); // if the validator exists the proxyCallbackURL needs to have the external host and // servlet name added so that the cas knows where to send the validation notice ServerBeanPropertyUpdater.updateURL(settingInfo.getSiteUrl(true) + baseURL, _applicationContext); //------------------------------------------------------------------------ //--- extract intranet ip/mask and initialize AccessManager logger.info(" - Access manager..."); //------------------------------------------------------------------------ //--- get edit params and initialize DataManager logger.info(" - Xml serializer and Data manager..."); SvnManager svnManager = _applicationContext.getBean(SvnManager.class); XmlSerializer xmlSerializer = _applicationContext.getBean(XmlSerializer.class); if (xmlSerializer instanceof XmlSerializerSvn && svnManager != null) { svnManager.setContext(context); Path subversionPath = dataDirectory.getMetadataRevisionDir().toAbsolutePath().normalize(); svnManager.setSubversionPath(subversionPath.toString()); svnManager.init(); } /** * Initialize language detector */ LanguageDetector.init( appPath.resolve(_applicationContext.getBean(Geonet.Config.LANGUAGE_PROFILES_DIR, String.class))); //------------------------------------------------------------------------ //--- Initialize thesaurus logger.info(" - Thesaurus..."); _applicationContext.getBean(ThesaurusManager.class).init(false, context, thesauriDir); //------------------------------------------------------------------------ //--- initialize catalogue services for the web logger.info(" - Open Archive Initiative (OAI-PMH) server..."); OaiPmhDispatcher oaipmhDis = new OaiPmhDispatcher(settingMan, schemaMan); GeonetContext gnContext = new GeonetContext(_applicationContext, false, statusActionsClass); //------------------------------------------------------------------------ //--- return application context beanFactory.registerSingleton("serviceHandlerConfig", handlerConfig); beanFactory.registerSingleton("oaipmhDisatcher", oaipmhDis); _applicationContext.getBean(DataManager.class).init(context, false); _applicationContext.getBean(HarvestManager.class).init(context, gnContext.isReadOnly()); _applicationContext.getBean(ThumbnailMaker.class).init(context); logger.info("Site ID is : " + settingMan.getSiteId()); // Creates a default site logo, only if the logo image doesn't exists // This can happen if the application has been updated with a new version preserving the database and // images/logos folder is not copied from old application createSiteLogo(settingMan.getSiteId(), context, context.getAppPath()); // Notify unregistered metadata at startup. Needed, for example, when the user enables the notifier config // to notify the existing metadata in database // TODO: Fix DataManager.getUnregisteredMetadata and uncomment next lines metadataNotifierControl = new MetadataNotifierControl(context); metadataNotifierControl.runOnce(); // Reindex Blank template metadata DataManager dm = _applicationContext.getBean(DataManager.class); Set<Integer> metadataToReindex = new HashSet<>(); metadataToReindex.add(new Integer(1)); context.info("Re-indexing metadata"); BatchOpsMetadataReindexer r = new BatchOpsMetadataReindexer(dm, metadataToReindex); r.process(); //--- load proxy information from settings into Jeeves for observers such //--- as jeeves.utils.XmlResolver to use ProxyInfo pi = JeevesProxyInfo.getInstance(); boolean useProxy = settingMan.getValueAsBool("system/proxy/use", false); if (useProxy) { String proxyHost = settingMan.getValue("system/proxy/host"); String proxyPort = settingMan.getValue("system/proxy/port"); String username = settingMan.getValue("system/proxy/username"); String password = settingMan.getValue("system/proxy/password"); pi.setProxyInfo(proxyHost, Integer.valueOf(proxyPort), username, password); } boolean inspireEnable = settingMan.getValueAsBool("system/inspire/enable", false); if (inspireEnable) { String atomType = settingMan.getValue("system/inspire/atom"); String atomSchedule = settingMan.getValue("system/inspire/atomSchedule"); if (StringUtils.isNotEmpty(atomType) && StringUtils.isNotEmpty(atomSchedule) && atomType.equalsIgnoreCase(InspireAtomType.ATOM_REMOTE)) { logger.info(" - INSPIRE ATOM feed harvester ..."); InspireAtomHarvesterScheduler.schedule(atomSchedule, context, gnContext); } } // // db heartbeat configuration -- for failover to readonly database // boolean dbHeartBeatEnabled = Boolean .parseBoolean(handlerConfig.getValue(Geonet.Config.DB_HEARTBEAT_ENABLED, "false")); if (dbHeartBeatEnabled) { Integer dbHeartBeatInitialDelay = Integer .parseInt(handlerConfig.getValue(Geonet.Config.DB_HEARTBEAT_INITIALDELAYSECONDS, "5")); Integer dbHeartBeatFixedDelay = Integer .parseInt(handlerConfig.getValue(Geonet.Config.DB_HEARTBEAT_FIXEDDELAYSECONDS, "60")); createDBHeartBeat(gnContext, dbHeartBeatInitialDelay, dbHeartBeatFixedDelay); } fillCaches(context); AbstractEntityListenerManager.setSystemRunning(true); return gnContext; }
From source file:org.kuali.rice.krad.test.KRADTestCase.java
@Override protected void setUpInternal() throws Exception { super.setUpInternal(); List<Class> classes = TestUtilities.getHierarchyClassesToHandle(getClass(), new Class[] { TestDictionaryConfig.class }, new HashSet<String>()); // if annotation is present then initialize test data dictionary (setup once per suite) if (!classes.isEmpty()) { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("TestDataDictionary.xml"); dd = (DataDictionary) context.getBean("testDataDictionary"); // add any additional dictionary files required by the test for (Class c : classes) { if (c.isAnnotationPresent(TestDictionaryConfig.class)) { TestDictionaryConfig testDictionaryConfig = (TestDictionaryConfig) c .getAnnotation(TestDictionaryConfig.class); String namespaceCode = testDictionaryConfig.namespaceCode(); String dictionaryFileString = testDictionaryConfig.dataDictionaryFiles(); String[] dictionaryFiles = StringUtils.split(dictionaryFileString, ","); for (String dictionaryFile : dictionaryFiles) { LOG.info("Adding test data dictionary file: " + dictionaryFile); dd.addConfigFileLocation(namespaceCode, dictionaryFile); }// w w w . ja va 2s. com } } dd.parseDataDictionaryConfigurationFiles(false); dd.validateDD(false); // Validation performs some necessary post-processing of the beans - we need to run this each time we add new files dd.performBeanOverrides(); } }
From source file:org.kuali.student.common.test.spring.AbstractTransactionalDaoTest.java
/** * Loads the application context defined in the @Dao testDataFile * attribute. Then uses the EntityManager em to persist the beans in * persistList// ww w. j av a2 s . c om */ @Before public void preLoadBeans() { for (Field f : this.getClass().getDeclaredFields()) { if (f.isAnnotationPresent(Dao.class)) { Dao dao = f.getAnnotation(Dao.class); if (dao.testDataFile().length() > 0) { ConfigurableApplicationContext ac = new FileSystemXmlApplicationContext(dao.testDataFile()); List<?> persistList = (List<?>) ac.getBean("persistList"); ac.close(); for (Object o : persistList) { em.persist(o); } em.flush(); } } } }
From source file:org.kuali.student.common.test.spring.LoadDataBean.java
public void loadData() { if (daoAnnotations == null || loaded || daoAnnotations.trim().isEmpty()) { return;//from w w w . ja v a 2 s . c om } // Load all the beans String[] classes = daoAnnotations.split(","); for (String line : classes) { try { String[] split = line.split("\\|"); // Invoke the data loader for this dao invokeDataLoader(split[0]); // Load data bean file for this dao if (split.length > 1 && !split[1].isEmpty()) { String testDataFile = split[1]; ConfigurableApplicationContext ac = new FileSystemXmlApplicationContext(testDataFile); List<?> persistList = (List<?>) ac.getBean("persistList"); ac.close(); for (Object bean : persistList) { if (!em.contains(bean)) { em.persist(bean); } } } // Load sql file for this dao if (split.length > 2 && !split[2].isEmpty()) { String testDataFile = split[2]; File sqlFile; if (testDataFile.startsWith("classpath:")) { sqlFile = new ClassPathResource(testDataFile.substring("classpath:".length())).getFile(); } else { sqlFile = new File(testDataFile); } BufferedReader in = new BufferedReader(new FileReader(sqlFile)); try { String ln = ""; int lnNr = 0; try { while ((ln = in.readLine()) != null) { lnNr++; if (!ln.startsWith("/") && !ln.startsWith("--") && StringUtils.isNotBlank(ln)) { ln = ln.replaceFirst("[;/]\\s*$", ""); em.createNativeQuery(ln).executeUpdate(); } } } catch (PersistenceException e) { LOG.error("Failed statement at line " + lnNr + ": " + ln); throw e; } } finally { in.close(); } } } catch (Exception e) { throw new RuntimeException(e); } } loaded = true; }
From source file:org.springframework.amqp.rabbit.admin.RabbitTemplateConsumerExample.java
public static void main(String[] args) throws Exception { boolean sync = true; if (sync) {/*from w ww. j a v a 2 s. c o m*/ ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext( TestRabbitConfiguration.class); RabbitTemplate template = ctx.getBean(RabbitTemplate.class); receiveSync(template, TestConstants.NUM_MESSAGES); } else { ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext( RabbitConsumerConfiguration.class); receiveAsync(ctx); } }
From source file:org.springframework.amqp.rabbit.admin.RabbitTemplateConsumerExample.java
private static void receiveAsync(ConfigurableApplicationContext ctx) throws InterruptedException { ctx.getBean(SimpleMessageListenerContainer.class); log.debug("Main execution thread sleeping 5 seconds..."); Thread.sleep(500000);/*www .j ava2s. co m*/ log.debug("Application exiting."); System.exit(0); }
From source file:org.springframework.amqp.rabbit.admin.RabbitTemplateProducerExample.java
public static void main(String[] args) throws Exception { ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext( RabbitProducerConfiguration.class); RabbitTemplate template = ctx.getBean(RabbitTemplate.class); for (int i = 1; i <= 10; i++) { template.convertAndSend("test-" + i); Thread.sleep(100);//ww w .jav a 2 s. c o m } log.debug("done sending"); ctx.stop(); System.exit(0); }
From source file:org.springframework.amqp.rabbit.core.RabbitAdminTests.java
@Test public void testMultiEntities() { ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(Config.class); RabbitTemplate template = ctx.getBean(RabbitTemplate.class); template.convertAndSend("e1", "k1", "foo"); template.convertAndSend("e2", "k2", "bar"); template.convertAndSend("e3", "k3", "baz"); template.convertAndSend("e4", "k4", "qux"); assertEquals("foo", template.receiveAndConvert("q1")); assertEquals("bar", template.receiveAndConvert("q2")); assertEquals("baz", template.receiveAndConvert("q3")); assertEquals("qux", template.receiveAndConvert("q4")); RabbitAdmin admin = ctx.getBean(RabbitAdmin.class); admin.deleteQueue("q1"); admin.deleteQueue("q2"); admin.deleteQueue("q3"); admin.deleteQueue("q4"); admin.deleteExchange("e1"); admin.deleteExchange("e2"); admin.deleteExchange("e3"); admin.deleteExchange("e4"); assertNull(admin.getQueueProperties(ctx.getBean(Config.class).protypeQueueName)); ctx.close();/*from www. ja v a 2 s .c om*/ }
From source file:org.springframework.amqp.rabbit.retry.MissingIdRetryTests.java
@SuppressWarnings("rawtypes") @Test// w w w . j a v a 2s .c o m public void testWithNoId() throws Exception { // 2 messages; each retried once by missing id interceptor this.latch = new CountDownLatch(4); ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext("retry-context.xml", this.getClass()); RabbitTemplate template = ctx.getBean(RabbitTemplate.class); ConnectionFactory connectionFactory = ctx.getBean(ConnectionFactory.class); SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory); container.setStatefulRetryFatalWithNullMessageId(false); container.setMessageListener(new MessageListenerAdapter(new POJO())); container.setQueueNames("retry.test.queue"); StatefulRetryOperationsInterceptorFactoryBean fb = new StatefulRetryOperationsInterceptorFactoryBean(); // use an external template so we can share his cache RetryTemplate retryTemplate = new RetryTemplate(); RetryContextCache cache = spy(new MapRetryContextCache()); retryTemplate.setRetryContextCache(cache); fb.setRetryOperations(retryTemplate); Advice retryInterceptor = fb.getObject(); container.setAdviceChain(retryInterceptor); container.start(); template.convertAndSend("retry.test.exchange", "retry.test.binding", "Hello, world!"); template.convertAndSend("retry.test.exchange", "retry.test.binding", "Hello, world!"); try { assertTrue(latch.await(30, TimeUnit.SECONDS)); Map map = (Map) new DirectFieldAccessor(cache).getPropertyValue("map"); int n = 0; while (n++ < 100 && map.size() != 0) { Thread.sleep(100); } verify(cache, never()).put(any(), any(RetryContext.class)); verify(cache, never()).remove(any()); assertEquals("Expected map.size() = 0, was: " + map.size(), 0, map.size()); } finally { container.stop(); ctx.close(); } }