List of usage examples for org.springframework.context.support ClassPathXmlApplicationContext getBean
@Override public <T> T getBean(String name, Class<T> requiredType) throws BeansException
From source file:com.evolveum.midpoint.tools.ninja.ImportObjects.java
public boolean execute() { System.out.println("Starting objects import."); File objects = new File(filePath); if (!objects.exists() || !objects.canRead()) { System.out.println(/*from ww w . ja v a 2 s .co m*/ "XML file with objects '" + objects.getAbsolutePath() + "' doesn't exist or can't be read."); return false; } InputStream input = null; ClassPathXmlApplicationContext context = null; try { System.out.println("Loading spring contexts."); context = new ClassPathXmlApplicationContext(CONTEXTS); InputStreamReader reader = new InputStreamReader(new FileInputStream(objects), "utf-8"); input = new ReaderInputStream(reader, reader.getEncoding()); final RepositoryService repository = context.getBean("repositoryService", RepositoryService.class); PrismContext prismContext = context.getBean(PrismContext.class); EventHandler handler = new EventHandler() { @Override public EventResult preMarshall(Element objectElement, Node postValidationTree, OperationResult objectResult) { return EventResult.cont(); } @Override public <T extends Objectable> EventResult postMarshall(PrismObject<T> object, Element objectElement, OperationResult objectResult) { try { String displayName = getDisplayName(object); System.out.println("Importing object " + displayName); repository.addObject((PrismObject<ObjectType>) object, null, objectResult); } catch (Exception ex) { objectResult.recordFatalError("Unexpected problem: " + ex.getMessage(), ex); System.out.println("Exception occurred during import, reason: " + ex.getMessage()); ex.printStackTrace(); } objectResult.recordSuccessIfUnknown(); if (objectResult.isAcceptable()) { // Continue import return EventResult.cont(); } else { return EventResult.skipObject(objectResult.getMessage()); } } @Override public void handleGlobalError(OperationResult currentResult) { } }; Validator validator = new Validator(prismContext, handler); validator.setVerbose(true); validator.setValidateSchema(validateSchema); OperationResult result = new OperationResult("Import objeccts"); validator.validate(input, result, OperationConstants.IMPORT_OBJECT); result.recomputeStatus(); if (!result.isSuccess()) { System.out.println("Operation result was not success, dumping result.\n" + result.debugDump(3)); } } catch (Exception ex) { System.out.println("Exception occurred during import task, reason: " + ex.getMessage()); ex.printStackTrace(); } finally { IOUtils.closeQuietly(input); destroyContext(context); } System.out.println("Objects import finished."); return true; }
From source file:com.brienwheeler.apps.schematool.SchemaToolBean.java
public void afterPropertiesSet() throws Exception { try {/*from ww w . j av a 2 s .com*/ // set based on default values in schematool properties file if not already set PropertyPlaceholderConfigurer.setProperty(emfPersistenceLocationsPropName, emfPersistenceLocationsPropValue); Configuration configuration = determineHibernateConfiguration(); Settings settings = null; if (exec || mode == Mode.UPDATE) { ClassPathXmlApplicationContext newContext = new SmartClassPathXmlApplicationContext( emfContextLocation); try { // get a reference to the factory bean, don't have it create a new EntityManager LocalContainerEntityManagerFactoryBean factoryBean = newContext .getBean("&" + emfContextBeanName, LocalContainerEntityManagerFactoryBean.class); SettingsFactory settingsFactory = new InjectedDataSourceSettingsFactory( factoryBean.getDataSource()); settings = settingsFactory.buildSettings(new Properties()); } finally { newContext.close(); } } if (mode == Mode.UPDATE) { SchemaUpdate update = new SchemaUpdate(configuration, settings); update.execute(true, exec); } else { SchemaExport export = exec ? new SchemaExport(configuration, settings) : new SchemaExport(configuration); export.create(true, exec); } } catch (Exception e) { log.error("Error running SchemaTool", e); throw e; } }
From source file:com.temenos.interaction.loader.detector.SpringBasedLoaderAction.java
@Override public void execute(FileEvent<File> dirEvent) { LOGGER.debug("Creation of new Spring ApplicationContext based CommandController triggerred by change in", dirEvent.getResource().getAbsolutePath()); Collection<File> jars = FileUtils.listFiles(dirEvent.getResource(), new String[] { "jar" }, true); Set<URL> urls = new HashSet(); for (File f : jars) { try {//w ww . j a v a2 s. c o m LOGGER.trace("Adding {} to list of URLs to create ApplicationContext from", f.toURI().toURL()); urls.add(f.toURI().toURL()); } catch (MalformedURLException ex) { // kindly ignore and log } } Reflections reflectionHelper = new Reflections( new ConfigurationBuilder().addClassLoader(classloaderFactory.getForObject(dirEvent)) .addScanners(new ResourcesScanner()).addUrls(urls)); Set<String> resources = new HashSet(); for (String locationPattern : configLocationsPatterns) { String regex = convertWildcardToRegex(locationPattern); resources.addAll(reflectionHelper.getResources(Pattern.compile(regex))); } if (!resources.isEmpty()) { // if resources are empty just clean up the previous ApplicationContext and leave! LOGGER.debug("Detected potential Spring config files to load"); ClassPathXmlApplicationContext context; if (parentContext != null) { context = new ClassPathXmlApplicationContext(parentContext); } else { context = new ClassPathXmlApplicationContext(); } context.setConfigLocations(configLocationsPatterns.toArray(new String[] {})); ClassLoader childClassLoader = classloaderFactory.getForObject(dirEvent); context.setClassLoader(childClassLoader); context.refresh(); CommandController cc = null; try { cc = context.getBean(commandControllerBeanName, CommandController.class); LOGGER.debug("Detected pre-configured CommandController in added config files"); } catch (BeansException ex) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("No detected pre-configured CommandController in added config files.", ex); } Map<String, InteractionCommand> commands = context.getBeansOfType(InteractionCommand.class); if (!commands.isEmpty()) { LOGGER.debug("Adding new commands"); SpringContextBasedInteractionCommandController scbcc = new SpringContextBasedInteractionCommandController(); scbcc.setApplicationContext(context); cc = scbcc; } else { LOGGER.debug("No commands detected to be added"); } } if (parentChainingCommandController != null) { List<CommandController> newCommandControllers = new ArrayList<CommandController>( parentChainingCommandController.getCommandControllers()); // "unload" the previously loaded CommandController if (previouslyAddedCommandController != null) { LOGGER.debug("Removing previously added instance of CommandController"); newCommandControllers.remove(previouslyAddedCommandController); } // if there is a new CommandController on the Spring file, add it on top of the chain if (cc != null) { LOGGER.debug("Adding newly created CommandController to ChainingCommandController"); newCommandControllers.add(0, cc); parentChainingCommandController.setCommandControllers(newCommandControllers); previouslyAddedCommandController = cc; } else { previouslyAddedCommandController = null; } } else { LOGGER.debug( "No ChainingCommandController set to add newly created CommandController to - skipping action"); } if (previousAppCtx != null) { if (previousAppCtx instanceof Closeable) { try { ((Closeable) previousAppCtx).close(); } catch (Exception ex) { LOGGER.error("Error closing the ApplicationContext.", ex); } } previousAppCtx = context; } } else { LOGGER.debug("No Spring config files detected in the JARs scanned"); } }
From source file:org.dataconservancy.packaging.apt.AutomatedPackageTool.java
private void run() throws Exception { final ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext( "classpath*:org/dataconservancy/apt/config/applicationContext.xml", "classpath*:org/dataconservancy/config/applicationContext.xml", "classpath*:org/dataconservancy/packaging/tool/ser/config/applicationContext.xml"); boolean useDefaults = true; // Prepare parameter builder PackageGenerationParametersBuilder parametersBuilder = appContext .getBean("packageGenerationParametersBuilder", PackageGenerationParametersBuilder.class); // Load parameters first from default, then override with home directory .packageGenerationParameters, then with // specified params file (if given). PackageGenerationParameters packageParams; try {/*from w w w.ja v a 2s .com*/ packageParams = parametersBuilder.buildParameters(getClass() .getResourceAsStream(defaultResourceConfigPath + packageGenerationsParametersFileName)); updateCompression(packageParams); } catch (ParametersBuildException e) { throw new PackageToolException(PackagingToolReturnInfo.CMD_LINE_PARAM_BUILD_EXCEPTION, e); } File userParamsFile = new File(userDataconservancyDirectory, packageGenerationsParametersFileName); if (userParamsFile.exists()) { try { PackageGenerationParameters homeParams = parametersBuilder .buildParameters(new FileInputStream(userParamsFile)); System.err.println("Overriding generation parameters with values from standard '" + packageGenerationsParametersFileName + "'"); useDefaults = false; updateCompression(homeParams); packageParams.overrideParams(homeParams); } catch (FileNotFoundException e) { // Do nothing, it's ok to not have this file } catch (ParametersBuildException e) { throw new PackageToolException(PackagingToolReturnInfo.CMD_LINE_PARAM_BUILD_EXCEPTION, e); } } if (packageGenerationParamsFile != null) { try { PackageGenerationParameters fileParams = parametersBuilder .buildParameters(new FileInputStream(packageGenerationParamsFile)); System.err.println("Overriding generation parameters with values from " + packageGenerationParamsFile + " specified on command line"); useDefaults = false; updateCompression(fileParams); packageParams.overrideParams(fileParams); } catch (ParametersBuildException e) { throw new PackageToolException(PackagingToolReturnInfo.CMD_LINE_PARAM_BUILD_EXCEPTION, e); } catch (FileNotFoundException e) { throw new PackageToolException(PackagingToolReturnInfo.CMD_LINE_FILE_NOT_FOUND_EXCEPTION, e); } if (debug) { log.debug("Parameters resulted from parsing file " + packageGenerationParamsFile.getAbsoluteFile() + ": \n" + packageParams.toString()); } } // Finally, override with command line options // If any options overridden, this will cause useDefaults to become false, if it wasn't already PackageGenerationParameters flagParams = createCommandLinePrefs(); if (!flagParams.getKeys().isEmpty()) { useDefaults = false; System.err.println("Overriding generation parameters using command line flags"); updateCompression(flagParams); packageParams.overrideParams(flagParams); } //we need to validate any specified file locations in the package generation params to make sure they exist if (packageParams.getParam(GeneralParameterNames.PACKAGE_LOCATION) == null) { packageParams.addParam(GeneralParameterNames.PACKAGE_LOCATION, System.getProperty("java.io.tmpdir")); } validateLocationParameters(packageParams); // Resolve the rules file location. Priority is given to a command line file path, then to one in the user's home location, then to the app default if (rulesFile == null) { File userRulesFile = new File(userDataconservancyDirectory, rulesFileName); if (userRulesFile.exists()) { rulesFile = userRulesFile; } else { //get the default rules file supplied with the app } } System.err.println("MOOOOOOOOOOOOOOOOOOOOOOOO"); }
From source file:org.entando.entando.aps.system.XmlWebApplicationContext.java
@Override public Object getBean(String name, Object... args) throws BeansException { Object bean = super.getBean(name, args); List<ClassPathXmlApplicationContext> contexts = (List<ClassPathXmlApplicationContext>) this .getServletContext().getAttribute("pluginsContextsList"); if (contexts != null) { for (ClassPathXmlApplicationContext classPathXmlApplicationContext : contexts) { if (bean == null) { try { bean = classPathXmlApplicationContext.getBean(name, args); } catch (Exception ex) { }// w w w. j a va2 s. c o m } } } return bean; }
From source file:org.entando.entando.aps.system.XmlWebApplicationContext.java
@Override public <T> T getBean(String name, Class<T> requiredType) throws BeansException { T bean = null;/* w ww .j av a 2 s . c o m*/ try { bean = super.getBean(name, requiredType); } catch (Exception e) { List<ClassPathXmlApplicationContext> contexts = (List<ClassPathXmlApplicationContext>) this .getServletContext().getAttribute("pluginsContextsList"); if (contexts != null) { for (ClassPathXmlApplicationContext classPathXmlApplicationContext : contexts) { if (bean == null) { try { bean = classPathXmlApplicationContext.getBean(name, requiredType); return bean; } catch (Exception ex) { } } } } } return bean; }
From source file:org.springframework.batch.core.test.step.SplitJobMapRepositoryIntegrationTests.java
@SuppressWarnings("resource") @Test//from w ww . ja v a 2 s .com public void testMultithreadedSplit() throws Throwable { JobLauncher jobLauncher = null; Job job = null; ClassPathXmlApplicationContext context = null; for (int i = 0; i < MAX_COUNT; i++) { if (i % 100 == 0) { if (context != null) { context.close(); } logger.info("Starting job: " + i); context = new ClassPathXmlApplicationContext(getClass().getSimpleName() + "-context.xml", getClass()); jobLauncher = context.getBean("jobLauncher", JobLauncher.class); job = context.getBean("job", Job.class); } try { JobExecution execution = jobLauncher.run(job, new JobParametersBuilder().addLong("count", new Long(i)).toJobParameters()); assertEquals(BatchStatus.COMPLETED, execution.getStatus()); } catch (Throwable e) { logger.info("Failed on iteration " + i + " of " + MAX_COUNT); throw e; } } }
From source file:org.springframework.integration.channel.DirectChannelTests.java
@Test // See INT-2434 public void testChannelCreationWithBeanDefinitionOverrideTrue() throws Exception { ClassPathXmlApplicationContext parentContext = new ClassPathXmlApplicationContext("parent-config.xml", this.getClass()); MessageChannel parentChannelA = parentContext.getBean("parentChannelA", MessageChannel.class); MessageChannel parentChannelB = parentContext.getBean("parentChannelB", MessageChannel.class); ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(); context.setAllowBeanDefinitionOverriding(false); context.setConfigLocations(/*from w w w .j a va2 s . c om*/ new String[] { "classpath:org/springframework/integration/channel/channel-override-config.xml" }); context.setParent(parentContext); Method method = ReflectionUtils.findMethod(ClassPathXmlApplicationContext.class, "obtainFreshBeanFactory"); method.setAccessible(true); method.invoke(context); assertFalse(context.containsBean("channelA")); assertFalse(context.containsBean("channelB")); assertTrue(context.containsBean("channelC")); assertTrue(context.containsBean("channelD")); context.refresh(); PublishSubscribeChannel channelEarly = context.getBean("channelEarly", PublishSubscribeChannel.class); assertTrue(context.containsBean("channelA")); assertTrue(context.containsBean("channelB")); assertTrue(context.containsBean("channelC")); assertTrue(context.containsBean("channelD")); EventDrivenConsumer consumerA = context.getBean("serviceA", EventDrivenConsumer.class); assertEquals(context.getBean("channelA"), TestUtils.getPropertyValue(consumerA, "inputChannel")); assertEquals(context.getBean("channelB"), TestUtils.getPropertyValue(consumerA, "handler.outputChannel")); EventDrivenConsumer consumerB = context.getBean("serviceB", EventDrivenConsumer.class); assertEquals(context.getBean("channelB"), TestUtils.getPropertyValue(consumerB, "inputChannel")); assertEquals(context.getBean("channelC"), TestUtils.getPropertyValue(consumerB, "handler.outputChannel")); EventDrivenConsumer consumerC = context.getBean("serviceC", EventDrivenConsumer.class); assertEquals(context.getBean("channelC"), TestUtils.getPropertyValue(consumerC, "inputChannel")); assertEquals(context.getBean("channelD"), TestUtils.getPropertyValue(consumerC, "handler.outputChannel")); EventDrivenConsumer consumerD = context.getBean("serviceD", EventDrivenConsumer.class); assertEquals(parentChannelA, TestUtils.getPropertyValue(consumerD, "inputChannel")); assertEquals(parentChannelB, TestUtils.getPropertyValue(consumerD, "handler.outputChannel")); EventDrivenConsumer consumerE = context.getBean("serviceE", EventDrivenConsumer.class); assertEquals(parentChannelB, TestUtils.getPropertyValue(consumerE, "inputChannel")); EventDrivenConsumer consumerF = context.getBean("serviceF", EventDrivenConsumer.class); assertEquals(channelEarly, TestUtils.getPropertyValue(consumerF, "inputChannel")); }
From source file:org.springframework.integration.core.MessageIdGenerationTests.java
@Test public void testCustomIdGenerationWithParentRegistrar() throws Exception { ClassPathXmlApplicationContext parent = new ClassPathXmlApplicationContext( "MessageIdGenerationTests-context-withGenerator.xml", this.getClass()); ClassPathXmlApplicationContext child = new ClassPathXmlApplicationContext( new String[] { "MessageIdGenerationTests-context.xml" }, this.getClass(), parent); IdGenerator idGenerator = child.getBean("idGenerator", IdGenerator.class); MessageChannel inputChannel = child.getBean("input", MessageChannel.class); inputChannel.send(new GenericMessage<Integer>(0)); verify(idGenerator, atLeastOnce()).generateId(); child.close();//from www . java2 s.c o m parent.close(); this.assertDestroy(); }
From source file:org.springframework.integration.core.MessageIdGenerationTests.java
@Test public void testCustomIdGenerationWithParentRegistrarClosed() throws Exception { ClassPathXmlApplicationContext parent = new ClassPathXmlApplicationContext( "MessageIdGenerationTests-context-withGenerator.xml", this.getClass()); ClassPathXmlApplicationContext child = new ClassPathXmlApplicationContext( new String[] { "MessageIdGenerationTests-context.xml" }, this.getClass(), parent); IdGenerator idGenerator = child.getBean("idGenerator", IdGenerator.class); MessageChannel inputChannel = child.getBean("input", MessageChannel.class); inputChannel.send(new GenericMessage<Integer>(0)); verify(idGenerator, atLeastOnce()).generateId(); parent.close();/*from w w w . j a v a2 s . c o m*/ child.close(); this.assertDestroy(); }