/*
 * Copyright 2011-2019 B2i Healthcare Pte Ltd, http://b2i.sg
 * 
 * Licensed 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 com.b2international.snowowl.server.product;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.slf4j.LoggerFactory;

import com.b2international.snowowl.core.SnowOwl;

/**
 * Server side Snow Owl product bootstraps and runs the entire headless server application.
 * 
 */
public class SnowOwlServerActivator implements BundleActivator {

	private static BundleContext bundleContext;
	private static SnowOwl snowowl;

	public static BundleContext getBundleContext() {
		return bundleContext;
	}
	
	public static SnowOwl getSnowOwl() {
		return snowowl;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
	 */
	@Override
	public void start(BundleContext context) throws Exception {
		try {
			SnowOwlServerActivator.bundleContext = context;
			snowowl = SnowOwl.create().bootstrap().run();
		} catch (Throwable e) {
			LoggerFactory.getLogger("snowowl").error(e.getMessage(), e);
			System.exit(-1);
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
	 */
	@Override
	public void stop(BundleContext context) throws Exception {
		snowowl.shutdown();
		SnowOwlServerActivator.bundleContext = null;
	}

}
@@ -758,16 +758,60 @@
 ontext;%0A
+import org.osgi.framework.launch.Framework;%0A
 import o
@@ -1569,16 +1569,601 @@
 .run();%0A
+%09%09%09Thread hook = new Thread() %7B%0A%09            @Override%0A%09            public void run() %7B%0A%09                try %7B%0A%09                    Framework systemBundle = context.getBundle(0).adapt(Framework.class);%0A%09                    systemBundle.stop();%0A%09                    systemBundle.waitForStop(60000);%0A%09                %7D catch (Exception e) %7B%0A%09                    System.err.println(%22Failed to cleanly shutdown OSGi Framework: %22 + e.getMessage());%0A%09                    e.printStackTrace();%0A%09                %7D%0A%09            %7D%0A%09        %7D;%0A%09        Runtime.getRuntime().addShutdownHook(hook);%0A
 %09%09%7D catc

add shutdown hook to gracefully shutdown Snow Owl