Add shutdown hook to launcher. (FELIX-1478)


git-svn-id: https://svn.apache.org/repos/asf/felix/trunk@808164 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/main/src/main/java/org/apache/felix/main/Main.java b/main/src/main/java/org/apache/felix/main/Main.java
index e557ee1..49568f4 100644
--- a/main/src/main/java/org/apache/felix/main/Main.java
+++ b/main/src/main/java/org/apache/felix/main/Main.java
@@ -44,6 +44,11 @@
     public static final String BUNDLE_DIR_SWITCH = "-b";
 
     /**
+     * The property name used to specify whether the launcher should
+     * install a shutdown hook.
+    **/
+    public static final String SHUTDOWN_HOOK_PROP = "felix.shutdown.hook";
+    /**
      * The property name used to specify an URL to the system
      * property file.
     **/
@@ -228,6 +233,30 @@
             configProps.setProperty(Constants.FRAMEWORK_STORAGE, cacheDir);
         }
 
+        // If enabled, register a shutdown hook to make sure the framework is
+        // cleanly shutdown when the VM exits.
+        String enableHook = configProps.getProperty(SHUTDOWN_HOOK_PROP);
+        if ((enableHook == null) || !enableHook.equalsIgnoreCase("false"))
+        {
+            Runtime.getRuntime().addShutdownHook(new Thread() {
+                public void run()
+                {
+                    try
+                    {
+                        if (m_fwk != null)
+                        {
+                            m_fwk.stop();
+                            m_fwk.waitForStop(0);
+                        }
+                    }
+                    catch (Exception ex)
+                    {
+                        System.err.println("Error stopping framework: " + ex);
+                    }
+                }
+            });
+        }
+
         // Print welcome banner.
         System.out.println("\nWelcome to Felix");
         System.out.println("================\n");
diff --git a/main/src/main/resources/config.properties b/main/src/main/resources/config.properties
index ab15acd..515e7c5 100644
--- a/main/src/main/resources/config.properties
+++ b/main/src/main/resources/config.properties
@@ -83,6 +83,10 @@
 # uncomment the following line to not install them.
 #felix.service.urlhandlers=false
 
+# The launcher registers a shutdown hook to cleanly stop the framework
+# by default, uncomment the following line to disable it.
+#felix.shutdown.hook=false
+
 #
 # Bundle config properties.
 #