Created
March 25, 2011 10:51
-
-
Save mathieuancelin/886677 to your computer and use it in GitHub Desktop.
The custom SingletonProvider using the current class context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.jboss.weld.environment.osgi.integration; | |
import java.util.Hashtable; | |
import java.util.Map; | |
import org.jboss.weld.bean.proxy.ProxyMethodHandler; | |
import org.jboss.weld.bootstrap.api.Singleton; | |
import org.jboss.weld.bootstrap.api.SingletonProvider; | |
import org.osgi.framework.Bundle; | |
import org.osgi.framework.FrameworkUtil; | |
public class CurrentBundleSingletonProvider extends SingletonProvider { | |
@Override | |
public <T> Singleton<T> create(Class<? extends T> type) { | |
return new CurrentBundleSingleton<T>(); | |
} | |
private static class CurrentBundleSingleton<T> implements Singleton<T> { | |
private final Map<Long, T> store = new Hashtable<Long, T>(); | |
@Override | |
public T get() { | |
T instance = store.get(getBundleId()); | |
if (instance == null) { | |
throw new IllegalStateException("Singleton not set for bundle " + getBundleId()); | |
} | |
return instance; | |
} | |
@Override | |
public void set(T object) { | |
store.put(getBundleId(), object); | |
} | |
@Override | |
public void clear() { | |
store.remove(getBundleId()); | |
} | |
public boolean isSet() { | |
return store.containsKey(getBundleId()); | |
} | |
private Long getBundleId() { | |
Class<?> currentClass = ProxyMethodHandler.currentCaller.get(); | |
Bundle bundle = FrameworkUtil.getBundle(currentClass); | |
if (bundle != null) { | |
return bundle.getBundleId(); | |
} else { | |
throw new IllegalStateException("Can't find bundle for class " + currentClass.getName()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment