]> git.argeo.org Git - lgpl/argeo-commons.git/blob - CmsShutdown.java
324462d39a67b1dd22318aff75780fe236423ea6
[lgpl/argeo-commons.git] / CmsShutdown.java
1 package org.argeo.cms.internal.osgi;
2
3 import org.argeo.api.cms.CmsLog;
4 import org.osgi.framework.Bundle;
5 import org.osgi.framework.FrameworkEvent;
6 import org.osgi.framework.FrameworkUtil;
7 import org.osgi.framework.launch.Framework;
8
9 /** Shutdowns the OSGi framework */
10 public class CmsShutdown extends Thread {
11 public final int EXIT_OK = 0;
12 public final int EXIT_ERROR = 1;
13 public final int EXIT_TIMEOUT = 2;
14 public final int EXIT_UNKNOWN = 3;
15
16 private final CmsLog log = CmsLog.getLog(CmsShutdown.class);
17 // private final BundleContext bc =
18 // FrameworkUtil.getBundle(CmsShutdown.class).getBundleContext();
19 private final Framework framework;
20
21 /** Shutdown timeout in ms */
22 private long timeout = 10 * 60 * 1000;
23
24 public CmsShutdown() {
25 super("CMS Shutdown Hook");
26 framework = FrameworkUtil.getBundle(CmsShutdown.class) != null
27 ? (Framework) FrameworkUtil.getBundle(CmsShutdown.class).getBundleContext().getBundle(0)
28 : null;
29 }
30
31 @Override
32 public void run() {
33 if (framework != null && framework.getState() != Bundle.ACTIVE) {
34 return;
35 }
36
37 if (log.isDebugEnabled())
38 log.debug("Shutting down OSGi framework...");
39 try {
40 if (framework != null) {
41 // shutdown framework
42 framework.stop();
43 // wait for shutdown
44 FrameworkEvent shutdownEvent = framework.waitForStop(timeout);
45 int stoppedType = shutdownEvent.getType();
46 Runtime runtime = Runtime.getRuntime();
47 if (stoppedType == FrameworkEvent.STOPPED) {
48 // close VM
49 // System.exit(EXIT_OK);
50 } else if (stoppedType == FrameworkEvent.ERROR) {
51 log.error("The OSGi framework stopped with an error");
52 runtime.halt(EXIT_ERROR);
53 } else if (stoppedType == FrameworkEvent.WAIT_TIMEDOUT) {
54 log.error("The OSGi framework hasn't stopped after " + timeout + "ms."
55 + " Forcibly terminating the JVM...");
56 runtime.halt(EXIT_TIMEOUT);
57 } else {
58 log.error("Unknown state of OSGi framework after " + timeout + "ms."
59 + " Forcibly terminating the JVM... (" + shutdownEvent + ")");
60 runtime.halt(EXIT_UNKNOWN);
61 }
62 }
63 } catch (Exception e) {
64 e.printStackTrace();
65 log.error("Unexpected exception " + e + " in shutdown hook. " + " Forcibly terminating the JVM...");
66 Runtime.getRuntime().halt(EXIT_UNKNOWN);
67 }
68 }
69
70 }