List of usage examples for org.springframework.context ConfigurableApplicationContext getBean
Object getBean(String name) throws BeansException;
From source file:org.springframework.amqp.rabbit.retry.MissingIdRetryTests.java
@SuppressWarnings("rawtypes") @Test//from w ww .j a v a 2 s . c o m public void testWithId() throws Exception { // 2 messages; each retried twice by retry interceptor this.latch = new CountDownLatch(6); 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.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); fb.setMessageRecoverer(new RejectAndDontRequeueRecoverer()); Advice retryInterceptor = fb.getObject(); container.setAdviceChain(retryInterceptor); container.start(); MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("text/plain"); messageProperties.setMessageId("foo"); Message message = new Message("Hello, world!".getBytes(), messageProperties); template.send("retry.test.exchange", "retry.test.binding", message); template.send("retry.test.exchange", "retry.test.binding", message); 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); } ArgumentCaptor putCaptor = ArgumentCaptor.forClass(Object.class); ArgumentCaptor getCaptor = ArgumentCaptor.forClass(Object.class); ArgumentCaptor removeCaptor = ArgumentCaptor.forClass(Object.class); verify(cache, times(6)).put(putCaptor.capture(), any(RetryContext.class)); verify(cache, times(6)).get(getCaptor.capture()); verify(cache, atLeast(2)).remove(removeCaptor.capture()); verify(cache, atMost(4)).remove(removeCaptor.capture()); logger.debug("puts:" + putCaptor.getAllValues()); logger.debug("gets:" + putCaptor.getAllValues()); logger.debug("removes:" + removeCaptor.getAllValues()); assertEquals("Expected map.size() = 0, was: " + map.size(), 0, map.size()); } finally { container.stop(); ctx.close(); } }
From source file:org.springframework.amqp.rabbit.retry.MissingIdRetryTests.java
@SuppressWarnings("rawtypes") @Test/*from w w w.j a v a2 s .c om*/ public void testWithIdAndSuccess() throws Exception { // 2 messages; each retried twice by retry interceptor this.latch = new CountDownLatch(6); 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); final Set<String> processed = new HashSet<>(); final CountDownLatch latch = new CountDownLatch(4); container.setMessageListener(m -> { latch.countDown(); if (!processed.contains(m.getMessageProperties().getMessageId())) { processed.add(m.getMessageProperties().getMessageId()); throw new RuntimeException("fail"); } }); 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); fb.setMessageRecoverer(new RejectAndDontRequeueRecoverer()); Advice retryInterceptor = fb.getObject(); container.setAdviceChain(retryInterceptor); container.start(); MessageProperties messageProperties = new MessageProperties(); messageProperties.setContentType("text/plain"); messageProperties.setMessageId("foo"); Message message = new Message("Hello, world!".getBytes(), messageProperties); template.send("retry.test.exchange", "retry.test.binding", message); messageProperties.setMessageId("bar"); template.send("retry.test.exchange", "retry.test.binding", message); 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); } ArgumentCaptor putCaptor = ArgumentCaptor.forClass(Object.class); ArgumentCaptor getCaptor = ArgumentCaptor.forClass(Object.class); ArgumentCaptor removeCaptor = ArgumentCaptor.forClass(Object.class); verify(cache, times(2)).put(putCaptor.capture(), any(RetryContext.class)); verify(cache, times(2)).get(getCaptor.capture()); verify(cache, atLeast(2)).remove(removeCaptor.capture()); verify(cache, atMost(4)).remove(removeCaptor.capture()); logger.debug("puts:" + putCaptor.getAllValues()); logger.debug("gets:" + putCaptor.getAllValues()); logger.debug("removes:" + removeCaptor.getAllValues()); assertEquals("Expected map.size() = 0, was: " + map.size(), 0, map.size()); } finally { container.stop(); ctx.close(); } }
From source file:org.springframework.amqp.rabbit.stocks.ui.StockPanel.java
public static void main(String[] a) { ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("client-bootstrap-config.xml"); StockController controller = context.getBean(StockController.class); JFrame f = new JFrame("Rabbit Stock Demo"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //TODO consider @Configurable f.add(new StockPanel(controller)); f.pack();//from w ww.ja va 2s .c om f.setVisible(true); }
From source file:org.springframework.batch.core.configuration.support.DefaultJobLoader.java
@SuppressWarnings("resource") private Collection<Job> doLoad(ApplicationContextFactory factory, boolean unregister) throws DuplicateJobException { Collection<String> jobNamesBefore = jobRegistry.getJobNames(); ConfigurableApplicationContext context = factory.createApplicationContext(); Collection<String> jobNamesAfter = jobRegistry.getJobNames(); // Try to detect auto-registration (e.g. through a bean post processor) boolean autoRegistrationDetected = jobNamesAfter.size() > jobNamesBefore.size(); Collection<String> jobsRegistered = new HashSet<String>(); if (autoRegistrationDetected) { for (String name : jobNamesAfter) { if (!jobNamesBefore.contains(name)) { jobsRegistered.add(name); }/*from w ww. j av a 2 s . co m*/ } } contexts.put(factory, context); String[] names = context.getBeanNamesForType(Job.class); for (String name : names) { if (!autoRegistrationDetected) { Job job = (Job) context.getBean(name); String jobName = job.getName(); // On reload try to unregister first if (unregister) { if (logger.isDebugEnabled()) { logger.debug( "Unregistering job: " + jobName + " from context: " + context.getDisplayName()); } doUnregister(jobName); } if (logger.isDebugEnabled()) { logger.debug("Registering job: " + jobName + " from context: " + context.getDisplayName()); } doRegister(context, job); jobsRegistered.add(jobName); } } Collection<Job> result = new ArrayList<Job>(); for (String name : jobsRegistered) { try { result.add(jobRegistry.getJob(name)); } catch (NoSuchJobException e) { // should not happen; throw new IllegalStateException("Could not retrieve job that was should have been registered", e); } } contextToJobNames.put(context, jobsRegistered); return result; }
From source file:org.springframework.batch.core.launch.support.CommandLineJobRunner.java
@SuppressWarnings("resource") int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) { ConfigurableApplicationContext context = null; try {/* w w w . ja va 2s .c o m*/ try { context = new AnnotationConfigApplicationContext(Class.forName(jobPath)); } catch (ClassNotFoundException cnfe) { context = new ClassPathXmlApplicationContext(jobPath); } context.getAutowireCapableBeanFactory().autowireBeanProperties(this, AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false); Assert.state(launcher != null, "A JobLauncher must be provided. Please add one to the configuration."); if (opts.contains("-restart") || opts.contains("-next")) { Assert.state(jobExplorer != null, "A JobExplorer must be provided for a restart or start next operation. Please add one to the configuration."); } String jobName = jobIdentifier; JobParameters jobParameters = jobParametersConverter .getJobParameters(StringUtils.splitArrayElementsIntoProperties(parameters, "=")); Assert.isTrue(parameters == null || parameters.length == 0 || !jobParameters.isEmpty(), "Invalid JobParameters " + Arrays.asList(parameters) + ". If parameters are provided they should be in the form name=value (no whitespace)."); if (opts.contains("-stop")) { List<JobExecution> jobExecutions = getRunningJobExecutions(jobIdentifier); if (jobExecutions == null) { throw new JobExecutionNotRunningException( "No running execution found for job=" + jobIdentifier); } for (JobExecution jobExecution : jobExecutions) { jobExecution.setStatus(BatchStatus.STOPPING); jobRepository.update(jobExecution); } return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode()); } if (opts.contains("-abandon")) { List<JobExecution> jobExecutions = getStoppedJobExecutions(jobIdentifier); if (jobExecutions == null) { throw new JobExecutionNotStoppedException( "No stopped execution found for job=" + jobIdentifier); } for (JobExecution jobExecution : jobExecutions) { jobExecution.setStatus(BatchStatus.ABANDONED); jobRepository.update(jobExecution); } return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode()); } if (opts.contains("-restart")) { JobExecution jobExecution = getLastFailedJobExecution(jobIdentifier); if (jobExecution == null) { throw new JobExecutionNotFailedException( "No failed or stopped execution found for job=" + jobIdentifier); } jobParameters = jobExecution.getJobParameters(); jobName = jobExecution.getJobInstance().getJobName(); } Job job = null; if (jobLocator != null) { try { job = jobLocator.getJob(jobName); } catch (NoSuchJobException e) { } } if (job == null) { job = (Job) context.getBean(jobName); } if (opts.contains("-next")) { JobParameters nextParameters = getNextJobParameters(job); Map<String, JobParameter> map = new HashMap<String, JobParameter>(nextParameters.getParameters()); map.putAll(jobParameters.getParameters()); jobParameters = new JobParameters(map); } JobExecution jobExecution = launcher.run(job, jobParameters); return exitCodeMapper.intValue(jobExecution.getExitStatus().getExitCode()); } catch (Throwable e) { String message = "Job Terminated in error: " + e.getMessage(); logger.error(message, e); CommandLineJobRunner.message = message; return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode()); } finally { if (context != null) { context.close(); } } }
From source file:org.springframework.cloud.stream.binder.test.integration.EndToEndIntegrationTests.java
private Sender createSender(String... arguments) { ConfigurableApplicationContext context = new SpringApplicationBuilder(SenderApplication.class) .bannerMode(Banner.Mode.OFF).build() .run(applicationArguments(String.format(OUTPUT_DESTINATION_FORMAT, this.destination), arguments)); startedContexts.add(context);/*from w ww . jav a 2 s .c om*/ return context.getBean(Sender.class); }
From source file:org.springframework.cloud.stream.binder.test.integration.EndToEndIntegrationTests.java
private Receiver createReceiver(String... arguments) { ConfigurableApplicationContext context = new SpringApplicationBuilder(ReceiverApplication.class) .bannerMode(Banner.Mode.OFF).build() .run(applicationArguments(String.format(INPUT_DESTINATION_FORMAT, this.destination), arguments)); startedContexts.add(context);/*from www . j a va 2 s .c om*/ return context.getBean(Receiver.class); }
From source file:org.springframework.cloud.stream.metrics.ApplicationMetricsExporterTests.java
@Test(expected = NoSuchBeanDefinitionException.class) public void checkDisabledConfiguration() throws Exception { ConfigurableApplicationContext applicationContext = SpringApplication.run(BinderExporterApplication.class, "--server.port=0", "--spring.jmx.enabled=false"); try {/*from w w w. j a v a 2s. c om*/ applicationContext.getBean(Emitter.class); } catch (Exception e) { throw e; } finally { applicationContext.close(); } }
From source file:org.springframework.cloud.stream.metrics.ApplicationMetricsExporterTests.java
@Test public void defaultIncludes() throws Exception { ConfigurableApplicationContext applicationContext = SpringApplication.run(BinderExporterApplication.class, "--server.port=0", "--spring.jmx.enabled=false", "--spring.metrics.export.delay-millis=500", "--spring.cloud.stream.bindings." + Emitter.APPLICATION_METRICS + ".destination=foo"); Emitter emitterSource = applicationContext.getBean(Emitter.class); MessageCollector collector = applicationContext.getBean(MessageCollector.class); Message<?> message = collector.forChannel(emitterSource.applicationMetrics()).poll(10, TimeUnit.SECONDS); Assert.assertNotNull(message);/* w ww. j a v a 2 s . c o m*/ ObjectMapper mapper = applicationContext.getBean(ObjectMapper.class); ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(), ApplicationMetrics.class); Assert.assertTrue( contains("integration.channel.errorChannel.errorRate.mean", applicationMetrics.getMetrics())); Assert.assertEquals("application", applicationMetrics.getName()); Assert.assertTrue(CollectionUtils.isEmpty(applicationMetrics.getProperties())); applicationContext.close(); }
From source file:org.springframework.cloud.stream.metrics.ApplicationMetricsExporterTests.java
@Test public void customAppNameAndIndex() throws Exception { ConfigurableApplicationContext applicationContext = SpringApplication.run(BinderExporterApplication.class, "--server.port=0", "--spring.jmx.enabled=false", "--spring.metrics.export.delay-millis=500", "--spring.application.name=foo", "--spring.cloud.stream.bindings." + Emitter.APPLICATION_METRICS + ".destination=foo"); Emitter emitterSource = applicationContext.getBean(Emitter.class); MessageCollector collector = applicationContext.getBean(MessageCollector.class); Message<?> message = collector.forChannel(emitterSource.applicationMetrics()).poll(10, TimeUnit.SECONDS); Assert.assertNotNull(message);//www. jav a 2s .c o m ObjectMapper mapper = applicationContext.getBean(ObjectMapper.class); ApplicationMetrics applicationMetrics = mapper.readValue((String) message.getPayload(), ApplicationMetrics.class); Assert.assertTrue( contains("integration.channel.errorChannel.errorRate.mean", applicationMetrics.getMetrics())); Assert.assertTrue(contains("mem", applicationMetrics.getMetrics())); Assert.assertEquals("foo", applicationMetrics.getName()); Assert.assertTrue(CollectionUtils.isEmpty(applicationMetrics.getProperties())); applicationContext.close(); }