List of usage examples for org.springframework.context ConfigurableApplicationContext getBean
Object getBean(String name) throws BeansException;
From source file:org.springframework.integration.endpoint.PseudoTransactionalMessageSourceTests.java
@Test public void testTransactionSynchronizationFactoryBean() { ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(TestTxSyncConfiguration.class); TransactionSynchronizationFactory syncFactory = ctx.getBean(TransactionSynchronizationFactory.class); PollableChannel queueChannel = ctx.getBean("outputChannel", PollableChannel.class); SourcePollingChannelAdapter adapter = new SourcePollingChannelAdapter(); adapter.setTransactionSynchronizationFactory(syncFactory); QueueChannel outputChannel = new QueueChannel(); adapter.setOutputChannel(outputChannel); adapter.setSource(new MessageSource<String>() { @Override/* w ww .j ava 2 s. co m*/ public Message<String> receive() { GenericMessage<String> message = new GenericMessage<String>("foo"); IntegrationResourceHolder holder = (IntegrationResourceHolder) TransactionSynchronizationManager .getResource(this); holder.addAttribute("baz", "qux"); holder.addAttribute("bix", "qox"); return message; } }); TransactionSynchronizationManager.initSynchronization(); TransactionSynchronizationManager.setActualTransactionActive(true); doPoll(adapter); TransactionSynchronizationUtils.triggerBeforeCommit(false); TransactionSynchronizationUtils.triggerAfterCommit(); Message<?> beforeCommitMessage = queueChannel.receive(1000); assertNotNull(beforeCommitMessage); assertEquals("qox", beforeCommitMessage.getPayload()); Message<?> afterCommitMessage = queueChannel.receive(1000); assertNotNull(afterCommitMessage); assertEquals("qux", afterCommitMessage.getPayload()); TransactionSynchronizationUtils.triggerAfterCompletion(TransactionSynchronization.STATUS_COMMITTED); TransactionSynchronizationManager.clearSynchronization(); TransactionSynchronizationManager.setActualTransactionActive(false); ctx.close(); }
From source file:org.springframework.integration.samples.ftp.FtpOutboundGatewaySample.java
@Test public void testLsGetRm() throws Exception { ConfigurableApplicationContext ctx = new ClassPathXmlApplicationContext( "classpath:/META-INF/spring/integration/FtpOutboundGatewaySample-context.xml"); final ToFtpFlowGateway toFtpFlow = ctx.getBean(ToFtpFlowGateway.class); // execute the flow (ls, get, rm, aggregate results) List<Boolean> rmResults = toFtpFlow.lsGetAndRmFiles("/"); //Check everything went as expected, and clean up assertEquals("Was expecting the collection 'rmResults' to contain 2 elements.", 2, rmResults.size()); for (Boolean result : rmResults) { assertTrue(result);/* w w w. j a va 2 s .c om*/ } assertTrue("Expected FTP remote directory to be empty", new File(TestSuite.FTP_ROOT_DIR).delete()); }
From source file:org.springframework.migrationanalyzer.commandline.AbstractMigrationAnalysis.java
final void run(String[] args) { CommandLine commandLine = null;//from ww w .ja v a 2s . c om try { commandLine = new PosixParser().parse(OPTIONS, args); String outputType = commandLine.getOptionValue(OptionsFactory.OPTION_KEY_OUTPUT_TYPE); String outputPath = commandLine.getOptionValue(OptionsFactory.OPTION_KEY_OUTPUT_PATH); String[] excludes = commandLine.getOptionValues(OptionsFactory.OPTION_KEY_EXCLUDE); String inputPath = getInputPath(commandLine); try { ConfigurableApplicationContext applicationContext = getApplicationContext(); applicationContext.addBeanFactoryPostProcessor(new ConfigurationRegisteringBeanFactoryPostProcessor( new Configuration(inputPath, outputPath, outputType, excludes))); applicationContext.refresh(); applicationContext.getBean(MigrationAnalysisExecutor.class).execute(); } catch (RuntimeException re) { this.logger.error("A failure occurred. Please see earlier output for details."); exit(-1); } } catch (ParseException e) { displayUsage(); exit(-1); } }
From source file:org.springframework.xd.dirt.stream.FileSourceModuleTests.java
@Test public void testSplitterUsesIterator() throws Exception { System.out.println(System.getProperty("user.dir")); ConfigurableApplicationContext ctx = new FileSystemXmlApplicationContext( new String[] { "../modules/common/file-source-common-context.xml", "classpath:org/springframework/xd/dirt/stream/ppc-context.xml" }, false);//from w ww .ja v a 2s .co m StandardEnvironment env = new StandardEnvironment(); Properties props = new Properties(); props.setProperty("fixedDelay", "5"); props.setProperty("timeUnit", "SECONDS"); props.setProperty("initialDelay", "0"); props.setProperty("withMarkers", "false"); PropertiesPropertySource pps = new PropertiesPropertySource("props", props); env.getPropertySources().addLast(pps); env.setActiveProfiles("use-contents-with-split"); ctx.setEnvironment(env); ctx.refresh(); FileSplitter splitter = ctx.getBean(FileSplitter.class); File foo = File.createTempFile("foo", ".txt"); final AtomicReference<Method> splitMessage = new AtomicReference<>(); ReflectionUtils.doWithMethods(FileSplitter.class, new MethodCallback() { @Override public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException { method.setAccessible(true); splitMessage.set(method); } }, new MethodFilter() { @Override public boolean matches(Method method) { return method.getName().equals("splitMessage"); } }); Object result = splitMessage.get().invoke(splitter, new GenericMessage<File>(foo)); assertThat(result, instanceOf(Iterator.class)); ctx.close(); foo.delete(); }
From source file:org.springframework.yarn.examples.CommonMain.java
public static void main(String args[]) { ConfigurableApplicationContext context = null; try {/*from w w w .ja va2s .c om*/ context = new ClassPathXmlApplicationContext("application-context.xml"); System.out.println("Submitting example"); YarnClient client = (YarnClient) context.getBean("yarnClient"); client.submitApplication(); System.out.println("Submitted example"); } catch (Throwable e) { log.error("Error in main method", e); } finally { if (context != null) { context.close(); } } }
From source file:org.springframework.yarn.examples.Main.java
public static void main(String args[]) { Properties properties = StringUtils.splitArrayElementsIntoProperties(args, "="); if (properties == null) { properties = new Properties(); }/* w w w .j a v a 2 s . c om*/ boolean nokill = Boolean.parseBoolean(properties.getProperty("nokill")); String appid = properties.getProperty("appid"); if (nokill) { new Main().doMain(new String[] { YarnSystemConstants.DEFAULT_CONTEXT_FILE_CLIENT, YarnSystemConstants.DEFAULT_ID_CLIENT, CommandLineClientRunner.OPT_SUBMIT }); } else if (appid != null) { new Main().doMain(new String[] { YarnSystemConstants.DEFAULT_CONTEXT_FILE_CLIENT, YarnSystemConstants.DEFAULT_ID_CLIENT, CommandLineClientRunner.OPT_KILL, CommandLineClientRunner.ARG_APPLICATION_ID + "=" + appid }); } else if (!nokill) { ConfigurableApplicationContext context = null; try { context = new ClassPathXmlApplicationContext("application-context.xml"); System.out.println("Submitting kill-application example"); YarnClient client = (YarnClient) context.getBean("yarnClient"); ApplicationId applicationId = client.submitApplication(); System.out.println("Submitted kill-application example"); System.out.println("Waiting 30 seconds before aborting the application"); Thread.sleep(30000); System.out.println( "Asking resource manager to abort application with applicationid=" + applicationId); client.killApplication(applicationId); } catch (Throwable e) { log.error("Error in main method", e); } finally { if (context != null) { context.close(); } } } }
From source file:org.springframework.yarn.launch.AbstractCommandLineRunner.java
/** * Builds the Application Context(s) and handles 'execution' * of a bean./* w w w . j ava2s .com*/ * * @param configLocation the main context config location * @param masterIdentifier the bean identifier * @param childConfigLocation the child context config location * @param parameters the parameters * @param opts the options * @return the status of the execution */ protected int start(String configLocation, String masterIdentifier, String childConfigLocation, String[] parameters, Set<String> opts) { ConfigurableApplicationContext context = null; ExitStatus exitStatus = ExitStatus.COMPLETED; try { context = getApplicationContext(configLocation); getChildApplicationContext(childConfigLocation, context); @SuppressWarnings("unchecked") T bean = (T) context.getBean(masterIdentifier); if (log.isDebugEnabled()) { log.debug("Passing bean=" + bean + " from context=" + context + " for beanId=" + masterIdentifier); } exitStatus = handleBeanRun(bean, parameters, opts); } catch (Throwable e) { e.printStackTrace(); String message = "Terminated in error: " + e.getMessage(); log.error(message, e); AbstractCommandLineRunner.message = message; return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode()); } finally { if (context != null) { context.close(); } } return exitCodeMapper.intValue(exitStatus.getExitCode()); }
From source file:sample.atmosphere.SampleAtmosphereApplicationTests.java
@Test public void chatEndpoint() throws Exception { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) .properties("websocket.uri:ws://localhost:" + this.port + "/chat/websocket") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close();/*from www .ja v a2 s.com*/ assertThat(count, equalTo(0L)); assertThat(messagePayloadReference.get(), containsString("{\"message\":\"test\",\"author\":\"test\",\"time\":")); }
From source file:samples.websocket.jetty93.echo.CustomContainerWebSocketsApplicationTests.java
@Test public void echoEndpoint() throws Exception { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) .properties("websocket.uri:ws://localhost:" + PORT + "/ws/echo/websocket") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close();//w ww . j a va 2 s .c om assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Did you say \"Hello world!\"?"); }
From source file:samples.websocket.jetty93.echo.CustomContainerWebSocketsApplicationTests.java
@Test public void reverseEndpoint() throws Exception { ConfigurableApplicationContext context = new SpringApplicationBuilder(ClientConfiguration.class, PropertyPlaceholderAutoConfiguration.class) .properties("websocket.uri:ws://localhost:" + PORT + "/ws/reverse") .run("--spring.main.web_environment=false"); long count = context.getBean(ClientConfiguration.class).latch.getCount(); AtomicReference<String> messagePayloadReference = context.getBean(ClientConfiguration.class).messagePayload; context.close();// ww w . ja va 2 s . c om assertThat(count).isEqualTo(0); assertThat(messagePayloadReference.get()).isEqualTo("Reversed: !dlrow olleH"); }