CAMEL-11261 Revise Camel context destruction in... ... Spring (Boot) applications
This changes the way `CamelContext` is started/stopped when used with Spring Framework. It uses `ContextRefreshedEvent` for startup and `Lifecycle::stop` to stop, the reason why `Lifecycle` can't be used for startup is that only beans that implement `SmartLifecycle` are started and `SpringCamelContext` can't implement `SmartLifecycle` because of overlapping `isAutoStartupMethod` in `RuntimeConfiguration` and `SmartLifecycle` with different return types -- that cannot be used as covariant return type as the `SmartLifecycle` signature uses primitive type. The order of startup is quite important, as some changes to Camel context are not properly expressed if made after context startup (for instance `EndpointStrategy` change), so `SpringCamelContext` has `LOWEST_PRECEDENCE` and `RoutesCollector`s, `CamelContextFactoryBean` have +1 precedence over that in order to add routes and setup context before startup. Using `ContextRefreshedEvent` is actually better than using `SmartLifecycle` as `SmartLifecycle` invocation precedes `ContextRefreshedEvent` emission, so there could be beans in the context that also start on `ContextRefreshedEvent` and Camel would start before those. One side note on using events is that at some point Spring might default, however unlikely that seems, to using multi-threaded event listener invocation, so this might complicate things. Project: http://git-wip-us.apache.org/repos/asf/camel/repo Commit: http://git-wip-us.apache.org/repos/asf/camel/commit/fbf0ffad Tree: http://git-wip-us.apache.org/repos/asf/camel/tree/fbf0ffad Diff: http://git-wip-us.apache.org/repos/asf/camel/diff/fbf0ffad Branch: refs/heads/master Commit: fbf0ffad627b42088705afe0e29c5ebc1a77809a Parents: 7558e63 Author: Zoran Regvart <[email protected]> Authored: Fri May 26 11:13:13 2017 +0200 Committer: Zoran Regvart <[email protected]> Committed: Sun May 28 21:56:18 2017 +0200 ---------------------------------------------------------------------- ...pringQuartzTwoAppsClusteredFailoverTest.java | 5 + ...rtzConsumerTwoAppsClusteredRecoveryTest.java | 23 +- ...pringQuartzTwoAppsClusteredFailoverTest.java | 10 +- components/camel-spring-boot/pom.xml | 5 + .../spring/boot/CamelAutoConfiguration.java | 40 +++- .../camel/spring/boot/RoutesCollector.java | 17 +- .../boot/TypeConversionConfiguration.java | 10 +- .../spring/boot/StartupShutdownOrderTest.java | 238 ++++++++++++++++++ .../spring/javaconfig/CamelConfiguration.java | 1 - .../spring/javaconfig/RoutesCollector.java | 10 +- .../camel/spring/javaconfig/MainTest.java | 15 +- components/camel-spring/pom.xml | 6 + .../camel/spring/CamelContextFactoryBean.java | 105 +++++--- .../apache/camel/spring/SpringCamelContext.java | 146 ++++++----- .../rest/SpringFromRestDuplicateTest.java | 6 +- .../spring/CircularComponentCreationTest.java | 3 +- .../spring/StartupShutdownOrderBaseTest.java | 239 +++++++++++++++++++ ...nSpringCamelContextFactoryBeanOrderTest.java | 43 ++++ ...rtupShutdownSpringCamelContextOrderTest.java | 41 ++++ .../spring/config/SpringRouteNoFromTest.java | 6 +- .../spring/config/SpringRouteNoOutputTest.java | 8 +- .../file/SpringFileConsumerPreMoveTest.java | 14 +- .../spring/issues/MisspelledRouteRefTest.java | 24 +- .../issues/SpringMainStartFailedIssueTest.java | 6 +- ...ringCamelContextStartingFailedEventTest.java | 10 +- ...adLetterChannelInvalidDeadLetterUriTest.java | 11 +- ...erChannelInvalidOptionDeadLetterUriTest.java | 11 +- ...gDoubleLoadBalancerMisconfigurationTest.java | 7 +- .../SpringRouteTopLevelMisconfiguredTest.java | 17 +- .../SpringTryCatchMisconfiguredTest.java | 18 +- ...TryCatchMustHaveExceptionConfiguredTest.java | 9 +- .../CamelSpringBootExecutionListener.java | 13 + 32 files changed, 890 insertions(+), 227 deletions(-) ---------------------------------------------------------------------- http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-quartz/src/test/java/org/apache/camel/routepolicy/quartz/SpringQuartzTwoAppsClusteredFailoverTest.java ---------------------------------------------------------------------- diff --git a/components/camel-quartz/src/test/java/org/apache/camel/routepolicy/quartz/SpringQuartzTwoAppsClusteredFailoverTest.java b/components/camel-quartz/src/test/java/org/apache/camel/routepolicy/quartz/SpringQuartzTwoAppsClusteredFailoverTest.java index b0df94f..c08e7e8 100644 --- a/components/camel-quartz/src/test/java/org/apache/camel/routepolicy/quartz/SpringQuartzTwoAppsClusteredFailoverTest.java +++ b/components/camel-quartz/src/test/java/org/apache/camel/routepolicy/quartz/SpringQuartzTwoAppsClusteredFailoverTest.java @@ -22,6 +22,7 @@ import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.TestSupport; import org.apache.camel.util.IOHelper; import org.junit.Test; +import org.quartz.Scheduler; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -61,6 +62,10 @@ public class SpringQuartzTwoAppsClusteredFailoverTest extends TestSupport { // now let's simulate a crash of the first app (the quartz instance 'app-one') log.warn("The first app is going to crash NOW!"); + // we need to stop the Scheduler first as the CamelContext will gracefully shutdown and + // delete all scheduled jobs, so there would be nothing for the second CamelContext to + // failover from + app.getBean(Scheduler.class).shutdown(); IOHelper.close(app); log.warn("Crashed..."); http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-quartz2/src/test/java/org/apache/camel/component/quartz2/SpringQuartzConsumerTwoAppsClusteredRecoveryTest.java ---------------------------------------------------------------------- diff --git a/components/camel-quartz2/src/test/java/org/apache/camel/component/quartz2/SpringQuartzConsumerTwoAppsClusteredRecoveryTest.java b/components/camel-quartz2/src/test/java/org/apache/camel/component/quartz2/SpringQuartzConsumerTwoAppsClusteredRecoveryTest.java index 9758097..f4818d8 100644 --- a/components/camel-quartz2/src/test/java/org/apache/camel/component/quartz2/SpringQuartzConsumerTwoAppsClusteredRecoveryTest.java +++ b/components/camel-quartz2/src/test/java/org/apache/camel/component/quartz2/SpringQuartzConsumerTwoAppsClusteredRecoveryTest.java @@ -32,8 +32,6 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Tests a Quartz based cluster setup of two Camel Apps being triggered through with recoverableJob option is true {@link QuartzConsumer}. - * - * @version */ public class SpringQuartzConsumerTwoAppsClusteredRecoveryTest extends TestSupport { @@ -41,25 +39,24 @@ public class SpringQuartzConsumerTwoAppsClusteredRecoveryTest extends TestSuppor public void testQuartzPersistentStoreClusteredApp() throws Exception { // boot up the database the two apps are going to share inside a clustered quartz setup AbstractXmlApplicationContext db = new ClassPathXmlApplicationContext("org/apache/camel/component/quartz2/SpringQuartzConsumerClusteredAppDatabase.xml"); - db.start(); // now launch the first clustered app which will acquire the quartz database lock and become the master AbstractXmlApplicationContext app = new ClassPathXmlApplicationContext("org/apache/camel/component/quartz2/SpringQuartzConsumerRecoveryClusteredAppOne.xml"); - app.start(); - + // now let's simulate a crash of the first app (the quartz instance 'app-one') log.warn("The first app is going to crash NOW!"); + IOHelper.close(app); log.warn("Crashed..."); log.warn("Crashed..."); log.warn("Crashed..."); - + Thread.sleep(2000); - + // as well as the second one which will run in slave mode as it will not be able to acquire the same lock AbstractXmlApplicationContext app2 = new ClassPathXmlApplicationContext("org/apache/camel/component/quartz2/SpringQuartzConsumerRecoveryClusteredAppTwo.xml"); app2.start(); - + // wait long enough until the second app takes it over... Thread.sleep(20000); // inside the logs one can then clearly see how the route of the second app ('app-two') starts consuming: @@ -81,22 +78,22 @@ public class SpringQuartzConsumerTwoAppsClusteredRecoveryTest extends TestSuppor // and as the last step shutdown the second app as well as the database IOHelper.close(app2, db); } - + private static class ClusteringPredicate implements Predicate { private final String expectedPayload; - + ClusteringPredicate(boolean pings) { expectedPayload = pings ? "clustering PINGS!" : "clustering PONGS!"; } - + @Override public boolean matches(Exchange exchange) { return exchange.getIn().getBody().equals(expectedPayload); } } - + public static class MyProcessor implements Processor, ApplicationContextAware { ApplicationContext applicationContext; @@ -110,7 +107,7 @@ public class SpringQuartzConsumerTwoAppsClusteredRecoveryTest extends TestSuppor public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } - + } } http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-quartz2/src/test/java/org/apache/camel/routepolicy/quartz2/SpringQuartzTwoAppsClusteredFailoverTest.java ---------------------------------------------------------------------- diff --git a/components/camel-quartz2/src/test/java/org/apache/camel/routepolicy/quartz2/SpringQuartzTwoAppsClusteredFailoverTest.java b/components/camel-quartz2/src/test/java/org/apache/camel/routepolicy/quartz2/SpringQuartzTwoAppsClusteredFailoverTest.java index 30cce7f..cacf44e 100644 --- a/components/camel-quartz2/src/test/java/org/apache/camel/routepolicy/quartz2/SpringQuartzTwoAppsClusteredFailoverTest.java +++ b/components/camel-quartz2/src/test/java/org/apache/camel/routepolicy/quartz2/SpringQuartzTwoAppsClusteredFailoverTest.java @@ -22,13 +22,12 @@ import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.TestSupport; import org.apache.camel.util.IOHelper; import org.junit.Test; +import org.quartz.Scheduler; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Tests a Quartz based cluster setup of two Camel Apps being triggered through {@link CronScheduledRoutePolicy}. - * - * @version */ public class SpringQuartzTwoAppsClusteredFailoverTest extends TestSupport { @@ -36,15 +35,12 @@ public class SpringQuartzTwoAppsClusteredFailoverTest extends TestSupport { public void testQuartzPersistentStoreClusteredApp() throws Exception { // boot up the database the two apps are going to share inside a clustered quartz setup AbstractXmlApplicationContext db = new ClassPathXmlApplicationContext("org/apache/camel/routepolicy/quartz2/SpringQuartzClusteredAppDatabase.xml"); - db.start(); // now launch the first clustered app which will acquire the quartz database lock and become the master AbstractXmlApplicationContext app = new ClassPathXmlApplicationContext("org/apache/camel/routepolicy/quartz2/SpringQuartzClusteredAppOne.xml"); - app.start(); // as well as the second one which will run in slave mode as it will not be able to acquire the same lock AbstractXmlApplicationContext app2 = new ClassPathXmlApplicationContext("org/apache/camel/routepolicy/quartz2/SpringQuartzClusteredAppTwo.xml"); - app2.start(); CamelContext camel = app.getBean("camelContext", CamelContext.class); @@ -61,6 +57,10 @@ public class SpringQuartzTwoAppsClusteredFailoverTest extends TestSupport { // now let's simulate a crash of the first app (the quartz instance 'app-one') log.warn("The first app is going to crash NOW!"); + // we need to stop the Scheduler first as the CamelContext will gracefully shutdown and + // delete all scheduled jobs, so there would be nothing for the second CamelContext to + // failover from + app.getBean(Scheduler.class).shutdown(); IOHelper.close(app); log.warn("Crashed..."); http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring-boot/pom.xml ---------------------------------------------------------------------- diff --git a/components/camel-spring-boot/pom.xml b/components/camel-spring-boot/pom.xml index afc77a8..c2dd5b5 100644 --- a/components/camel-spring-boot/pom.xml +++ b/components/camel-spring-boot/pom.xml @@ -83,6 +83,11 @@ <scope>test</scope> </dependency> <dependency> + <groupId>org.apache.camel</groupId> + <artifactId>camel-core-xml</artifactId> + <scope>test</scope> + </dependency> + <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/CamelAutoConfiguration.java ---------------------------------------------------------------------- diff --git a/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/CamelAutoConfiguration.java b/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/CamelAutoConfiguration.java index c46e758..4a8fcbb 100644 --- a/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/CamelAutoConfiguration.java +++ b/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/CamelAutoConfiguration.java @@ -77,7 +77,13 @@ public class CamelAutoConfiguration { /** * Spring-aware Camel context for the application. Auto-detects and loads all routes available in the Spring context. */ - @Bean + // We explicitly declare the destroyMethod to be "" as the Spring @Bean + // annotation defaults to AbstractBeanDefinition.INFER_METHOD otherwise + // and in that case CamelContext::shutdown or CamelContext::stop would + // be used for bean destruction. As SpringCamelContext is a lifecycle + // bean (implements Lifecycle) additional invocations of shutdown or + // close would be superfluous. + @Bean(destroyMethod = "") @ConditionalOnMissingBean(CamelContext.class) CamelContext camelContext(ApplicationContext applicationContext, CamelConfigurationProperties config) { @@ -95,7 +101,6 @@ public class CamelAutoConfiguration { } CamelContext camelContext = new SpringCamelContext(applicationContext); - SpringCamelContext.setNoStart(true); if (!config.isJmxEnabled()) { camelContext.disableJMX(); @@ -202,11 +207,6 @@ public class CamelAutoConfiguration { @Bean CamelSpringBootApplicationController applicationController(ApplicationContext applicationContext, CamelContext camelContext) { - // CAMEL-10279: We have to call setNoStart(true) here so that if a <camelContext> is imported via - // @ImportResource then it does not get started before the RoutesCollector gets a chance to add any - // routes found in RouteBuilders. Even if no RouteBuilders are found, the RoutesCollector will handle - // starting the the Camel Context. - SpringCamelContext.setNoStart(true); return new CamelSpringBootApplicationController(applicationContext, camelContext); } @@ -220,12 +220,17 @@ public class CamelAutoConfiguration { /** * Default producer template for the bootstrapped Camel context. */ - @Bean(initMethod = "", destroyMethod = "") - // Camel handles the lifecycle of this bean + // We explicitly declare the destroyMethod to be "" as the Spring @Bean + // annotation defaults to AbstractBeanDefinition.INFER_METHOD otherwise + // and in that case Service::close (ProducerTemplate implements Service) + // would be used for bean destruction. And we want Camel to handle the + // lifecycle. + @Bean(destroyMethod = "") @ConditionalOnMissingBean(ProducerTemplate.class) ProducerTemplate producerTemplate(CamelContext camelContext, CamelConfigurationProperties config) throws Exception { final ProducerTemplate producerTemplate = camelContext.createProducerTemplate(config.getProducerTemplateCacheSize()); + // we add this producerTemplate as a Service to CamelContext so that it performs proper lifecycle (start and stop) camelContext.addService(producerTemplate); return producerTemplate; } @@ -233,12 +238,17 @@ public class CamelAutoConfiguration { /** * Default consumer template for the bootstrapped Camel context. */ - @Bean(initMethod = "", destroyMethod = "") - // Camel handles the lifecycle of this bean + // We explicitly declare the destroyMethod to be "" as the Spring @Bean + // annotation defaults to AbstractBeanDefinition.INFER_METHOD otherwise + // and in that case Service::close (ConsumerTemplate implements Service) + // would be used for bean destruction. And we want Camel to handle the + // lifecycle. + @Bean(destroyMethod = "") @ConditionalOnMissingBean(ConsumerTemplate.class) ConsumerTemplate consumerTemplate(CamelContext camelContext, CamelConfigurationProperties config) throws Exception { final ConsumerTemplate consumerTemplate = camelContext.createConsumerTemplate(config.getConsumerTemplateCacheSize()); + // we add this consumerTemplate as a Service to CamelContext so that it performs proper lifecycle (start and stop) camelContext.addService(consumerTemplate); return consumerTemplate; } @@ -250,8 +260,12 @@ public class CamelAutoConfiguration { return new SpringPropertiesParser(); } - @Bean(initMethod = "", destroyMethod = "") - // Camel handles the lifecycle of this bean + // We explicitly declare the destroyMethod to be "" as the Spring @Bean + // annotation defaults to AbstractBeanDefinition.INFER_METHOD otherwise + // and in that case ShutdownableService::shutdown/Service::close + // (PropertiesComponent extends ServiceSupport) would be used for bean + // destruction. And we want Camel to handle the lifecycle. + @Bean(destroyMethod = "") PropertiesComponent properties(CamelContext camelContext, PropertiesParser parser) { if (camelContext.hasComponent("properties") != null) { return camelContext.getComponent("properties", PropertiesComponent.class); http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/RoutesCollector.java ---------------------------------------------------------------------- diff --git a/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/RoutesCollector.java b/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/RoutesCollector.java index ce78b01..d14ef06 100644 --- a/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/RoutesCollector.java +++ b/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/RoutesCollector.java @@ -41,20 +41,21 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.core.Ordered; import org.springframework.core.io.Resource; /** * Collects routes and rests from the various sources (like Spring application context beans registry or opinionated * classpath locations) and injects these into the Camel context. */ -public class RoutesCollector implements ApplicationListener<ContextRefreshedEvent> { +public class RoutesCollector implements ApplicationListener<ContextRefreshedEvent>, Ordered { // Static collaborators private static final Logger LOG = LoggerFactory.getLogger(RoutesCollector.class); // Collaborators - + private final ApplicationContext applicationContext; private final List<CamelContextConfiguration> camelContextConfigurations; @@ -193,6 +194,18 @@ public class RoutesCollector implements ApplicationListener<ContextRefreshedEven } } + @Override + public int getOrder() { + // RoutesCollector implements Ordered so that it's the + // second to last in ApplicationListener to receive events, + // SpringCamelContext should be the last one, + // CamelContextFactoryBean should be on par with + // RoutesCollector this is important for startup as we want + // all resources to be ready and all routes added to the + // context + return LOWEST_PRECEDENCE - 1; + } + private void maybeStart(CamelContext camelContext) throws Exception { // for example from unit testing we want to start Camel later and not when Spring framework // publish a ContextRefreshedEvent http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/TypeConversionConfiguration.java ---------------------------------------------------------------------- diff --git a/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/TypeConversionConfiguration.java b/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/TypeConversionConfiguration.java index b328f5d..f49cb31 100644 --- a/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/TypeConversionConfiguration.java +++ b/components/camel-spring-boot/src/main/java/org/apache/camel/spring/boot/TypeConversionConfiguration.java @@ -33,14 +33,18 @@ import org.springframework.core.convert.support.DefaultConversionService; @ConditionalOnProperty(value = "camel.springboot.typeConversion", matchIfMissing = true) public class TypeConversionConfiguration { - @Bean(initMethod = "", destroyMethod = "") + // We explicitly declare the destroyMethod to be "" as the Spring @Bean + // annotation defaults to AbstractBeanDefinition.INFER_METHOD otherwise + // and in that case ShutdownableService::shutdown/Service::close + // (BaseTypeConverterRegistry extends ServiceSupport) would be used for + // bean destruction. And we want Camel to handle the lifecycle. + @Bean(destroyMethod = "") // Camel handles the lifecycle of this bean TypeConverter typeConverter(CamelContext camelContext) { return camelContext.getTypeConverter(); } - @Bean(initMethod = "", destroyMethod = "") - // Camel handles the lifecycle of this bean + @Bean SpringTypeConverter springTypeConverter(CamelContext camelContext, ConversionService[] conversionServices) { SpringTypeConverter springTypeConverter = new SpringTypeConverter(asList(conversionServices)); camelContext.getTypeConverterRegistry().addFallbackTypeConverter(springTypeConverter, true); http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring-boot/src/test/java/org/apache/camel/spring/boot/StartupShutdownOrderTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring-boot/src/test/java/org/apache/camel/spring/boot/StartupShutdownOrderTest.java b/components/camel-spring-boot/src/test/java/org/apache/camel/spring/boot/StartupShutdownOrderTest.java new file mode 100644 index 0000000..3884147 --- /dev/null +++ b/components/camel-spring-boot/src/test/java/org/apache/camel/spring/boot/StartupShutdownOrderTest.java @@ -0,0 +1,238 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.spring.boot; + +import java.util.Map; + +import org.apache.camel.CamelContext; +import org.apache.camel.support.ServiceSupport; +import org.junit.Test; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.Lifecycle; +import org.springframework.context.SmartLifecycle; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; + +import static org.assertj.core.api.Assertions.assertThat; + +public class StartupShutdownOrderTest { + + static class AutoCloseableBean implements AutoCloseable, TestState { + + boolean closed; + + private final ApplicationContext context; + + public AutoCloseableBean(final ApplicationContext context) { + this.context = context; + } + + @Override + public void assertValid() { + assertThat(closed).as("AutoCloseable bean should be closed").isTrue(); + } + + @Override + public void close() { + assertThat(camelIsStopped(context)).as("AutoCloseable bean should be stopped after Camel").isTrue(); + closed = true; + } + } + + static class Beans { + + @Bean + AutoCloseableBean autoCloseableBean(final ApplicationContext context) { + return new AutoCloseableBean(context); + } + + @Bean + BeanWithShutdownMethod beanWithCloseMethod(final ApplicationContext context) { + return new BeanWithShutdownMethod(context); + } + + @Bean + DisposeBean disposedBean(final ApplicationContext context) { + return new DisposeBean(context); + } + + @Bean + InitBean initBean(final ApplicationContext context) { + return new InitBean(context); + } + + @Bean + Lifecycle lifecycleBean(final ApplicationContext context) { + return new LifecycleBean(context); + } + } + + static class BeanWithShutdownMethod implements TestState { + + boolean shutdown; + + private final ApplicationContext context; + + public BeanWithShutdownMethod(final ApplicationContext context) { + this.context = context; + } + + @Override + public void assertValid() { + assertThat(shutdown).as("Bean with shutdown method should be shutdown").isTrue(); + } + + public void shutdown() { + assertThat(camelIsStopped(context)).as("@Bean with close() method should be stopped after Camel").isTrue(); + shutdown = true; + } + } + + static class DisposeBean implements DisposableBean, TestState { + + boolean disposed; + + private final ApplicationContext context; + + public DisposeBean(final ApplicationContext context) { + this.context = context; + } + + @Override + public void assertValid() { + assertThat(disposed).as("DisposableBean should be disposed").isTrue(); + } + + @Override + public void destroy() throws Exception { + assertThat(camelIsStopped(context)).as("DisposableBean should be stopped after Camel").isTrue(); + disposed = true; + } + } + + static class InitBean implements InitializingBean, TestState { + + ApplicationContext context; + + boolean initialized; + + @Autowired + public InitBean(final ApplicationContext context) { + this.context = context; + } + + @Override + public void afterPropertiesSet() throws Exception { + assertThat(camelIsStopped(context)).as("initializing bean should be started before Camel").isTrue(); + initialized = true; + } + + @Override + public void assertValid() { + assertThat(initialized).as("InitializingBean should be initialized").isTrue(); + } + } + + static class LifecycleBean implements SmartLifecycle, TestState { + + ApplicationContext context; + + boolean started; + + boolean stopped; + + @Autowired + public LifecycleBean(final ApplicationContext context) { + this.context = context; + } + + @Override + public void assertValid() { + assertThat(started).as("Lifecycle should have been started").isTrue(); + assertThat(stopped).as("Lifecycle should be stopped").isTrue(); + } + + @Override + public int getPhase() { + return 0; + } + + @Override + public boolean isAutoStartup() { + return true; + } + + @Override + public boolean isRunning() { + return started; + } + + @Override + public void start() { + assertThat(camelIsStopped(context)).as("lifecycle bean should be started before Camel").isTrue(); + started = true; + } + + @Override + public void stop() { + assertThat(camelIsStopped(context)).as("lifecycle bean should be stopped after Camel").isTrue(); + stopped = true; + } + + @Override + public void stop(final Runnable callback) { + stop(); + callback.run(); + } + } + + interface TestState { + void assertValid(); + } + + @Test + public void camelContextShouldBeStartedLastAndStoppedFirst() { + final ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( + CamelAutoConfiguration.class, Beans.class); + + final ServiceSupport camelContext = (ServiceSupport) context.getBean(CamelContext.class); + final Map<String, TestState> testStates = context.getBeansOfType(TestState.class); + + assertThat(camelContext.isStarted()).as("Camel context should be started").isTrue(); + + context.close(); + + assertThat(camelContext.isStopped()).as("Camel context should be stopped").isTrue(); + testStates.values().stream().forEach(TestState::assertValid); + } + + static ServiceSupport camel(final ApplicationContext context) { + return (ServiceSupport) context.getBean(CamelContext.class); + } + + static boolean camelIsStarted(final ApplicationContext context) { + return camel(context).isStarted(); + } + + static boolean camelIsStopped(final ApplicationContext context) { + return !camelIsStarted(context); + } +} http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring-javaconfig/src/main/java/org/apache/camel/spring/javaconfig/CamelConfiguration.java ---------------------------------------------------------------------- diff --git a/components/camel-spring-javaconfig/src/main/java/org/apache/camel/spring/javaconfig/CamelConfiguration.java b/components/camel-spring-javaconfig/src/main/java/org/apache/camel/spring/javaconfig/CamelConfiguration.java index d0cbc2b..6900e6e 100644 --- a/components/camel-spring-javaconfig/src/main/java/org/apache/camel/spring/javaconfig/CamelConfiguration.java +++ b/components/camel-spring-javaconfig/src/main/java/org/apache/camel/spring/javaconfig/CamelConfiguration.java @@ -158,7 +158,6 @@ public abstract class CamelConfiguration implements BeanFactoryAware, Applicatio @Bean public CamelContext camelContext() throws Exception { CamelContext camelContext = createCamelContext(); - SpringCamelContext.setNoStart(true); setupCamelContext(camelContext); return camelContext; } http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring-javaconfig/src/main/java/org/apache/camel/spring/javaconfig/RoutesCollector.java ---------------------------------------------------------------------- diff --git a/components/camel-spring-javaconfig/src/main/java/org/apache/camel/spring/javaconfig/RoutesCollector.java b/components/camel-spring-javaconfig/src/main/java/org/apache/camel/spring/javaconfig/RoutesCollector.java index 02bc123..9e6b351 100644 --- a/components/camel-spring-javaconfig/src/main/java/org/apache/camel/spring/javaconfig/RoutesCollector.java +++ b/components/camel-spring-javaconfig/src/main/java/org/apache/camel/spring/javaconfig/RoutesCollector.java @@ -25,12 +25,13 @@ import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.core.Ordered; /** * Collects routes and rests from the various sources (like Spring application context beans registry or opinionated * classpath locations) and injects these into the Camel context. */ -public class RoutesCollector implements ApplicationListener<ContextRefreshedEvent> { +public class RoutesCollector implements ApplicationListener<ContextRefreshedEvent>, Ordered { // Static collaborators @@ -94,4 +95,11 @@ public class RoutesCollector implements ApplicationListener<ContextRefreshedEven } } + @Override + public int getOrder() { + // we want the RoutesCollector to receive ContextRefreshedEvent + // before SpringCamelContext (see SpringCamelContext::getOrder) + return LOWEST_PRECEDENCE - 1; + } + } http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring-javaconfig/src/test/java/org/apache/camel/spring/javaconfig/MainTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring-javaconfig/src/test/java/org/apache/camel/spring/javaconfig/MainTest.java b/components/camel-spring-javaconfig/src/test/java/org/apache/camel/spring/javaconfig/MainTest.java index 0564b98..7c9b58f 100644 --- a/components/camel-spring-javaconfig/src/test/java/org/apache/camel/spring/javaconfig/MainTest.java +++ b/components/camel-spring-javaconfig/src/test/java/org/apache/camel/spring/javaconfig/MainTest.java @@ -19,7 +19,6 @@ package org.apache.camel.spring.javaconfig; import org.apache.camel.CamelContext; import org.apache.camel.ProducerTemplate; import org.apache.camel.component.mock.MockEndpoint; -import org.apache.camel.spring.SpringCamelContext; import org.junit.Assert; import org.junit.Test; import org.springframework.context.ApplicationContext; @@ -33,7 +32,7 @@ public class MainTest extends Assert { runTests(context); context.stop(); } - + @Test public void testOptionBP() throws Exception { CamelContext context = createCamelContext(new String[]{"-bp", "org.apache.camel.spring.javaconfig.config"}); @@ -41,24 +40,24 @@ public class MainTest extends Assert { runTests(context); context.stop(); } - + private CamelContext createCamelContext(String[] options) throws Exception { - Main main = new Main(); + Main main = new Main(); main.parseArguments(options); ApplicationContext applicationContext = main.createDefaultApplicationContext(); - CamelContext context = SpringCamelContext.springCamelContext(applicationContext); - return context; + CamelContext context = applicationContext.getBean(CamelContext.class); + return context; } private void runTests(CamelContext context) throws Exception { MockEndpoint resultEndpoint = context.getEndpoint("mock:result", MockEndpoint.class); ProducerTemplate template = context.createProducerTemplate(); - + String expectedBody = "<matched/>"; resultEndpoint.expectedBodiesReceived(expectedBody); template.sendBodyAndHeader("direct:start", expectedBody, "foo", "bar"); resultEndpoint.assertIsSatisfied(); - + resultEndpoint.reset(); resultEndpoint.expectedMessageCount(0); template.sendBodyAndHeader("direct:start", "<notMatched/>", "foo", "notMatchedHeaderValue"); http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/pom.xml ---------------------------------------------------------------------- diff --git a/components/camel-spring/pom.xml b/components/camel-spring/pom.xml index 9836390..9ef3c5a 100644 --- a/components/camel-spring/pom.xml +++ b/components/camel-spring/pom.xml @@ -194,6 +194,12 @@ <version>${cglib-version}</version> <scope>test</scope> </dependency> + <dependency> + <groupId>org.assertj</groupId> + <artifactId>assertj-core</artifactId> + <version>${assertj-version}</version> + <scope>test</scope> + </dependency> </dependencies> http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/main/java/org/apache/camel/spring/CamelContextFactoryBean.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/main/java/org/apache/camel/spring/CamelContextFactoryBean.java b/components/camel-spring/src/main/java/org/apache/camel/spring/CamelContextFactoryBean.java index 9914942..f0c115c 100644 --- a/components/camel-spring/src/main/java/org/apache/camel/spring/CamelContextFactoryBean.java +++ b/components/camel-spring/src/main/java/org/apache/camel/spring/CamelContextFactoryBean.java @@ -19,6 +19,7 @@ package org.apache.camel.spring; import java.util.ArrayList; import java.util.List; import java.util.Map; + import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; @@ -78,22 +79,24 @@ import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; +import org.springframework.context.Lifecycle; +import org.springframework.context.Phased; import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.core.Ordered; import static org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException; /** * CamelContext using XML configuration. - * - * @version */ @Metadata(label = "spring,configuration") @XmlRootElement(name = "camelContext") @XmlAccessorType(XmlAccessType.FIELD) public class CamelContextFactoryBean extends AbstractCamelContextFactoryBean<SpringCamelContext> - implements FactoryBean<SpringCamelContext>, InitializingBean, DisposableBean, ApplicationContextAware, ApplicationListener<ApplicationEvent> { + implements FactoryBean<SpringCamelContext>, InitializingBean, DisposableBean, ApplicationContextAware, Lifecycle, + Phased, ApplicationListener<ContextRefreshedEvent>, Ordered { + private static final Logger LOG = LoggerFactory.getLogger(CamelContextFactoryBean.class); @XmlAttribute(name = "depends-on") @@ -229,7 +232,7 @@ public class CamelContextFactoryBean extends AbstractCamelContextFactoryBean<Spr public Class<SpringCamelContext> getObjectType() { return SpringCamelContext.class; } - + protected <S> S getBeanForType(Class<S> clazz) { S bean = null; String[] names = getApplicationContext().getBeanNamesForType(clazz, true, true); @@ -346,43 +349,65 @@ public class CamelContextFactoryBean extends AbstractCamelContextFactoryBean<Spr } } - public void onApplicationEvent(ApplicationEvent event) { - // From Spring 3.0.1, The BeanFactory applicationEventListener - // and Bean's applicationEventListener will be called, - // So we just delegate the onApplicationEvent call here. + @Override + public void start() { + try { + setupRoutes(); + } catch (Exception e) { + throw wrapRuntimeCamelException(e); + } + + // when the routes are setup we need to start the Camel context + context.start(); + } - SpringCamelContext context = getContext(false); + @Override + public void stop() { if (context != null) { - // we need to defer setting up routes until Spring has done all its dependency injection - // which is only guaranteed to be done when it emits the ContextRefreshedEvent event. - if (event instanceof ContextRefreshedEvent) { - try { - setupRoutes(); - } catch (Exception e) { - throw wrapRuntimeCamelException(e); - } - } - // let the spring camel context handle the events - context.onApplicationEvent(event); - } else { - LOG.debug("Publishing spring-event: {}", event); - - if (event instanceof ContextRefreshedEvent) { - // now lets start the CamelContext so that all its possible - // dependencies are initialized - try { - // we need to defer setting up routes until Spring has done all its dependency injection - // which is only guaranteed to be done when it emits the ContextRefreshedEvent event. - setupRoutes(); - LOG.trace("Starting the context now"); - getContext().start(); - } catch (Exception e) { - throw wrapRuntimeCamelException(e); - } - } + context.stop(); } } + @Override + public boolean isRunning() { + return context != null && context.isRunning(); + } + + @Override + public int getPhase() { + // the factory starts the context from + // onApplicationEvent(ContextRefreshedEvent) so the phase we're + // in only influences when the context is to be stopped, and + // we want the CamelContext to be first in line to get stopped + // if we wanted the phase to be considered while starting, we + // would need to implement SmartLifecycle (see + // DefaultLifecycleProcessor::startBeans) + // we use LOWEST_PRECEDENCE here as this is taken into account + // only when stopping and then in reversed order + return LOWEST_PRECEDENCE - 1; + } + + @Override + public int getOrder() { + // CamelContextFactoryBean implements Ordered so that it's the + // second to last in ApplicationListener to receive events, + // SpringCamelContext should be the last one, this is important + // for startup as we want all resources to be ready and all + // routes added to the context (see setupRoutes() and + // org.apache.camel.spring.boot.RoutesCollector) + return LOWEST_PRECEDENCE - 1; + } + + @Override + public void onApplicationEvent(final ContextRefreshedEvent event) { + // start the CamelContext when the Spring ApplicationContext is + // done initializing, as the last step in ApplicationContext + // being started/refreshed, there could be a race condition with + // other ApplicationListeners that react to + // ContextRefreshedEvent but this is the best that we can do + start(); + } + // Properties // ------------------------------------------------------------------------- @@ -393,6 +418,7 @@ public class CamelContextFactoryBean extends AbstractCamelContextFactoryBean<Spr return applicationContext; } + @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @@ -412,8 +438,9 @@ public class CamelContextFactoryBean extends AbstractCamelContextFactoryBean<Spr * Create the context */ protected SpringCamelContext createContext() { - SpringCamelContext ctx = newCamelContext(); - ctx.setName(getId()); + SpringCamelContext ctx = newCamelContext(); + ctx.setName(getId()); + return ctx; } http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/main/java/org/apache/camel/spring/SpringCamelContext.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/main/java/org/apache/camel/spring/SpringCamelContext.java b/components/camel-spring/src/main/java/org/apache/camel/spring/SpringCamelContext.java index 540436d..d81ca3d 100644 --- a/components/camel-spring/src/main/java/org/apache/camel/spring/SpringCamelContext.java +++ b/components/camel-spring/src/main/java/org/apache/camel/spring/SpringCamelContext.java @@ -33,16 +33,16 @@ import org.apache.camel.util.StopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; -import org.springframework.beans.factory.DisposableBean; -import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationEvent; +import org.springframework.context.ApplicationListener; import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.context.event.ContextClosedEvent; +import org.springframework.context.Lifecycle; +import org.springframework.context.Phased; import org.springframework.context.event.ContextRefreshedEvent; -import org.springframework.context.event.ContextStoppedEvent; import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.core.Ordered; import static org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException; @@ -56,8 +56,8 @@ import static org.apache.camel.util.ObjectHelper.wrapRuntimeCamelException; * * @version */ -public class SpringCamelContext extends DefaultCamelContext implements InitializingBean, DisposableBean, - ApplicationContextAware { +public class SpringCamelContext extends DefaultCamelContext implements Lifecycle, ApplicationContextAware, Phased, + ApplicationListener<ApplicationEvent>, Ordered { private static final Logger LOG = LoggerFactory.getLogger(SpringCamelContext.class); private static final ThreadLocal<Boolean> NO_START = new ThreadLocal<Boolean>(); @@ -105,7 +105,7 @@ public class SpringCamelContext extends DefaultCamelContext implements Initializ SpringCamelContext answer = new SpringCamelContext(); answer.setApplicationContext(applicationContext); if (maybeStart) { - answer.afterPropertiesSet(); + answer.start(); } return answer; } @@ -119,45 +119,59 @@ public class SpringCamelContext extends DefaultCamelContext implements Initializ return springCamelContext(new ClassPathXmlApplicationContext(configLocations)); } - public void afterPropertiesSet() throws Exception { - StopWatch watch = new StopWatch(); - - maybeStart(); - - LOG.debug("afterPropertiesSet() took {} millis", watch.stop()); - } - - public void destroy() throws Exception { - stop(); - } - - public void onApplicationEvent(ApplicationEvent event) { - LOG.debug("onApplicationEvent: {}", event); + @Override + public void start() { + // for example from unit testing we want to start Camel later (manually) + if (Boolean.TRUE.equals(NO_START.get())) { + LOG.trace("Ignoring start() as NO_START is false"); + return; + } - if (event instanceof ContextRefreshedEvent) { - // now lets start the CamelContext so that all its possible - // dependencies are initialized + if (!isStarted() && !isStarting()) { try { - maybeStart(); + StopWatch watch = new StopWatch(); + super.start(); + LOG.debug("start() took {} millis", watch.stop()); } catch (Exception e) { throw wrapRuntimeCamelException(e); } - } else if (event instanceof ContextClosedEvent) { - // ContextClosedEvent is emitted when Spring is about to be shutdown - if (isShutdownEager()) { - try { - maybeStop(); - } catch (Exception e) { - throw wrapRuntimeCamelException(e); - } - } - } else if (event instanceof ContextStoppedEvent) { - // ContextStoppedEvent is emitted when Spring is end of shutdown + } else { + // ignore as Camel is already started + LOG.trace("Ignoring start() as Camel is already started"); + } + } + + @Override + public void stop() { + if (!isStopping() && !isStopped()) { try { - maybeStop(); + super.stop(); } catch (Exception e) { throw wrapRuntimeCamelException(e); } + } else { + // ignore as Camel is already stopped + LOG.trace("Ignoring stop() as Camel is already stopped"); + } + } + + @Override + public void onApplicationEvent(ApplicationEvent event) { + LOG.debug("onApplicationEvent: {}", event); + + if (event instanceof ContextRefreshedEvent) { + // nominally we would prefer to use Lifecycle interface that + // would invoke start() method, but in order to do that + // SpringCamelContext needs to implement SmartLifecycle + // (look at DefaultLifecycleProcessor::startBeans), but it + // cannot implement it as it already implements + // RuntimeConfiguration, and both SmartLifecycle and + // RuntimeConfiguration declare isAutoStartup method but + // with boolean and Boolean return types, and covariant + // methods with primitive types are not allowed by the JLS + // so we need to listen for ContextRefreshedEvent and start + // on its reception + start(); } if (eventComponent != null) { @@ -165,6 +179,17 @@ public class SpringCamelContext extends DefaultCamelContext implements Initializ } } + @Override + public int getOrder() { + // SpringCamelContext implements Ordered so that it's the last + // in ApplicationListener to receive events, this is important + // for startup as we want all resources to be ready and all + // routes added to the context (see + // org.apache.camel.spring.boot.RoutesCollector) + // and we need to be after CamelContextFactoryBean + return LOWEST_PRECEDENCE; + } + // Properties // ----------------------------------------------------------------------- @@ -172,6 +197,7 @@ public class SpringCamelContext extends DefaultCamelContext implements Initializ return applicationContext; } + @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; ClassLoader cl; @@ -250,6 +276,7 @@ public class SpringCamelContext extends DefaultCamelContext implements Initializ return getEndpoint("spring-event:default", EventEndpoint.class); } + @Override protected Endpoint convertBeanToEndpoint(String uri, Object bean) { // We will use the type convert to build the endpoint first Endpoint endpoint = getTypeConverter().convertTo(Endpoint.class, bean); @@ -271,31 +298,6 @@ public class SpringCamelContext extends DefaultCamelContext implements Initializ return new SpringModelJAXBContextFactory(); } - private void maybeStart() throws Exception { - // for example from unit testing we want to start Camel later and not when Spring framework - // publish a ContextRefreshedEvent - - if (NO_START.get() == null) { - if (!isStarted() && !isStarting()) { - start(); - } else { - // ignore as Camel is already started - LOG.trace("Ignoring maybeStart() as Apache Camel is already started"); - } - } else { - LOG.trace("Ignoring maybeStart() as NO_START is false"); - } - } - - private void maybeStop() throws Exception { - if (!isStopping() && !isStopped()) { - stop(); - } else { - // ignore as Camel is already stopped - LOG.trace("Ignoring maybeStop() as Apache Camel is already stopped"); - } - } - @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -306,4 +308,24 @@ public class SpringCamelContext extends DefaultCamelContext implements Initializ return sb.toString(); } + @Override + public int getPhase() { + // the context is started by invoking start method which + // happens either on ContextRefreshedEvent or explicitly + // invoking the method, for instance CamelContextFactoryBean + // is using that to start the context, _so_ here we want to + // have maximum priority as the getPhase() will be used only + // for stopping, in order to be used for starting we would + // need to implement SmartLifecycle which we cannot + // (explained in comment in the onApplicationEvent method) + // we use LOWEST_PRECEDENCE here as this is taken into account + // only when stopping and then in reversed order + return LOWEST_PRECEDENCE; + } + + @Override + public boolean isRunning() { + return !isStopping() && !isStopped(); + } + } http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/test/java/org/apache/camel/component/rest/SpringFromRestDuplicateTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/test/java/org/apache/camel/component/rest/SpringFromRestDuplicateTest.java b/components/camel-spring/src/test/java/org/apache/camel/component/rest/SpringFromRestDuplicateTest.java index 0017ede..d1cda9a 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/component/rest/SpringFromRestDuplicateTest.java +++ b/components/camel-spring/src/test/java/org/apache/camel/component/rest/SpringFromRestDuplicateTest.java @@ -16,13 +16,11 @@ */ package org.apache.camel.component.rest; +import org.apache.camel.RuntimeCamelException; import org.apache.camel.spring.SpringTestSupport; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -/** - * @version - */ public class SpringFromRestDuplicateTest extends SpringTestSupport { @Override @@ -31,7 +29,7 @@ public class SpringFromRestDuplicateTest extends SpringTestSupport { try { new ClassPathXmlApplicationContext("org/apache/camel/component/rest/SpringFromRestDuplicateTest.xml"); fail("Should throw exception"); - } catch (Exception e) { + } catch (RuntimeCamelException e) { IllegalArgumentException iae = assertIsInstanceOf(IllegalArgumentException.class, e.getCause()); assertEquals("Duplicate verb detected in rest-dsl: get:{id}", iae.getMessage()); } http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/test/java/org/apache/camel/spring/CircularComponentCreationTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/CircularComponentCreationTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/CircularComponentCreationTest.java index 0a74bfe..bc99073 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/spring/CircularComponentCreationTest.java +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/CircularComponentCreationTest.java @@ -33,8 +33,7 @@ public class CircularComponentCreationTest { doTest("org/apache/camel/spring/CircularComponentCreationSimpleTest.xml"); Assert.fail("Exception should have been thrown"); - } catch (Exception e) { - Assert.assertTrue(e instanceof RuntimeCamelException); + } catch (RuntimeCamelException e) { Assert.assertTrue(e.getCause() instanceof FailedToCreateRouteException); } } http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/test/java/org/apache/camel/spring/StartupShutdownOrderBaseTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/StartupShutdownOrderBaseTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/StartupShutdownOrderBaseTest.java new file mode 100644 index 0000000..2910f33 --- /dev/null +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/StartupShutdownOrderBaseTest.java @@ -0,0 +1,239 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.spring; + +import java.util.Map; + +import org.apache.camel.CamelContext; +import org.apache.camel.support.ServiceSupport; +import org.junit.Test; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.Lifecycle; +import org.springframework.context.SmartLifecycle; +import org.springframework.context.annotation.Bean; + +import static org.assertj.core.api.Assertions.assertThat; + +public abstract class StartupShutdownOrderBaseTest { + + static class AutoCloseableBean implements AutoCloseable, TestState { + + boolean closed; + + private final ApplicationContext context; + + public AutoCloseableBean(final ApplicationContext context) { + this.context = context; + } + + @Override + public void assertValid() { + assertThat(closed).as("AutoCloseable bean should be closed").isTrue(); + } + + @Override + public void close() { + assertThat(camelIsStopped(context)).as("AutoCloseable bean should be stopped after Camel").isTrue(); + closed = true; + } + } + + static class Beans { + + @Bean + AutoCloseableBean autoCloseableBean(final ApplicationContext context) { + return new AutoCloseableBean(context); + } + + @Bean + BeanWithShutdownMethod beanWithCloseMethod(final ApplicationContext context) { + return new BeanWithShutdownMethod(context); + } + + @Bean + DisposeBean disposedBean(final ApplicationContext context) { + return new DisposeBean(context); + } + + @Bean + InitBean initBean(final ApplicationContext context) { + return new InitBean(context); + } + + @Bean + Lifecycle lifecycleBean(final ApplicationContext context) { + return new LifecycleBean(context); + } + } + + static class BeanWithShutdownMethod implements TestState { + + boolean shutdown; + + private final ApplicationContext context; + + public BeanWithShutdownMethod(final ApplicationContext context) { + this.context = context; + } + + @Override + public void assertValid() { + assertThat(shutdown).as("Bean with shutdown method should be shutdown").isTrue(); + } + + public void shutdown() { + assertThat(camelIsStopped(context)).as("@Bean with close() method should be stopped after Camel").isTrue(); + shutdown = true; + } + } + + static class DisposeBean implements DisposableBean, TestState { + + boolean disposed; + + private final ApplicationContext context; + + public DisposeBean(final ApplicationContext context) { + this.context = context; + } + + @Override + public void assertValid() { + assertThat(disposed).as("DisposableBean should be disposed").isTrue(); + } + + @Override + public void destroy() throws Exception { + assertThat(camelIsStopped(context)).as("DisposableBean should be stopped after Camel").isTrue(); + disposed = true; + } + } + + static class InitBean implements InitializingBean, TestState { + + ApplicationContext context; + + boolean initialized; + + @Autowired + public InitBean(final ApplicationContext context) { + this.context = context; + } + + @Override + public void afterPropertiesSet() throws Exception { + assertThat(camelIsStopped(context)).as("initializing bean should be started before Camel").isTrue(); + initialized = true; + } + + @Override + public void assertValid() { + assertThat(initialized).as("InitializingBean should be initialized").isTrue(); + } + } + + static class LifecycleBean implements SmartLifecycle, TestState { + + ApplicationContext context; + + boolean started; + + boolean stopped; + + @Autowired + public LifecycleBean(final ApplicationContext context) { + this.context = context; + } + + @Override + public void assertValid() { + assertThat(started).as("Lifecycle should have been started").isTrue(); + assertThat(stopped).as("Lifecycle should be stopped").isTrue(); + } + + @Override + public int getPhase() { + return 0; + } + + @Override + public boolean isAutoStartup() { + return true; + } + + @Override + public boolean isRunning() { + return started; + } + + @Override + public void start() { + assertThat(camelIsStopped(context)).as("lifecycle bean should be started before Camel").isTrue(); + started = true; + } + + @Override + public void stop() { + assertThat(camelIsStopped(context)).as("lifecycle bean should be stopped after Camel").isTrue(); + stopped = true; + } + + @Override + public void stop(final Runnable callback) { + stop(); + callback.run(); + } + } + + interface TestState { + void assertValid(); + } + + @Test + public void camelContextShouldBeStartedLastAndStoppedFirst() { + final ConfigurableApplicationContext context = createContext(); + + final ServiceSupport camelContext = (ServiceSupport) context.getBean(CamelContext.class); + final Map<String, TestState> testStates = context.getBeansOfType(TestState.class); + + assertThat(camelContext.isStarted()).as("Camel context should be started").isTrue(); + + context.close(); + + assertThat(camelContext.isStopped()).as("Camel context should be stopped").isTrue(); + testStates.values().stream().forEach(TestState::assertValid); + } + + abstract ConfigurableApplicationContext createContext(); + + static ServiceSupport camel(final ApplicationContext context) { + return (ServiceSupport) context.getBean(CamelContext.class); + } + + static boolean camelIsStarted(final ApplicationContext context) { + return camel(context).isStarted(); + } + + static boolean camelIsStopped(final ApplicationContext context) { + return !camelIsStarted(context); + } + +} http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/test/java/org/apache/camel/spring/StartupShutdownSpringCamelContextFactoryBeanOrderTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/StartupShutdownSpringCamelContextFactoryBeanOrderTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/StartupShutdownSpringCamelContextFactoryBeanOrderTest.java new file mode 100644 index 0000000..7e3a3c9 --- /dev/null +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/StartupShutdownSpringCamelContextFactoryBeanOrderTest.java @@ -0,0 +1,43 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.spring; + +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +public class StartupShutdownSpringCamelContextFactoryBeanOrderTest extends StartupShutdownOrderBaseTest { + @Configuration + static class CamelContextConfiguration { + @Bean + CamelContextFactoryBean camelContext() { + final CamelContextFactoryBean factory = new CamelContextFactoryBean(); + factory.setId("camelContext"); + + return factory; + } + } + + @Override + ConfigurableApplicationContext createContext() { + final ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( + CamelContextConfiguration.class, Beans.class); + return context; + } + +} http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/test/java/org/apache/camel/spring/StartupShutdownSpringCamelContextOrderTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/StartupShutdownSpringCamelContextOrderTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/StartupShutdownSpringCamelContextOrderTest.java new file mode 100644 index 0000000..2200862 --- /dev/null +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/StartupShutdownSpringCamelContextOrderTest.java @@ -0,0 +1,41 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.camel.spring; + +import org.apache.camel.CamelContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +public class StartupShutdownSpringCamelContextOrderTest extends StartupShutdownOrderBaseTest { + @Configuration + static class CamelContextConfiguration { + @Bean + CamelContext camelContext() { + return new SpringCamelContext(); + } + } + + @Override + ConfigurableApplicationContext createContext() { + final ConfigurableApplicationContext context = new AnnotationConfigApplicationContext( + CamelContextConfiguration.class, Beans.class); + return context; + } + +} http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/test/java/org/apache/camel/spring/config/SpringRouteNoFromTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/config/SpringRouteNoFromTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/config/SpringRouteNoFromTest.java index b4fc035..0e542c8 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/spring/config/SpringRouteNoFromTest.java +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/config/SpringRouteNoFromTest.java @@ -16,13 +16,11 @@ */ package org.apache.camel.spring.config; +import org.apache.camel.RuntimeCamelException; import org.apache.camel.spring.SpringTestSupport; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -/** - * - */ public class SpringRouteNoFromTest extends SpringTestSupport { @Override @@ -40,7 +38,7 @@ public class SpringRouteNoFromTest extends SpringTestSupport { try { answer = new ClassPathXmlApplicationContext("org/apache/camel/spring/config/SpringRouteNoFromTest.xml"); fail("Should have thrown exception"); - } catch (Exception e) { + } catch (RuntimeCamelException e) { IllegalArgumentException iae = (IllegalArgumentException) e.getCause(); assertEquals("Route myRoute has no inputs: Route(myRoute)[[] -> [To[mock:result]]]", iae.getMessage()); return null; http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/test/java/org/apache/camel/spring/config/SpringRouteNoOutputTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/config/SpringRouteNoOutputTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/config/SpringRouteNoOutputTest.java index 4ff49a0..a0d0b16 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/spring/config/SpringRouteNoOutputTest.java +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/config/SpringRouteNoOutputTest.java @@ -16,13 +16,11 @@ */ package org.apache.camel.spring.config; +import org.apache.camel.RuntimeCamelException; import org.apache.camel.spring.SpringTestSupport; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -/** - * - */ public class SpringRouteNoOutputTest extends SpringTestSupport { @Override @@ -40,8 +38,8 @@ public class SpringRouteNoOutputTest extends SpringTestSupport { try { answer = new ClassPathXmlApplicationContext("org/apache/camel/spring/config/SpringRouteNoOutputTest.xml"); fail("Should have thrown exception"); - } catch (Exception e) { - IllegalArgumentException iae = (IllegalArgumentException) e.getCause(); + } catch (RuntimeCamelException e) { + IllegalArgumentException iae = assertIsInstanceOf(IllegalArgumentException.class, e.getCause()); assertEquals("Route myRoute has no outputs: Route(myRoute)[[From[direct:start]] -> []]", iae.getMessage()); return null; } http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/test/java/org/apache/camel/spring/file/SpringFileConsumerPreMoveTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/file/SpringFileConsumerPreMoveTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/file/SpringFileConsumerPreMoveTest.java index cf7d975..6958457 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/spring/file/SpringFileConsumerPreMoveTest.java +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/file/SpringFileConsumerPreMoveTest.java @@ -18,22 +18,19 @@ package org.apache.camel.spring.file; import org.apache.camel.CamelContext; import org.apache.camel.component.file.FileConsumerPreMoveTest; -import org.apache.camel.spring.SpringCamelContext; - import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -/** - * @version - */ public class SpringFileConsumerPreMoveTest extends FileConsumerPreMoveTest { private AbstractXmlApplicationContext applicationContext; + @Override protected CamelContext createCamelContext() throws Exception { - applicationContext = new ClassPathXmlApplicationContext("org/apache/camel/spring/file/SpringFileConsumerPreMoveTest.xml"); - return SpringCamelContext.springCamelContext(applicationContext); + applicationContext = new ClassPathXmlApplicationContext( + "org/apache/camel/spring/file/SpringFileConsumerPreMoveTest.xml"); + return applicationContext.getBean(CamelContext.class); } - + @Override protected void tearDown() throws Exception { if (applicationContext != null) { @@ -41,6 +38,5 @@ public class SpringFileConsumerPreMoveTest extends FileConsumerPreMoveTest { } super.tearDown(); } - } http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/test/java/org/apache/camel/spring/issues/MisspelledRouteRefTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/issues/MisspelledRouteRefTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/issues/MisspelledRouteRefTest.java index fa4999f..f507078 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/spring/issues/MisspelledRouteRefTest.java +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/issues/MisspelledRouteRefTest.java @@ -17,30 +17,24 @@ package org.apache.camel.spring.issues; import junit.framework.TestCase; + import org.apache.camel.CamelException; +import org.apache.camel.RuntimeCamelException; import org.apache.camel.spring.Main; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -/** - * @version - */ -public class MisspelledRouteRefTest extends TestCase { +import static org.apache.camel.TestSupport.assertIsInstanceOf; - private static final Logger LOG = LoggerFactory.getLogger(MisspelledRouteRefTest.class); +public class MisspelledRouteRefTest extends TestCase { - public void testApplicationContextFailed() { + public void testApplicationContextFailed() throws Exception { try { - Main main = new Main(); + Main main = new Main(); main.setApplicationContextUri("org/apache/camel/spring/issues/MisspelledRouteRefTest.xml"); main.start(); fail("Should have thrown an exception"); - } catch (Exception e) { - //expected but want to see what it looks like... - LOG.debug("Exception message : " + e.getMessage()); - - CamelException cause = (CamelException) e.getCause(); - assertEquals("Cannot find any routes with this RouteBuilder reference: RouteBuilderRef[xxxroute]", cause.getMessage()); + } catch (RuntimeCamelException e) { + CamelException ce = assertIsInstanceOf(CamelException.class, e.getCause()); + assertEquals("Cannot find any routes with this RouteBuilder reference: RouteBuilderRef[xxxroute]", ce.getMessage()); } } } http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/test/java/org/apache/camel/spring/issues/SpringMainStartFailedIssueTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/issues/SpringMainStartFailedIssueTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/issues/SpringMainStartFailedIssueTest.java index 3f2fa16..beb8e7b 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/spring/issues/SpringMainStartFailedIssueTest.java +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/issues/SpringMainStartFailedIssueTest.java @@ -17,12 +17,10 @@ package org.apache.camel.spring.issues; import org.apache.camel.FailedToCreateRouteException; +import org.apache.camel.RuntimeCamelException; import org.apache.camel.TestSupport; import org.apache.camel.spring.Main; -/** - * @version - */ public class SpringMainStartFailedIssueTest extends TestSupport { public void testStartupFailed() throws Exception { @@ -32,7 +30,7 @@ public class SpringMainStartFailedIssueTest extends TestSupport { try { main.run(args); fail("Should have thrown an exception"); - } catch (Exception e) { + } catch (RuntimeCamelException e) { assertIsInstanceOf(FailedToCreateRouteException.class, e.getCause()); } http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/test/java/org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.java index 1239f76..278db1c 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.java +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.java @@ -16,14 +16,13 @@ */ package org.apache.camel.spring.management; +import org.apache.camel.FailedToCreateRouteException; import org.apache.camel.ResolveEndpointFailedException; +import org.apache.camel.RuntimeCamelException; import org.apache.camel.spring.SpringTestSupport; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -/** - * @version - */ public class SpringCamelContextStartingFailedEventTest extends SpringTestSupport { @Override @@ -35,8 +34,9 @@ public class SpringCamelContextStartingFailedEventTest extends SpringTestSupport try { new ClassPathXmlApplicationContext("org/apache/camel/spring/management/SpringCamelContextStartingFailedEventTest.xml"); fail("Should thrown an exception"); - } catch (Exception e) { - assertIsInstanceOf(ResolveEndpointFailedException.class, e.getCause().getCause()); + } catch (RuntimeCamelException e) { + FailedToCreateRouteException ftcre = assertIsInstanceOf(FailedToCreateRouteException.class, e.getCause()); + assertIsInstanceOf(ResolveEndpointFailedException.class, ftcre.getCause()); // expected } http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringDeadLetterChannelInvalidDeadLetterUriTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringDeadLetterChannelInvalidDeadLetterUriTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringDeadLetterChannelInvalidDeadLetterUriTest.java index f44559f..9404fb8 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringDeadLetterChannelInvalidDeadLetterUriTest.java +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringDeadLetterChannelInvalidDeadLetterUriTest.java @@ -16,17 +16,17 @@ */ package org.apache.camel.spring.processor; +import org.apache.camel.FailedToCreateRouteException; import org.apache.camel.NoSuchEndpointException; +import org.apache.camel.RuntimeCamelException; import org.apache.camel.spring.SpringTestSupport; import org.junit.Test; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -/** - * @version - */ public class SpringDeadLetterChannelInvalidDeadLetterUriTest extends SpringTestSupport { + @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/spring/processor/SpringDeadLetterChannelInvalidDeadLetterUriTest.xml"); } @@ -36,8 +36,9 @@ public class SpringDeadLetterChannelInvalidDeadLetterUriTest extends SpringTestS try { super.setUp(); fail("Should have thrown an exception"); - } catch (Exception e) { - NoSuchEndpointException cause = assertIsInstanceOf(NoSuchEndpointException.class, e.getCause().getCause()); + } catch (RuntimeCamelException e) { + FailedToCreateRouteException ftcre = assertIsInstanceOf(FailedToCreateRouteException.class, e.getCause()); + NoSuchEndpointException cause = assertIsInstanceOf(NoSuchEndpointException.class, ftcre.getCause()); assertEquals("No endpoint could be found for: xxx, please check your classpath contains the needed Camel component jar.", cause.getMessage()); } } http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringDeadLetterChannelInvalidOptionDeadLetterUriTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringDeadLetterChannelInvalidOptionDeadLetterUriTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringDeadLetterChannelInvalidOptionDeadLetterUriTest.java index 1b9aa40..390184a 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringDeadLetterChannelInvalidOptionDeadLetterUriTest.java +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringDeadLetterChannelInvalidOptionDeadLetterUriTest.java @@ -16,17 +16,17 @@ */ package org.apache.camel.spring.processor; +import org.apache.camel.FailedToCreateRouteException; import org.apache.camel.ResolveEndpointFailedException; +import org.apache.camel.RuntimeCamelException; import org.apache.camel.spring.SpringTestSupport; import org.junit.Test; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -/** - * @version - */ public class SpringDeadLetterChannelInvalidOptionDeadLetterUriTest extends SpringTestSupport { + @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/spring/processor/SpringDeadLetterChannelInvalidOptionDeadLetterUriTest.xml"); } @@ -36,8 +36,9 @@ public class SpringDeadLetterChannelInvalidOptionDeadLetterUriTest extends Sprin try { super.setUp(); fail("Should have thrown an exception"); - } catch (Exception e) { - ResolveEndpointFailedException cause = assertIsInstanceOf(ResolveEndpointFailedException.class, e.getCause().getCause()); + } catch (RuntimeCamelException e) { + FailedToCreateRouteException ftcre = assertIsInstanceOf(FailedToCreateRouteException.class, e.getCause()); + ResolveEndpointFailedException cause = assertIsInstanceOf(ResolveEndpointFailedException.class, ftcre.getCause()); assertTrue(cause.getMessage().endsWith("Unknown parameters=[{foo=bar}]")); } } http://git-wip-us.apache.org/repos/asf/camel/blob/fbf0ffad/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringDoubleLoadBalancerMisconfigurationTest.java ---------------------------------------------------------------------- diff --git a/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringDoubleLoadBalancerMisconfigurationTest.java b/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringDoubleLoadBalancerMisconfigurationTest.java index dcd4e99..9345460 100644 --- a/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringDoubleLoadBalancerMisconfigurationTest.java +++ b/components/camel-spring/src/test/java/org/apache/camel/spring/processor/SpringDoubleLoadBalancerMisconfigurationTest.java @@ -19,12 +19,10 @@ package org.apache.camel.spring.processor; import org.apache.camel.CamelContext; import org.apache.camel.ContextTestSupport; import org.apache.camel.FailedToCreateRouteException; +import org.apache.camel.RuntimeCamelException; import static org.apache.camel.spring.processor.SpringTestHelper.createSpringCamelContext; -/** - * @version - */ public class SpringDoubleLoadBalancerMisconfigurationTest extends ContextTestSupport { @Override @@ -32,7 +30,7 @@ public class SpringDoubleLoadBalancerMisconfigurationTest extends ContextTestSup try { super.setUp(); fail("Should have thrown exception"); - } catch (Exception e) { + } catch (RuntimeCamelException e) { FailedToCreateRouteException fe = assertIsInstanceOf(FailedToCreateRouteException.class, e.getCause()); IllegalArgumentException ie = assertIsInstanceOf(IllegalArgumentException.class, fe.getCause()); assertTrue(ie.getMessage().startsWith("Loadbalancer already configured to: RandomLoadBalancer. Cannot set it to: LoadBalanceType[RoundRobinLoadBalancer")); @@ -43,6 +41,7 @@ public class SpringDoubleLoadBalancerMisconfigurationTest extends ContextTestSup // noop } + @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/DoubleLoadBalancerMisconfigurationTest.xml"); }
