View Javadoc
1   /*
2    * Copyright (C) 2007-2012 Argeo GmbH
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *         http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.argeo.osgi.boot;
17  
18  import java.io.File;
19  
20  import org.osgi.framework.BundleContext;
21  import org.osgi.framework.launch.Framework;
22  
23  /** Monitors the runtime and can shut it down. */
24  public class AdminThread extends Thread {
25  	public final static String PROP_ARGEO_OSGI_SHUTDOWN_FILE = "argeo.osgi.shutdownFile";
26  	private File shutdownFile;
27  	private final BundleContext bundleContext;
28  
29  	public AdminThread(BundleContext bundleContext) {
30  		super("OSGi Boot Admin");
31  		this.bundleContext = bundleContext;
32  		if (System.getProperty(PROP_ARGEO_OSGI_SHUTDOWN_FILE) != null) {
33  			shutdownFile = new File(
34  					System.getProperty(PROP_ARGEO_OSGI_SHUTDOWN_FILE));
35  			if (!shutdownFile.exists()) {
36  				shutdownFile = null;
37  				OsgiBootUtils.warn("Shutdown file " + shutdownFile
38  						+ " not found, feature deactivated");
39  			}
40  		}
41  	}
42  
43  	public void run() {
44  		if (shutdownFile != null) {
45  			// wait for file to be removed
46  			while (shutdownFile.exists()) {
47  				try {
48  					Thread.sleep(1000);
49  				} catch (InterruptedException e) {
50  					e.printStackTrace();
51  				}
52  			}
53  
54  			Framework framework = (Framework) bundleContext.getBundle(0);
55  			try {
56  				// shutdown framework
57  				framework.stop();
58  				// wait 10 mins for shutdown
59  				framework.waitForStop(10 * 60 * 1000);
60  				// close VM
61  				System.exit(0);
62  			} catch (Exception e) {
63  				e.printStackTrace();
64  				System.exit(1);
65  			}
66  		}
67  	}
68  }