Author: davsclaus
Date: Tue Jun 15 05:34:22 2010
New Revision: 954711

URL: http://svn.apache.org/viewvc?rev=954711&view=rev
Log:
CAMEL-2800: Manually started routes is now shutdown by Camel as well.

Added:
    
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/GracefulShutdownNoAutoStartOrderClashTest.java
   (with props)
    
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/ShutdownGracefulNoAutoStartedRoutesTest.java
      - copied, changed from r954362, 
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/SimpleShutdownGracefulTest.java
    
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/SimpleShutdownGracefulNoAtuoStartedTest.java
      - copied, changed from r954362, 
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/SimpleShutdownGracefulTest.java
Modified:
    
camel/trunk/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java

Modified: 
camel/trunk/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java
URL: 
http://svn.apache.org/viewvc/camel/trunk/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java?rev=954711&r1=954710&r2=954711&view=diff
==============================================================================
--- 
camel/trunk/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java
 (original)
+++ 
camel/trunk/camel-core/src/main/java/org/apache/camel/impl/DefaultCamelContext.java
 Tue Jun 15 05:34:22 2010
@@ -17,6 +17,7 @@
 package org.apache.camel.impl;
 
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Date;
@@ -552,7 +553,7 @@ public class DefaultCamelContext extends
     public synchronized void startRoute(String routeId) throws Exception {
         RouteService routeService = routeServices.get(routeId);
         if (routeService != null) {
-            routeService.start();
+            startRouteService(routeService);
         }
     }
 
@@ -926,102 +927,7 @@ public class DefaultCamelContext extends
 
         // the context is now considered started (i.e. isStarted() == true))
         // starting routes is done after, not during context startup
-        synchronized (this) {
-            // list of inputs to start when all the routes have been prepared 
for starting
-            // we use a tree map so the routes will be ordered according to 
startup order defined on the route
-            Map<Integer, DefaultRouteStartupOrder> inputs = new 
TreeMap<Integer, DefaultRouteStartupOrder>();
-
-            // figure out the order in which the routes should be started
-            for (RouteService routeService : routeServices.values()) {
-                Boolean autoStart = 
routeService.getRouteDefinition().isAutoStartup();
-                if (autoStart == null || autoStart) {
-                    try {
-                        // add the inputs from this route service to the list 
to start afterwards
-                        // should be ordered according to the startup number
-                        Integer startupOrder = 
routeService.getRouteDefinition().getStartupOrder();
-                        if (startupOrder == null) {
-                            // auto assign a default startup order
-                            startupOrder = defaultRouteStartupOrder++;
-                        }
-
-                        // create holder object that contains information 
about this route to be started
-                        Route route = 
routeService.getRoutes().iterator().next();
-                        DefaultRouteStartupOrder holder = new 
DefaultRouteStartupOrder(startupOrder, route, routeService);
-
-                        // check for clash by startupOrder id
-                        DefaultRouteStartupOrder other = 
inputs.get(startupOrder);
-                        if (other != null) {
-                            String otherId = other.getRoute().getId();
-                            throw new 
FailedToStartRouteException(holder.getRoute().getId(), "startupOrder clash. 
Route " + otherId + " already has startupOrder "
-                                + startupOrder + " configured which this route 
have as well. Please correct startupOrder to be unique among all your routes.");
-                        } else {
-                            // no clash then add the holder to the existing 
inputs of routes to be started
-                            inputs.put(startupOrder, holder);
-                        }
-                    } catch (FailedToStartRouteException e) {
-                        throw e;
-                    } catch (Exception e) {
-                        throw new FailedToStartRouteException(e);
-                    }
-                } else {
-                    // should not start on startup
-                    LOG.info("Cannot start route " + routeService.getId() + " 
as it is configured with auto startup disabled.");
-                }
-            }
-
-            // now prepare the routes by starting its services before we start 
the input
-            for (Map.Entry<Integer, DefaultRouteStartupOrder> entry : 
inputs.entrySet()) {
-                // defer starting inputs till later as we want to prepare the 
routes by starting
-                // all their processors and child services etc.
-                // then later we open the floods to Camel by starting the 
inputs
-                // what this does is to ensure Camel is more robust on 
starting routes as all routes
-                // will then be prepared in time before we start inputs which 
will consume messages to be routed
-                RouteService routeService = entry.getValue().getRouteService();
-                routeService.startInputs(false);
-                try {
-                    routeService.start();
-                } finally {
-                    routeService.startInputs(true);
-                }
-            }
-
-            // check for clash with multiple consumers of the same endpoints 
which is not allowed
-            List<Endpoint> routeInputs = new ArrayList<Endpoint>();
-            for (Map.Entry<Integer, DefaultRouteStartupOrder> entry : 
inputs.entrySet()) {
-                Integer order = entry.getKey();
-                Route route = entry.getValue().getRoute();
-
-                RouteService routeService = entry.getValue().getRouteService();
-                for (Consumer consumer : routeService.getInputs().values()) {
-                    Endpoint endpoint = consumer.getEndpoint();
-
-                    // is multiple consumers supported
-                    boolean multipleConsumersSupported = false;
-                    if (endpoint instanceof MultipleConsumersSupport) {
-                        multipleConsumersSupported = 
((MultipleConsumersSupport) endpoint).isMultipleConsumersSupported();
-                    }
-
-                    if (!multipleConsumersSupported && 
routeInputs.contains(endpoint)) {
-                        throw new 
FailedToStartRouteException(routeService.getId(),
-                            "Multiple consumers for the same endpoint is not 
allowed: " + endpoint);
-                    } else {
-                        // start the consumer on the route
-                        if (LOG.isDebugEnabled()) {
-                            LOG.debug("Starting consumer (order: " + order + 
") on route: " + route.getId());
-                        }
-                        for (LifecycleStrategy strategy : lifecycleStrategies) 
{
-                            strategy.onServiceAdd(this, consumer, route);
-                        }
-                        ServiceHelper.startService(consumer);
-
-                        routeInputs.add(endpoint);
-
-                        // add to the order which they was started, so we know 
how to stop them in reverse order
-                        routeStartupOrder.add(entry.getValue());
-                    }
-                }
-            }
-        }
+        safelyStartRouteServices(false, routeServices.values());
 
         for (int i = 0; i < getRoutes().size(); i++) {
             Route route = getRoutes().get(i);
@@ -1246,11 +1152,167 @@ public class DefaultCamelContext extends
         } else {
             routeServices.put(key, routeService);
             if (shouldStartRoutes()) {
+                safelyStartRouteServices(true, routeService);
+            }
+        }
+    }
+
+    /**
+     * Starts the routes services in a proper manner which ensures the routes 
will be started in correct order,
+     * check for clash and that the routes will also be shutdown in correct 
order as well.
+     * <p/>
+     * This method <b>must</b> be used to start routes in a safe manner.
+     *
+     * @param forceAutoStart whether to force auto starting the routes, 
despite they may be configured not do do so
+     * @param routeServices  the routes
+     * @throws Exception is thrown if error starting the routes
+     */
+    protected synchronized void safelyStartRouteServices(boolean 
forceAutoStart, Collection<RouteService> routeServices) throws Exception {
+        // list of inputs to start when all the routes have been prepared for 
starting
+        // we use a tree map so the routes will be ordered according to 
startup order defined on the route
+        Map<Integer, DefaultRouteStartupOrder> inputs = new TreeMap<Integer, 
DefaultRouteStartupOrder>();
+
+        // figure out the order in which the routes should be started
+        for (RouteService routeService : routeServices) {
+            DefaultRouteStartupOrder order = 
doPrepareRouteToBeStarted(routeService, forceAutoStart);
+            // check for clash before we add it as input
+            if (order != null && doCheckStartupOrderClash(order, inputs)) {
+                inputs.put(order.getStartupOrder(), order);
+            }
+        }
+
+        // warm up routes before we start them
+        doWarmUpRoutes(inputs);
+
+        // and now start the routes
+        // and check for clash with multiple consumers of the same endpoints 
which is not allowed
+        List<Endpoint> routeInputs = new ArrayList<Endpoint>();
+        doStartRoutes(inputs, routeInputs);
+        // inputs no longer needed
+        inputs.clear();
+    }
+
+    protected synchronized void safelyStartRouteServices(boolean 
forceAutoStart, RouteService... routeServices) throws Exception {
+        safelyStartRouteServices(forceAutoStart, Arrays.asList(routeServices));
+    }
+
+    private DefaultRouteStartupOrder doPrepareRouteToBeStarted(RouteService 
routeService, boolean forceAutoStart) throws Exception {
+        DefaultRouteStartupOrder answer = null;
+
+        Boolean autoStart = routeService.getRouteDefinition().isAutoStartup();
+        if (autoStart == null || autoStart || forceAutoStart) {
+            try {
+                // add the inputs from this route service to the list to start 
afterwards
+                // should be ordered according to the startup number
+                Integer startupOrder = 
routeService.getRouteDefinition().getStartupOrder();
+                if (startupOrder == null) {
+                    // auto assign a default startup order
+                    startupOrder = defaultRouteStartupOrder++;
+                }
+
+                // create holder object that contains information about this 
route to be started
+                Route route = routeService.getRoutes().iterator().next();
+                answer = new DefaultRouteStartupOrder(startupOrder, route, 
routeService);
+            } catch (Exception e) {
+                throw new FailedToStartRouteException(e);
+            }
+        } else {
+            // should not start on startup
+            LOG.info("Cannot start route " + routeService.getId() + " as it is 
configured with auto startup disabled.");
+        }
+
+        return answer;
+    }
+
+    private boolean doCheckStartupOrderClash(DefaultRouteStartupOrder answer, 
Map<Integer, DefaultRouteStartupOrder> inputs) throws 
FailedToStartRouteException {
+        // check for clash by startupOrder id
+        DefaultRouteStartupOrder other = inputs.get(answer.getStartupOrder());
+        if (other != null && answer != other) {
+            String otherId = other.getRoute().getId();
+            throw new FailedToStartRouteException(answer.getRoute().getId(), 
"startupOrder clash. Route " + otherId + " already has startupOrder "
+                + answer.getStartupOrder() + " configured which this route 
have as well. Please correct startupOrder to be unique among all your routes.");
+        }
+        // check in existing already started as well
+        for (RouteStartupOrder order : routeStartupOrder) {
+            String otherId = order.getRoute().getId();
+            if (answer.getStartupOrder() == order.getStartupOrder()) {
+                throw new 
FailedToStartRouteException(answer.getRoute().getId(), "startupOrder clash. 
Route " + otherId + " already has startupOrder "
+                    + answer.getStartupOrder() + " configured which this route 
have as well. Please correct startupOrder to be unique among all your routes.");
+            }
+        }
+        return true;
+    }
+
+    private void doWarmUpRoutes(Map<Integer, DefaultRouteStartupOrder> inputs) 
throws Exception {
+        // now prepare the routes by starting its services before we start the 
input
+        for (Map.Entry<Integer, DefaultRouteStartupOrder> entry : 
inputs.entrySet()) {
+            // defer starting inputs till later as we want to prepare the 
routes by starting
+            // all their processors and child services etc.
+            // then later we open the floods to Camel by starting the inputs
+            // what this does is to ensure Camel is more robust on starting 
routes as all routes
+            // will then be prepared in time before we start inputs which will 
consume messages to be routed
+            RouteService routeService = entry.getValue().getRouteService();
+            routeService.startInputs(false);
+            try {
                 routeService.start();
+            } finally {
+                routeService.startInputs(true);
+            }
+        }
+    }
+
+    private void doStartRoutes(Map<Integer, DefaultRouteStartupOrder> inputs, 
List<Endpoint> routeInputs) throws Exception {
+        for (Map.Entry<Integer, DefaultRouteStartupOrder> entry : 
inputs.entrySet()) {
+            Integer order = entry.getKey();
+            Route route = entry.getValue().getRoute();
+
+            RouteService routeService = entry.getValue().getRouteService();
+            for (Consumer consumer : routeService.getInputs().values()) {
+                Endpoint endpoint = consumer.getEndpoint();
+
+                // check multiple consumer violation
+                if (!doCheckMultipleConsumerSupportClash(endpoint, 
routeInputs)) {
+                    throw new FailedToStartRouteException(routeService.getId(),
+                        "Multiple consumers for the same endpoint is not 
allowed: " + endpoint);
+                }
+
+                // start the consumer on the route
+                if (LOG.isDebugEnabled()) {
+                    LOG.debug("Starting consumer (order: " + order + ") on 
route: " + route.getId());
+                }
+                for (LifecycleStrategy strategy : lifecycleStrategies) {
+                    strategy.onServiceAdd(this, consumer, route);
+                }
+                ServiceHelper.startService(consumer);
+
+                routeInputs.add(endpoint);
+
+                // add to the order which they was started, so we know how to 
stop them in reverse order
+                routeStartupOrder.add(entry.getValue());
             }
         }
     }
 
+    private boolean doCheckMultipleConsumerSupportClash(Endpoint endpoint, 
List<Endpoint> routeInputs) {
+        // is multiple consumers supported
+        boolean multipleConsumersSupported = false;
+        if (endpoint instanceof MultipleConsumersSupport) {
+            multipleConsumersSupported = ((MultipleConsumersSupport) 
endpoint).isMultipleConsumersSupported();
+        }
+
+        if (multipleConsumersSupported) {
+            // multiple consumer allowed, so return true
+            return true;
+        }
+
+        // check in progress list
+        if (routeInputs.contains(endpoint)) {
+            return false;
+        }
+
+        return true;
+    }
+
     /**
      * Lets force some lazy initialization to occur upfront before we start any
      * components and create routes

Added: 
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/GracefulShutdownNoAutoStartOrderClashTest.java
URL: 
http://svn.apache.org/viewvc/camel/trunk/camel-core/src/test/java/org/apache/camel/impl/GracefulShutdownNoAutoStartOrderClashTest.java?rev=954711&view=auto
==============================================================================
--- 
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/GracefulShutdownNoAutoStartOrderClashTest.java
 (added)
+++ 
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/GracefulShutdownNoAutoStartOrderClashTest.java
 Tue Jun 15 05:34:22 2010
@@ -0,0 +1,52 @@
+/**
+ * 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.impl;
+
+import org.apache.camel.ContextTestSupport;
+import org.apache.camel.FailedToStartRouteException;
+import org.apache.camel.builder.RouteBuilder;
+
+/**
+ * @version $Revision$
+ */
+public class GracefulShutdownNoAutoStartOrderClashTest extends 
ContextTestSupport {
+
+    public void testStartupOrderClash() throws Exception {
+        getMockEndpoint("mock:foo").expectedMessageCount(1);
+        template.sendBody("direct:foo", "Hello World");
+        assertMockEndpointsSatisfied();
+
+        try {
+            context.startRoute("bar");
+            fail("Should have thrown an exception");
+        } catch (FailedToStartRouteException e) {
+            assertEquals("Failed to start route bar because of startupOrder 
clash. Route foo already has startupOrder 5 configured"
+                + " which this route have as well. Please correct startupOrder 
to be unique among all your routes.", e.getMessage());
+        }
+    }
+
+    @Override
+    protected RouteBuilder createRouteBuilder() throws Exception {
+        return new RouteBuilder() {
+            @Override
+            public void configure() throws Exception {
+                
from("direct:foo").routeId("foo").startupOrder(5).to("mock:foo");
+                
from("direct:bar").routeId("bar").startupOrder(5).noAutoStartup().to("mock:bar");
+            }
+        };
+    }
+}

Propchange: 
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/GracefulShutdownNoAutoStartOrderClashTest.java
------------------------------------------------------------------------------
    svn:eol-style = native

Propchange: 
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/GracefulShutdownNoAutoStartOrderClashTest.java
------------------------------------------------------------------------------
    svn:keywords = Rev Date

Copied: 
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/ShutdownGracefulNoAutoStartedRoutesTest.java
 (from r954362, 
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/SimpleShutdownGracefulTest.java)
URL: 
http://svn.apache.org/viewvc/camel/trunk/camel-core/src/test/java/org/apache/camel/impl/ShutdownGracefulNoAutoStartedRoutesTest.java?p2=camel/trunk/camel-core/src/test/java/org/apache/camel/impl/ShutdownGracefulNoAutoStartedRoutesTest.java&p1=camel/trunk/camel-core/src/test/java/org/apache/camel/impl/SimpleShutdownGracefulTest.java&r1=954362&r2=954711&rev=954711&view=diff
==============================================================================
--- 
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/SimpleShutdownGracefulTest.java
 (original)
+++ 
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/ShutdownGracefulNoAutoStartedRoutesTest.java
 Tue Jun 15 05:34:22 2010
@@ -17,28 +17,28 @@
 package org.apache.camel.impl;
 
 import org.apache.camel.ContextTestSupport;
-import org.apache.camel.Exchange;
-import org.apache.camel.Processor;
 import org.apache.camel.builder.RouteBuilder;
 
 /**
  * @version $Revision$
  */
-public class SimpleShutdownGracefulTest extends ContextTestSupport {
-
-    private static String foo = "";
+public class ShutdownGracefulNoAutoStartedRoutesTest extends 
ContextTestSupport {
 
     public void testShutdownGraceful() throws Exception {
         getMockEndpoint("mock:foo").expectedMessageCount(1);
-        template.sendBody("seda:foo", "Hello World");
+        getMockEndpoint("mock:bar").expectedMessageCount(1);
+
+        context.startRoute("bar");
+
+        template.sendBody("direct:foo", "Hello World");
+        template.sendBody("direct:bar", "Bye World");
+
         assertMockEndpointsSatisfied();
 
-        // now stop the route before its complete
-        foo = foo + "stop";
         context.stop();
 
-        // it should wait as there was 1 inflight exchange when asked to stop
-        assertEquals("Should graceful shutdown", "stopHello World", foo);
+        assertTrue("Route foo should be stopped", 
context.getRouteStatus("foo").isStopped());
+        assertTrue("Route bar should be stopped", 
context.getRouteStatus("bar").isStopped());
     }
 
     @Override
@@ -46,12 +46,10 @@ public class SimpleShutdownGracefulTest 
         return new RouteBuilder() {
             @Override
             public void configure() throws Exception {
-                from("seda:foo").to("mock:foo").delay(3000).process(new 
Processor() {
-                    public void process(Exchange exchange) throws Exception {
-                        foo = foo + exchange.getIn().getBody(String.class);
-                    }
-                });
+                from("direct:foo").routeId("foo").to("mock:foo");
+
+                
from("direct:bar").routeId("bar").noAutoStartup().to("mock:bar");
             }
         };
     }
-}
+}
\ No newline at end of file

Copied: 
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/SimpleShutdownGracefulNoAtuoStartedTest.java
 (from r954362, 
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/SimpleShutdownGracefulTest.java)
URL: 
http://svn.apache.org/viewvc/camel/trunk/camel-core/src/test/java/org/apache/camel/impl/SimpleShutdownGracefulNoAtuoStartedTest.java?p2=camel/trunk/camel-core/src/test/java/org/apache/camel/impl/SimpleShutdownGracefulNoAtuoStartedTest.java&p1=camel/trunk/camel-core/src/test/java/org/apache/camel/impl/SimpleShutdownGracefulTest.java&r1=954362&r2=954711&rev=954711&view=diff
==============================================================================
--- 
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/SimpleShutdownGracefulTest.java
 (original)
+++ 
camel/trunk/camel-core/src/test/java/org/apache/camel/impl/SimpleShutdownGracefulNoAtuoStartedTest.java
 Tue Jun 15 05:34:22 2010
@@ -24,11 +24,13 @@ import org.apache.camel.builder.RouteBui
 /**
  * @version $Revision$
  */
-public class SimpleShutdownGracefulTest extends ContextTestSupport {
+public class SimpleShutdownGracefulNoAtuoStartedTest extends 
ContextTestSupport {
 
     private static String foo = "";
 
     public void testShutdownGraceful() throws Exception {
+        context.startRoute("foo");
+
         getMockEndpoint("mock:foo").expectedMessageCount(1);
         template.sendBody("seda:foo", "Hello World");
         assertMockEndpointsSatisfied();
@@ -46,7 +48,7 @@ public class SimpleShutdownGracefulTest 
         return new RouteBuilder() {
             @Override
             public void configure() throws Exception {
-                from("seda:foo").to("mock:foo").delay(3000).process(new 
Processor() {
+                
from("seda:foo").routeId("foo").noAutoStartup().to("mock:foo").delay(3000).process(new
 Processor() {
                     public void process(Exchange exchange) throws Exception {
                         foo = foo + exchange.getIn().getBody(String.class);
                     }
@@ -54,4 +56,4 @@ public class SimpleShutdownGracefulTest 
             }
         };
     }
-}
+}
\ No newline at end of file


Reply via email to