001    /**
002     * Licensed to the Apache Software Foundation (ASF) under one or more
003     * contributor license agreements.  See the NOTICE file distributed with
004     * this work for additional information regarding copyright ownership.
005     * The ASF licenses this file to You under the Apache License, Version 2.0
006     * (the "License"); you may not use this file except in compliance with
007     * the License.  You may obtain a copy of the License at
008     *
009     *      http://www.apache.org/licenses/LICENSE-2.0
010     *
011     * Unless required by applicable law or agreed to in writing, software
012     * distributed under the License is distributed on an "AS IS" BASIS,
013     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014     * See the License for the specific language governing permissions and
015     * limitations under the License.
016     */
017    package org.apache.camel.testng;
018    
019    import java.util.Arrays;
020    import java.util.Collections;
021    import java.util.HashSet;
022    import java.util.List;
023    import java.util.Set;
024    
025    import org.apache.camel.CamelContext;
026    import org.apache.camel.Route;
027    import org.apache.camel.impl.DefaultPackageScanClassResolver;
028    import org.apache.camel.impl.scan.AssignableToPackageScanFilter;
029    import org.apache.camel.impl.scan.InvertingPackageScanFilter;
030    import org.apache.camel.spring.SpringCamelContext;
031    import org.apache.camel.util.CastUtils;
032    import org.apache.camel.util.ObjectHelper;
033    import org.springframework.beans.factory.support.RootBeanDefinition;
034    import org.springframework.context.ApplicationContext;
035    import org.springframework.context.support.AbstractApplicationContext;
036    import org.springframework.context.support.GenericApplicationContext;
037    import org.testng.annotations.AfterClass;
038    import org.testng.annotations.AfterTest;
039    
040    
041    /**
042     * @version $Revision: 1172870 $
043     */
044    public abstract class CamelSpringTestSupport extends CamelTestSupport {
045        protected static ThreadLocal<AbstractApplicationContext> threadAppContext
046            = new ThreadLocal<AbstractApplicationContext>();
047        protected static Object lock = new Object();
048        protected static AbstractApplicationContext applicationContext;
049        protected abstract AbstractApplicationContext createApplicationContext();
050    
051        public void postProcessTest() throws Exception {
052            super.postProcessTest();
053            if (isCreateCamelContextPerClass()) {
054                applicationContext = threadAppContext.get();
055            }
056        }
057    
058        @Override
059        public void doPreSetup() throws Exception {
060            if (!"true".equalsIgnoreCase(System.getProperty("skipStartingCamelContext"))) {
061                // tell camel-spring it should not trigger starting CamelContext, since we do that later
062                // after we are finished setting up the unit test
063                synchronized (lock) {
064                    SpringCamelContext.setNoStart(true);
065                    if (isCreateCamelContextPerClass()) {
066                        applicationContext = threadAppContext.get();
067                        if (applicationContext == null) {
068                            applicationContext = createApplicationContext();
069                            threadAppContext.set(applicationContext);
070                        }
071                    } else {
072                        applicationContext = createApplicationContext();
073                    }
074                    assertNotNull(applicationContext, "Should have created a valid spring context");
075                    SpringCamelContext.setNoStart(false);
076                }
077            } else {
078                log.info("Skipping starting CamelContext as system property skipStartingCamelContext is set to be true.");
079            }
080        }
081    
082    
083        @Override
084        @AfterTest
085        public void tearDown() throws Exception {
086            super.tearDown();
087    
088            if (!isCreateCamelContextPerClass()) {
089                if (applicationContext != null) {
090                    applicationContext.destroy();
091                    applicationContext = null;
092                }
093            }
094        }
095    
096        @AfterClass
097        public static void tearSpringDownAfterClass() throws Exception {
098            if (threadAppContext.get() != null) {
099                threadAppContext.get().destroy();
100                threadAppContext.remove();
101            }
102        }
103    
104        @SuppressWarnings("unchecked")
105        private static class ExcludingPackageScanClassResolver extends DefaultPackageScanClassResolver {
106    
107            public void setExcludedClasses(Set<Class<?>> excludedClasses) {
108                excludedClasses = excludedClasses == null ? Collections.EMPTY_SET : excludedClasses;
109                addFilter(new InvertingPackageScanFilter(new AssignableToPackageScanFilter(excludedClasses)));
110            }
111    
112        }
113    
114        /**
115         * Create a parent context that initializes a
116         * {@link org.apache.camel.spi.PackageScanClassResolver} to exclude a set of given classes from
117         * being resolved. Typically this is used at test time to exclude certain routes,
118         * which might otherwise be just noisy, from being discovered and initialized.
119         * <p/>
120         * To use this filtering mechanism it is necessary to provide the
121         * {@link ApplicationContext} returned from here as the parent context to
122         * your test context e.g.
123         *
124         * <pre>
125         * protected AbstractXmlApplicationContext createApplicationContext() {
126         *     return new ClassPathXmlApplicationContext(new String[] {&quot;test-context.xml&quot;}, getRouteExcludingApplicationContext());
127         * }
128         * </pre>
129         *
130         * This will, in turn, call the template methods <code>excludedRoutes</code>
131         * and <code>excludedRoute</code> to determine the classes to be excluded from scanning.
132         *
133         * @return ApplicationContext a parent {@link ApplicationContext} configured
134         *         to exclude certain classes from package scanning
135         */
136        protected ApplicationContext getRouteExcludingApplicationContext() {
137            GenericApplicationContext routeExcludingContext = new GenericApplicationContext();
138            routeExcludingContext.registerBeanDefinition("excludingResolver", new RootBeanDefinition(ExcludingPackageScanClassResolver.class));
139            routeExcludingContext.refresh();
140    
141            ExcludingPackageScanClassResolver excludingResolver = (ExcludingPackageScanClassResolver)routeExcludingContext.getBean("excludingResolver");
142            List<Class<?>> excluded = CastUtils.cast(Arrays.asList(excludeRoutes()));
143            excludingResolver.setExcludedClasses(new HashSet<Class<?>>(excluded));
144    
145            return routeExcludingContext;
146        }
147    
148        /**
149         * Template method used to exclude {@link org.apache.camel.Route} from the test time context
150         * route scanning
151         *
152         * @return Class[] the classes to be excluded from test time context route scanning
153         */
154        protected Class<?>[] excludeRoutes() {
155            Class<?> excludedRoute = excludeRoute();
156            return excludedRoute != null ? new Class[] {excludedRoute} : new Class[0];
157        }
158    
159        /**
160         * Template method used to exclude a {@link org.apache.camel.Route} from the test camel context
161         */
162        protected Class<?> excludeRoute() {
163            return null;
164        }
165    
166        /**
167         * Looks up the mandatory spring bean of the given name and type, failing if
168         * it is not present or the correct type
169         */
170        public <T> T getMandatoryBean(Class<T> type, String name) {
171            Object value = applicationContext.getBean(name);
172            assertNotNull(value, "No spring bean found for name <" + name + ">");
173            if (type.isInstance(value)) {
174                return type.cast(value);
175            } else {
176                fail("Spring bean <" + name + "> is not an instanceof " + type.getName() + " but is of type " + ObjectHelper.className(value));
177                return null;
178            }
179        }
180    
181        @Override
182        protected void assertValidContext(CamelContext context) {
183            super.assertValidContext(context);
184    
185            List<Route> routes = context.getRoutes();
186            int routeCount = getExpectedRouteCount();
187            if (routeCount > 0) {
188                assertNotNull(routes, "Should have some routes defined");
189                assertTrue(routes.size() >= routeCount, "Should have at least one route");
190            }
191            log.debug("Camel Routes: " + routes);
192        }
193    
194        protected int getExpectedRouteCount() {
195            return 1;
196        }
197    
198        @Override
199        protected CamelContext createCamelContext() throws Exception {
200            return SpringCamelContext.springCamelContext(applicationContext, false);
201        }
202    }