Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathieuancelin/886677 to your computer and use it in GitHub Desktop.
Save mathieuancelin/886677 to your computer and use it in GitHub Desktop.
The custom SingletonProvider using the current class context
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