package biz.netcentric.cq.tools.actool.installhook;

import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleReference;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.day.jcr.vault.fs.api.ProgressTrackerListener;
import com.day.jcr.vault.fs.io.ImportOptions;
import com.day.jcr.vault.packaging.InstallHook;

public abstract class OsgiAwareInstallHook implements InstallHook {

	private final BundleContext bundleContext;
	private static final Logger LOG = LoggerFactory.getLogger(OsgiAwareInstallHook.class);

	public OsgiAwareInstallHook() throws ClassCastException {
		// https://gist.github.com/tux2323/1314120
		bundleContext = BundleReference.class
				.cast(OsgiAwareInstallHook.class.getClassLoader()).getBundle()
				.getBundleContext();
	}

	public BundleContext getBundleContext() {
		return bundleContext;
	}

	public ServiceReference getServiceReference(String clazz) {
		ServiceReference serviceReference = bundleContext
				.getServiceReference(clazz);
		return serviceReference;
	}

	public void log (String message, ImportOptions options) {
		ProgressTrackerListener listener = options.getListener();
		if (listener != null) {
			listener.onMessage(ProgressTrackerListener.Mode.TEXT, message, "");
		} else {
			LOG.info(message);
		}
	}
}

@@ -46,16 +46,50 @@
 lhook;%0A%0A
+import org.osgi.framework.Bundle;%0A
 import o
@@ -121,16 +121,16 @@
 ontext;%0A
-
 import o
@@ -156,32 +156,73 @@
 undleReference;%0A
+import org.osgi.framework.FrameworkUtil;%0A
 import org.osgi.
@@ -729,142 +729,358 @@
 %09// 
-https://gist.github.com/tux2323/1314120%0A%09%09
+since this class was loaded through a bundle class loader as well, just take the 
 bundle
-C
+ c
 ontext
- = BundleReference.class%0A%09%09%09%09.cast(OsgiAwareInstallHook.class.getClassLoader())
+%0A%09%09Bundle currentBundle = FrameworkUtil.getBundle(this.getClass());%0A%09%09if (currentBundle == null) %7B%0A%09%09%09throw new IllegalStateException(%22The class %22 + this.getClass() + %22 was not loaded througha a bundle classloader%22);%0A%09%09%7D%0A%09%09%0A%09%09bundleContext = currentBundle
 .get
@@ -1089,35 +1089,149 @@
 ndle
+Context
 ()
+;
 %0A%09%09
-%09%09.getB
+if (bundleContext == null) %7B%0A%09%09%09throw new IllegalStateException(%22Could not get b
 undle
-C
+ c
 ontext
-();
+ for bundle %22 + currentBundle);%0A%09%09%7D
 %0A%09%7D%0A

use OSGi API to get bundle context