This is an automated email from the ASF dual-hosted git repository.

lburgazzoli pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/camel.git


The following commit(s) were added to refs/heads/master by this push:
     new 1f4c8ea  CAMEL-15056: camel-main: provide a way to bring a custom 
engine to control shutdown logic
1f4c8ea is described below

commit 1f4c8ead861dca33e8d91ece6f59ceb31c864fb5
Author: lburgazzoli <[email protected]>
AuthorDate: Wed May 13 17:55:06 2020 +0200

    CAMEL-15056: camel-main: provide a way to bring a custom engine to control 
shutdown logic
---
 .../MainConfigurationPropertiesConfigurer.java     |   5 -
 .../camel-main-configuration-metadata.json         |   1 -
 .../org/apache/camel/main/BaseMainSupport.java     |   5 +-
 .../camel/main/DefaultMainShutdownStrategy.java    |  81 +++++++++++++
 .../src/main/java/org/apache/camel/main/Main.java  |  10 +-
 .../camel/main/MainConfigurationProperties.java    |  20 ----
 .../camel/main/MainDurationEventNotifier.java      | 133 +++++++++++----------
 .../apache/camel/main/MainLifecycleStrategy.java   |  16 +--
 .../apache/camel/main/MainShutdownStrategy.java    |  44 +++++++
 .../java/org/apache/camel/main/MainSupport.java    |  88 +++++---------
 ...rategy.java => SimpleMainShutdownStrategy.java} |  44 ++++---
 .../test/java/org/apache/camel/main/MainTest.java  |   5 +-
 .../src/test/resources/example.properties          |  17 +++
 13 files changed, 279 insertions(+), 190 deletions(-)

diff --git 
a/core/camel-main/src/generated/java/org/apache/camel/main/MainConfigurationPropertiesConfigurer.java
 
b/core/camel-main/src/generated/java/org/apache/camel/main/MainConfigurationPropertiesConfigurer.java
index 810f174..07b19fb 100644
--- 
a/core/camel-main/src/generated/java/org/apache/camel/main/MainConfigurationPropertiesConfigurer.java
+++ 
b/core/camel-main/src/generated/java/org/apache/camel/main/MainConfigurationPropertiesConfigurer.java
@@ -71,8 +71,6 @@ public class MainConfigurationPropertiesConfigurer extends 
org.apache.camel.supp
         case "EndpointRuntimeStatisticsEnabled": 
target.setEndpointRuntimeStatisticsEnabled(property(camelContext, 
boolean.class, value)); return true;
         case "fileconfigurations":
         case "FileConfigurations": 
target.setFileConfigurations(property(camelContext, java.lang.String.class, 
value)); return true;
-        case "hangupinterceptorenabled":
-        case "HangupInterceptorEnabled": 
target.setHangupInterceptorEnabled(property(camelContext, boolean.class, 
value)); return true;
         case "inflightrepositorybrowseenabled":
         case "InflightRepositoryBrowseEnabled": 
target.setInflightRepositoryBrowseEnabled(property(camelContext, boolean.class, 
value)); return true;
         case "javaroutesexcludepattern":
@@ -214,7 +212,6 @@ public class MainConfigurationPropertiesConfigurer extends 
org.apache.camel.supp
         answer.put("EndpointLazyStartProducer", boolean.class);
         answer.put("EndpointRuntimeStatisticsEnabled", boolean.class);
         answer.put("FileConfigurations", java.lang.String.class);
-        answer.put("HangupInterceptorEnabled", boolean.class);
         answer.put("InflightRepositoryBrowseEnabled", boolean.class);
         answer.put("JavaRoutesExcludePattern", java.lang.String.class);
         answer.put("JavaRoutesIncludePattern", java.lang.String.class);
@@ -328,8 +325,6 @@ public class MainConfigurationPropertiesConfigurer extends 
org.apache.camel.supp
         case "EndpointRuntimeStatisticsEnabled": return 
target.isEndpointRuntimeStatisticsEnabled();
         case "fileconfigurations":
         case "FileConfigurations": return target.getFileConfigurations();
-        case "hangupinterceptorenabled":
-        case "HangupInterceptorEnabled": return 
target.isHangupInterceptorEnabled();
         case "inflightrepositorybrowseenabled":
         case "InflightRepositoryBrowseEnabled": return 
target.isInflightRepositoryBrowseEnabled();
         case "javaroutesexcludepattern":
diff --git 
a/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json
 
b/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json
index 09f05e7..b162d2e 100644
--- 
a/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json
+++ 
b/core/camel-main/src/generated/resources/META-INF/camel-main-configuration-metadata.json
@@ -33,7 +33,6 @@
     { "name": "camel.main.endpointLazyStartProducer", "description": "Whether 
the producer should be started lazy (on the first message). By starting lazy 
you can use this to allow CamelContext and routes to startup in situations 
where a producer may otherwise fail during starting and cause the route to fail 
being started. By deferring this startup to be lazy then the startup failure 
can be handled during routing messages via Camel's routing error handlers. 
Beware that when the first mes [...]
     { "name": "camel.main.endpointRuntimeStatisticsEnabled", "description": 
"Sets whether endpoint runtime statistics is enabled (gathers runtime usage of 
each incoming and outgoing endpoints). The default value is false.", 
"sourceType": "org.apache.camel.main.DefaultConfigurationProperties", "type": 
"boolean", "javaType": "boolean" },
     { "name": "camel.main.fileConfigurations", "description": "Directory to 
load additional configuration files that contains configuration values that 
takes precedence over any other configuration. This can be used to refer to 
files that may have secret configuration that has been mounted on the file 
system for containers. You can specify a pattern to load from sub directories 
and a name pattern such as \/var\/app\/secret\/.properties, multiple 
directories can be separated by comma.", " [...]
-    { "name": "camel.main.hangupInterceptorEnabled", "description": "Whether 
to use graceful hangup when Camel is stopping or when the JVM terminates.", 
"sourceType": "org.apache.camel.main.MainConfigurationProperties", "type": 
"boolean", "javaType": "boolean", "defaultValue": true },
     { "name": "camel.main.inflightRepositoryBrowseEnabled", "description": 
"Sets whether the inflight repository should allow browsing each inflight 
exchange. This is by default disabled as there is a very slight performance 
overhead when enabled.", "sourceType": 
"org.apache.camel.main.DefaultConfigurationProperties", "type": "boolean", 
"javaType": "boolean" },
     { "name": "camel.main.javaRoutesExcludePattern", "description": "Used for 
exclusive filtering component scanning of RouteBuilder classes with Component 
annotation. The exclusive filtering takes precedence over inclusive filtering. 
The pattern is using Ant-path style pattern. Multiple patterns can be specified 
separated by comma. For example to exclude all classes starting with Bar use: 
&#42;&#42;\/Bar&#42; To exclude all routes form a specific package use: 
com\/mycompany\/bar\/&#42;  [...]
     { "name": "camel.main.javaRoutesIncludePattern", "description": "Used for 
inclusive filtering component scanning of RouteBuilder classes with Component 
annotation. The exclusive filtering takes precedence over inclusive filtering. 
The pattern is using Ant-path style pattern. Multiple patterns can be specified 
separated by comma. For example to include all classes starting with Foo use: 
&#42;&#42;\/Foo To include all routes form a specific package use: 
com\/mycompany\/foo\/&#42; To in [...]
diff --git 
a/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java 
b/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java
index f25b734..ef615c3 100644
--- a/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java
+++ b/core/camel-main/src/main/java/org/apache/camel/main/BaseMainSupport.java
@@ -33,7 +33,6 @@ import java.util.Optional;
 import java.util.Properties;
 import java.util.Set;
 import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.function.Function;
 
 import org.apache.camel.CamelContext;
@@ -74,8 +73,8 @@ import 
org.apache.camel.util.concurrent.ThreadPoolRejectedPolicy;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import static org.apache.camel.main.MainHelper.lookupPropertyFromSysOrEnv;
 import static 
org.apache.camel.main.MainHelper.loadEnvironmentVariablesAsProperties;
+import static org.apache.camel.main.MainHelper.lookupPropertyFromSysOrEnv;
 import static org.apache.camel.support.ObjectHelper.invokeMethod;
 import static org.apache.camel.util.ReflectionHelper.findMethod;
 import static org.apache.camel.util.StringHelper.matches;
@@ -95,8 +94,6 @@ public abstract class BaseMainSupport extends BaseService {
 
     private static final String VALID_THREAD_POOL_KEYS = 
"id|poolSize|maxPoolSize|keepAliveTime|timeUnit|maxQueueSize|allowCoreThreadTimeout|rejectedPolicy";
 
-    protected final AtomicBoolean completed = new AtomicBoolean(false);
-
     protected volatile CamelContext camelContext;
     protected volatile ProducerTemplate camelTemplate;
 
diff --git 
a/core/camel-main/src/main/java/org/apache/camel/main/DefaultMainShutdownStrategy.java
 
b/core/camel-main/src/main/java/org/apache/camel/main/DefaultMainShutdownStrategy.java
new file mode 100644
index 0000000..638dc4b
--- /dev/null
+++ 
b/core/camel-main/src/main/java/org/apache/camel/main/DefaultMainShutdownStrategy.java
@@ -0,0 +1,81 @@
+/*
+ * 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.main;
+
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.camel.util.concurrent.ThreadHelper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Implementation of {@link MainShutdownStrategy} that add a virtual machine 
shutdown hook to
+ * properly stop the main instance.
+ */
+public class DefaultMainShutdownStrategy extends SimpleMainShutdownStrategy {
+    protected static final Logger LOG = 
LoggerFactory.getLogger(DefaultMainShutdownStrategy.class);
+
+    private final AtomicBoolean hangupIntercepted;
+
+    private volatile boolean hangupInterceptorEnabled;
+
+    public DefaultMainShutdownStrategy() {
+        this.hangupIntercepted = new AtomicBoolean();
+    }
+
+    /**
+     * Disable the hangup support. No graceful stop by calling stop() on a
+     * Hangup signal.
+     */
+    public void disableHangupSupport() {
+        hangupInterceptorEnabled = false;
+    }
+
+    /**
+     * Hangup support is enabled by default.
+     */
+    public void enableHangupSupport() {
+        hangupInterceptorEnabled = true;
+    }
+
+    @Override
+    public void await() throws InterruptedException {
+        installHangupInterceptor();
+        super.await();
+    }
+
+    @Override
+    public void await(long timeout, TimeUnit unit) throws InterruptedException 
{
+        installHangupInterceptor();
+        super.await(timeout, unit);
+    }
+
+    private void handleHangup() {
+        LOG.info("Received hang up - stopping the main instance.");
+        shutdown();
+    }
+
+    private void installHangupInterceptor() {
+        if (this.hangupIntercepted.compareAndSet(false, 
hangupInterceptorEnabled)) {
+            Thread task = new Thread(this::handleHangup);
+            task.setName(ThreadHelper.resolveThreadName(null, 
"CamelHangupInterceptor"));
+
+            Runtime.getRuntime().addShutdownHook(task);
+        }
+    }
+}
diff --git a/core/camel-main/src/main/java/org/apache/camel/main/Main.java 
b/core/camel-main/src/main/java/org/apache/camel/main/Main.java
index c846850..45ecfc7 100644
--- a/core/camel-main/src/main/java/org/apache/camel/main/Main.java
+++ b/core/camel-main/src/main/java/org/apache/camel/main/Main.java
@@ -35,7 +35,7 @@ public class Main extends MainCommandLineSupport {
     public Main() {
     }
 
-    public Main(Class... configurationClass) {
+    public Main(Class<?>... configurationClass) {
         super(configurationClass);
     }
 
@@ -60,7 +60,7 @@ public class Main extends MainCommandLineSupport {
      * Binds the given <code>name</code> to the <code>bean</code> object, so
      * that it can be looked up inside the CamelContext this command line tool
      * runs with.
-     * 
+     *
      * @param name the used name through which we do bind
      * @param bean the object to bind
      */
@@ -71,7 +71,7 @@ public class Main extends MainCommandLineSupport {
     /**
      * Using the given <code>name</code> does lookup for the bean being already
      * bound using the {@link #bind(String, Object)} method.
-     * 
+     *
      * @see Registry#lookupByName(String)
      */
     public Object lookup(String name) {
@@ -82,7 +82,7 @@ public class Main extends MainCommandLineSupport {
      * Using the given <code>name</code> and <code>type</code> does lookup for
      * the bean being already bound using the {@link #bind(String, Object)}
      * method.
-     * 
+     *
      * @see Registry#lookupByNameAndType(String, Class)
      */
     public <T> T lookup(String name, Class<T> type) {
@@ -92,7 +92,7 @@ public class Main extends MainCommandLineSupport {
     /**
      * Using the given <code>type</code> does lookup for the bean being already
      * bound using the {@link #bind(String, Object)} method.
-     * 
+     *
      * @see Registry#findByTypeWithName(Class)
      */
     public <T> Map<String, T> lookupByType(Class<T> type) {
diff --git 
a/core/camel-main/src/main/java/org/apache/camel/main/MainConfigurationProperties.java
 
b/core/camel-main/src/main/java/org/apache/camel/main/MainConfigurationProperties.java
index c579361..d5529ce 100644
--- 
a/core/camel-main/src/main/java/org/apache/camel/main/MainConfigurationProperties.java
+++ 
b/core/camel-main/src/main/java/org/apache/camel/main/MainConfigurationProperties.java
@@ -37,7 +37,6 @@ public class MainConfigurationProperties extends 
DefaultConfigurationProperties<
     private boolean autowireComponentPropertiesNonNullOnly;
     private boolean autowireComponentPropertiesAllowPrivateSetter = true;
     private int durationHitExitCode;
-    private boolean hangupInterceptorEnabled = true;
     private String packageScanRouteBuilders;
 
     private String routesBuilderClasses;
@@ -211,17 +210,6 @@ public class MainConfigurationProperties extends 
DefaultConfigurationProperties<
         this.autowireComponentPropertiesAllowPrivateSetter = 
autowireComponentPropertiesAllowPrivateSetter;
     }
 
-    public boolean isHangupInterceptorEnabled() {
-        return hangupInterceptorEnabled;
-    }
-
-    /**
-     * Whether to use graceful hangup when Camel is stopping or when the JVM 
terminates.
-     */
-    public void setHangupInterceptorEnabled(boolean hangupInterceptorEnabled) {
-        this.hangupInterceptorEnabled = hangupInterceptorEnabled;
-    }
-
     public String getPackageScanRouteBuilders() {
         return packageScanRouteBuilders;
     }
@@ -456,14 +444,6 @@ public class MainConfigurationProperties extends 
DefaultConfigurationProperties<
     }
 
     /**
-     * Whether to use graceful hangup when Camel is stopping or when the JVM 
terminates.
-     */
-    public MainConfigurationProperties withHangupInterceptorEnabled(boolean 
hangupInterceptorEnabled) {
-        this.hangupInterceptorEnabled = hangupInterceptorEnabled;
-        return this;
-    }
-
-    /**
      * Sets the exit code for the application if duration was hit
      */
     public MainConfigurationProperties withDurationHitExitCode(int 
durationHitExitCode) {
diff --git 
a/core/camel-main/src/main/java/org/apache/camel/main/MainDurationEventNotifier.java
 
b/core/camel-main/src/main/java/org/apache/camel/main/MainDurationEventNotifier.java
index cc7c5bf..9d8fa0d 100644
--- 
a/core/camel-main/src/main/java/org/apache/camel/main/MainDurationEventNotifier.java
+++ 
b/core/camel-main/src/main/java/org/apache/camel/main/MainDurationEventNotifier.java
@@ -16,11 +16,10 @@
  */
 package org.apache.camel.main;
 
-import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
 
 import org.apache.camel.CamelContext;
 import org.apache.camel.spi.CamelEvent;
@@ -42,46 +41,41 @@ public class MainDurationEventNotifier extends 
EventNotifierSupport {
     private final CamelContext camelContext;
     private final int maxMessages;
     private final long maxIdleSeconds;
-    private final AtomicBoolean completed;
-    private final CountDownLatch latch;
+    private final MainShutdownStrategy shutdownStrategy;
     private final boolean stopCamelContext;
+    private final AtomicInteger doneMessages;
 
-    private volatile int doneMessages;
     private volatile StopWatch watch;
     private volatile ScheduledExecutorService idleExecutorService;
 
     public MainDurationEventNotifier(CamelContext camelContext, int 
maxMessages, long maxIdleSeconds,
-                                     AtomicBoolean completed, CountDownLatch 
latch, boolean stopCamelContext) {
+                                     MainShutdownStrategy shutdownStrategy, 
boolean stopCamelContext) {
         this.camelContext = camelContext;
         this.maxMessages = maxMessages;
         this.maxIdleSeconds = maxIdleSeconds;
-        this.completed = completed;
-        this.latch = latch;
+        this.shutdownStrategy = shutdownStrategy;
         this.stopCamelContext = stopCamelContext;
+        this.doneMessages = new AtomicInteger(0);
     }
 
     @Override
     public void notify(CamelEvent event) throws Exception {
+        // ignore any event that is received if shutdown is in process
+        if (!shutdownStrategy.isRunAllowed()) {
+            return;
+        }
+
         boolean begin = event instanceof ExchangeCreatedEvent;
         boolean complete = event instanceof ExchangeCompletedEvent || event 
instanceof ExchangeFailedEvent;
 
         if (maxMessages > 0 && complete) {
-            doneMessages++;
-
-            boolean result = doneMessages >= maxMessages;
-            LOG.trace("Duration max messages check {} >= {} -> {}", 
doneMessages, maxMessages, result);
-
-            if (result) {
-                if (completed.compareAndSet(false, true)) {
-                    LOG.info("Duration max messages triggering shutdown of the 
JVM.");
-                    // use thread to stop Camel as otherwise we would block 
current thread
-                    Thread thread = 
camelContext.getExecutorServiceManager().newThread("CamelMainShutdownCamelContext",
 new ShutdownTask());
-                    thread.start();
-                    // shutdown idle checker if in use as we are stopping
-                    if (idleExecutorService != null) {
-                        idleExecutorService.shutdownNow();
-                    }
-                }
+            boolean result = doneMessages.incrementAndGet() >= maxMessages;
+            LOG.trace("Duration max messages check {} >= {} -> {}", 
doneMessages.get(), maxMessages, result);
+
+            if (result && shutdownStrategy.isRunAllowed()) {
+                LOG.info("Duration max messages triggering shutdown of the 
JVM.");
+                // use thread to stop Camel as otherwise we would block 
current thread
+                
camelContext.getExecutorServiceManager().newThread("CamelMainShutdownCamelContext",
 this::shutdownTask).start();
             }
         }
 
@@ -105,58 +99,65 @@ public class MainDurationEventNotifier extends 
EventNotifierSupport {
     @Override
     protected void doStart() throws Exception {
         if (maxIdleSeconds > 0) {
-
             // we only start watch when Camel is started
             camelContext.addStartupListener((context, alreadyStarted) -> watch 
= new StopWatch());
 
             // okay we need to trigger on idle after X period, and therefore 
we need a background task that checks this
             idleExecutorService = Executors.newSingleThreadScheduledExecutor();
-            Runnable task = () -> {
-                if (watch == null) {
-                    // camel has not been started yet
-                    return;
-                }
-
-                // any inflight messages currently
-                int inflight = camelContext.getInflightRepository().size();
-                if (inflight > 0) {
-                    LOG.trace("Duration max idle check is skipped due {} 
inflight messages", inflight);
-                    return;
-                }
-
-                long seconds = watch.taken() / 1000;
-                boolean result = seconds >= maxIdleSeconds;
-                LOG.trace("Duration max idle check {} >= {} -> {}", seconds, 
maxIdleSeconds, result);
-
-                if (result) {
-                    if (completed.compareAndSet(false, true)) {
-                        LOG.info("Duration max idle triggering shutdown of the 
JVM.");
-                        // use thread to stop Camel as otherwise we would 
block current thread
-                        Thread thread = 
camelContext.getExecutorServiceManager().newThread("CamelMainShutdownCamelContext",
 new ShutdownTask());
-                        thread.start();
-                    }
-                }
-            };
-            idleExecutorService.scheduleAtFixedRate(task, 1, 1, 
TimeUnit.SECONDS);
+            idleExecutorService.scheduleAtFixedRate(this::idleTask, 1, 1, 
TimeUnit.SECONDS);
         }
     }
 
-    private class ShutdownTask implements Runnable {
-
-        @Override
-        public void run() {
-            try {
-                // shutting down CamelContext
-                if (stopCamelContext) {
-                    camelContext.stop();
-                }
-            } catch (Exception e) {
-                LOG.warn("Error during stopping CamelContext. This exception 
is ignored.", e);
-            } finally {
-                // trigger stopping the Main
-                latch.countDown();
+    private void shutdownTask() {
+        // don't run the task if shutdown is in process
+        if (!shutdownStrategy.isRunAllowed()) {
+            return;
+        }
+
+        // shutdown idle checker if in use as we are stopping
+        if (idleExecutorService != null) {
+            idleExecutorService.shutdownNow();
+        }
+
+        try {
+            // shutting down CamelContext
+            if (stopCamelContext) {
+                camelContext.stop();
             }
+        } catch (Exception e) {
+            LOG.warn("Error during stopping CamelContext. This exception is 
ignored.", e);
+        } finally {
+            // trigger stopping the Main
+            shutdownStrategy.shutdown();
         }
     }
 
+    private void idleTask() {
+        // don't run the task if shutdown is in process
+        if (!shutdownStrategy.isRunAllowed()) {
+            return;
+        }
+
+        if (watch == null) {
+            // camel has not been started yet
+            return;
+        }
+
+        // any inflight messages currently
+        int inflight = camelContext.getInflightRepository().size();
+        if (inflight > 0) {
+            LOG.trace("Duration max idle check is skipped due {} inflight 
messages", inflight);
+            return;
+        }
+
+        long seconds = watch.taken() / 1000;
+        boolean result = seconds >= maxIdleSeconds;
+        LOG.trace("Duration max idle check {} >= {} -> {}", seconds, 
maxIdleSeconds, result);
+
+        if (result && shutdownStrategy.isRunAllowed()) {
+            LOG.info("Duration max idle triggering shutdown of the JVM.");
+            // use thread to stop Camel as otherwise we would block current 
thread
+            
camelContext.getExecutorServiceManager().newThread("CamelMainShutdownCamelContext",
 this::shutdownTask).start();
+        }
+    }
 }
diff --git 
a/core/camel-main/src/main/java/org/apache/camel/main/MainLifecycleStrategy.java
 
b/core/camel-main/src/main/java/org/apache/camel/main/MainLifecycleStrategy.java
index 2ab3daf..72d51af 100644
--- 
a/core/camel-main/src/main/java/org/apache/camel/main/MainLifecycleStrategy.java
+++ 
b/core/camel-main/src/main/java/org/apache/camel/main/MainLifecycleStrategy.java
@@ -16,9 +16,6 @@
  */
 package org.apache.camel.main;
 
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.atomic.AtomicBoolean;
-
 import org.apache.camel.CamelContext;
 import org.apache.camel.support.LifecycleStrategySupport;
 import org.slf4j.Logger;
@@ -29,21 +26,18 @@ import org.slf4j.LoggerFactory;
  * when {@link CamelContext} is stopped from JMX or its stop method is invoked 
from Java code.
  */
 public class MainLifecycleStrategy extends LifecycleStrategySupport {
-
     private static final Logger LOG = 
LoggerFactory.getLogger(MainLifecycleStrategy.class);
-    private final AtomicBoolean completed;
-    private final CountDownLatch latch;
+    private final MainShutdownStrategy shutdownStrategy;
 
-    public MainLifecycleStrategy(AtomicBoolean completed, CountDownLatch 
latch) {
-        this.completed = completed;
-        this.latch = latch;
+    public MainLifecycleStrategy(MainShutdownStrategy shutdownStrategy) {
+        this.shutdownStrategy = shutdownStrategy;
     }
 
     @Override
     public void onContextStop(CamelContext context) {
         LOG.info("CamelContext: {} has been shutdown, triggering shutdown of 
the JVM.", context.getName());
+
         // trigger stopping the Main
-        completed.set(true);
-        latch.countDown();
+        shutdownStrategy.shutdown();
     }
 }
diff --git 
a/core/camel-main/src/main/java/org/apache/camel/main/MainShutdownStrategy.java 
b/core/camel-main/src/main/java/org/apache/camel/main/MainShutdownStrategy.java
new file mode 100644
index 0000000..0a28303
--- /dev/null
+++ 
b/core/camel-main/src/main/java/org/apache/camel/main/MainShutdownStrategy.java
@@ -0,0 +1,44 @@
+/*
+ * 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.main;
+
+import java.util.concurrent.TimeUnit;
+
+public interface MainShutdownStrategy {
+    /**
+     * @return true if the application is allowed to run.
+     */
+    boolean isRunAllowed();
+
+    /**
+     * @return true if the shutdown has been initiated by the caller.
+     */
+    boolean shutdown();
+
+    /**
+     * Wait for main to complete.
+     */
+    void await() throws InterruptedException;
+
+    /**
+     * Wait for main to complete.
+     *
+     * @param timeout the maximum time to wait
+     * @param unit the time unit of the {@code timeout} argument
+     */
+    void await(long timeout, TimeUnit unit) throws InterruptedException;
+}
diff --git 
a/core/camel-main/src/main/java/org/apache/camel/main/MainSupport.java 
b/core/camel-main/src/main/java/org/apache/camel/main/MainSupport.java
index 013dce7..aeb8982 100644
--- a/core/camel-main/src/main/java/org/apache/camel/main/MainSupport.java
+++ b/core/camel-main/src/main/java/org/apache/camel/main/MainSupport.java
@@ -16,14 +16,12 @@
  */
 package org.apache.camel.main;
 
-import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 
 import org.apache.camel.CamelContext;
 import org.apache.camel.spi.EventNotifier;
 import org.apache.camel.support.service.ServiceHelper;
-import org.apache.camel.util.concurrent.ThreadHelper;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -38,43 +36,23 @@ public abstract class MainSupport extends BaseMainSupport {
     protected static final int DEFAULT_EXIT_CODE = 0;
 
     protected final AtomicInteger exitCode = new 
AtomicInteger(UNINITIALIZED_EXIT_CODE);
-    protected final CountDownLatch latch = new CountDownLatch(1);
+    protected MainShutdownStrategy shutdownStrategy;
 
-    /**
-     * A class for intercepting the hang up signal and do a graceful shutdown 
of the Camel.
-     */
-    private static final class HangupInterceptor extends Thread {
-        Logger log = LoggerFactory.getLogger(this.getClass());
-        final MainSupport mainInstance;
-
-        HangupInterceptor(MainSupport main) {
-            mainInstance = main;
-        }
 
-        @Override
-        public void run() {
-            log.info("Received hang up - stopping the main instance.");
-            try {
-                mainInstance.stop();
-            } catch (Exception ex) {
-                log.warn("Error during stopping the main instance.", ex);
-            }
-        }
-    }
-
-    protected MainSupport(Class... configurationClasses) {
+    protected MainSupport(Class<?>... configurationClasses) {
         this();
         configure().addConfigurationClass(configurationClasses);
     }
 
     protected MainSupport() {
+        this.shutdownStrategy = new DefaultMainShutdownStrategy();
     }
 
     /**
      * Runs this process with the given arguments, and will wait until 
completed, or the JVM terminates.
      */
     public void run() throws Exception {
-        if (!completed.get()) {
+        if (shutdownStrategy.isRunAllowed()) {
             init();
             internalBeforeStart();
             // if we have an issue starting then propagate the exception to 
caller
@@ -95,21 +73,6 @@ public abstract class MainSupport extends BaseMainSupport {
     }
 
     /**
-     * Disable the hangup support. No graceful stop by calling stop() on a
-     * Hangup signal.
-     */
-    public void disableHangupSupport() {
-        mainConfigurationProperties.setHangupInterceptorEnabled(false);
-    }
-
-    /**
-     * Hangup support is enabled by default.
-     */
-    public void enableHangupSupport() {
-        mainConfigurationProperties.setHangupInterceptorEnabled(true);
-    }
-
-    /**
      * Callback to run custom logic before CamelContext is being started.
      * <p/>
      * It is recommended to use {@link org.apache.camel.main.MainListener} 
instead.
@@ -132,13 +95,6 @@ public abstract class MainSupport extends BaseMainSupport {
     }
 
     private void internalBeforeStart() {
-        if (mainConfigurationProperties.isHangupInterceptorEnabled()) {
-            String threadName = ThreadHelper.resolveThreadName(null, 
"CamelHangupInterceptor");
-
-            Thread task = new HangupInterceptor(this);
-            task.setName(threadName);
-            Runtime.getRuntime().addShutdownHook(task);
-        }
     }
 
     /**
@@ -178,9 +134,8 @@ public abstract class MainSupport extends BaseMainSupport {
      * Marks this process as being completed.
      */
     public void completed() {
-        completed.set(true);
+        shutdownStrategy.shutdown();
         exitCode.compareAndSet(UNINITIALIZED_EXIT_CODE, DEFAULT_EXIT_CODE);
-        latch.countDown();
     }
 
     /**
@@ -263,6 +218,19 @@ public abstract class MainSupport extends BaseMainSupport {
         mainConfigurationProperties.setTracing(true);
     }
 
+    public MainShutdownStrategy getShutdownStrategy() {
+        return shutdownStrategy;
+    }
+
+    /**
+     * Set the {@link MainShutdownStrategy} used to properly shut-down the 
main instance. By default a {@link DefaultMainShutdownStrategy}
+     * will be used.
+     * @param shutdownStrategy the shutdown strategy
+     */
+    public void setShutdownStrategy(MainShutdownStrategy shutdownStrategy) {
+        this.shutdownStrategy = shutdownStrategy;
+    }
+
     @Override
     protected void doStop() throws Exception {
         // call completed to properly stop as we count down the waiting latch
@@ -281,8 +249,7 @@ public abstract class MainSupport extends BaseMainSupport {
                 camelContext,
                 mainConfigurationProperties.getDurationMaxMessages(),
                 mainConfigurationProperties.getDurationMaxIdleSeconds(),
-                completed,
-                latch,
+                shutdownStrategy,
                 true);
 
             // register our event notifier
@@ -291,20 +258,20 @@ public abstract class MainSupport extends BaseMainSupport 
{
         }
 
         // register lifecycle so we are notified in Camel is stopped from JMX 
or somewhere else
-        camelContext.addLifecycleStrategy(new MainLifecycleStrategy(completed, 
latch));
+        camelContext.addLifecycleStrategy(new 
MainLifecycleStrategy(shutdownStrategy));
     }
 
     protected void waitUntilCompleted() {
-        while (!completed.get()) {
+        while (shutdownStrategy.isRunAllowed()) {
             try {
                 int idle = 
mainConfigurationProperties.getDurationMaxIdleSeconds();
                 int max = mainConfigurationProperties.getDurationMaxMessages();
                 long sec = mainConfigurationProperties.getDurationMaxSeconds();
                 if (sec > 0) {
                     LOG.info("Waiting for: {} seconds", sec);
-                    latch.await(sec, TimeUnit.SECONDS);
+                    shutdownStrategy.await(sec, TimeUnit.SECONDS);
                     exitCode.compareAndSet(UNINITIALIZED_EXIT_CODE, 
mainConfigurationProperties.getDurationHitExitCode());
-                    completed.set(true);
+                    shutdownStrategy.shutdown();
                 } else if (idle > 0 || max > 0) {
                     if (idle > 0 && max > 0) {
                         LOG.info("Waiting to be idle for: {} seconds or until: 
{} messages has been processed", idle, max);
@@ -314,15 +281,14 @@ public abstract class MainSupport extends BaseMainSupport 
{
                         LOG.info("Waiting until: {} messages has been 
processed", max);
                     }
                     exitCode.compareAndSet(UNINITIALIZED_EXIT_CODE, 
mainConfigurationProperties.getDurationHitExitCode());
-                    latch.await();
-                    completed.set(true);
+                    shutdownStrategy.await();
+                    shutdownStrategy.shutdown();
                 } else {
-                    latch.await();
+                    shutdownStrategy.await();
                 }
             } catch (InterruptedException e) {
                 // okay something interrupted us so terminate
-                completed.set(true);
-                latch.countDown();
+                shutdownStrategy.shutdown();
                 Thread.currentThread().interrupt();
             }
         }
diff --git 
a/core/camel-main/src/main/java/org/apache/camel/main/MainLifecycleStrategy.java
 
b/core/camel-main/src/main/java/org/apache/camel/main/SimpleMainShutdownStrategy.java
similarity index 56%
copy from 
core/camel-main/src/main/java/org/apache/camel/main/MainLifecycleStrategy.java
copy to 
core/camel-main/src/main/java/org/apache/camel/main/SimpleMainShutdownStrategy.java
index 2ab3daf..4fcd180 100644
--- 
a/core/camel-main/src/main/java/org/apache/camel/main/MainLifecycleStrategy.java
+++ 
b/core/camel-main/src/main/java/org/apache/camel/main/SimpleMainShutdownStrategy.java
@@ -17,33 +17,45 @@
 package org.apache.camel.main;
 
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 
-import org.apache.camel.CamelContext;
-import org.apache.camel.support.LifecycleStrategySupport;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-/**
- * A {@link org.apache.camel.spi.LifecycleStrategy} to trigger shutdown of the 
Main JVM
- * when {@link CamelContext} is stopped from JMX or its stop method is invoked 
from Java code.
- */
-public class MainLifecycleStrategy extends LifecycleStrategySupport {
+public class SimpleMainShutdownStrategy implements MainShutdownStrategy {
+    protected static final Logger LOG = 
LoggerFactory.getLogger(SimpleMainShutdownStrategy.class);
 
-    private static final Logger LOG = 
LoggerFactory.getLogger(MainLifecycleStrategy.class);
     private final AtomicBoolean completed;
     private final CountDownLatch latch;
 
-    public MainLifecycleStrategy(AtomicBoolean completed, CountDownLatch 
latch) {
-        this.completed = completed;
-        this.latch = latch;
+    public SimpleMainShutdownStrategy() {
+        this.completed = new AtomicBoolean(false);
+        this.latch = new CountDownLatch(1);
+    }
+
+    @Override
+    public boolean isRunAllowed() {
+        return !completed.get();
+    }
+
+    @Override
+    public boolean shutdown() {
+        if (completed.compareAndSet(false, true)) {
+            latch.countDown();
+            return true;
+        }
+
+        return false;
+    }
+
+    @Override
+    public void await() throws InterruptedException {
+        latch.await();
     }
 
     @Override
-    public void onContextStop(CamelContext context) {
-        LOG.info("CamelContext: {} has been shutdown, triggering shutdown of 
the JVM.", context.getName());
-        // trigger stopping the Main
-        completed.set(true);
-        latch.countDown();
+    public void await(long timeout, TimeUnit unit) throws InterruptedException 
{
+        latch.await(timeout, unit);
     }
 }
diff --git a/core/camel-main/src/test/java/org/apache/camel/main/MainTest.java 
b/core/camel-main/src/test/java/org/apache/camel/main/MainTest.java
index a1e8431..f9dcf4d 100644
--- a/core/camel-main/src/test/java/org/apache/camel/main/MainTest.java
+++ b/core/camel-main/src/test/java/org/apache/camel/main/MainTest.java
@@ -55,10 +55,13 @@ public class MainTest extends Assert {
 
     @Test
     public void testDisableHangupSupport() throws Exception {
+        DefaultMainShutdownStrategy shutdownStrategy = new 
DefaultMainShutdownStrategy();
+        shutdownStrategy.disableHangupSupport();
+
         // lets make a simple route
         Main main = new Main();
+        main.setShutdownStrategy(shutdownStrategy);
         main.configure().addRoutesBuilder(new MyRouteBuilder());
-        main.disableHangupSupport();
         main.enableTrace();
         main.bind("foo", 31);
         main.start();
diff --git a/core/camel-main/src/test/resources/example.properties 
b/core/camel-main/src/test/resources/example.properties
new file mode 100644
index 0000000..73fe31c
--- /dev/null
+++ b/core/camel-main/src/test/resources/example.properties
@@ -0,0 +1,17 @@
+## ---------------------------------------------------------------------------
+## 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.
+## ---------------------------------------------------------------------------
+millisecs = 5000
\ No newline at end of file

Reply via email to