下面列出了org.osgi.framework.ServiceException#org.osgi.framework.FrameworkEvent 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public void log(FrameworkEvent fe) {
Level l = Level.FINE;
if ((fe.getType() & FrameworkEvent.ERROR) != 0) {
l = Level.SEVERE;
} else if ((fe.getType() & FrameworkEvent.WARNING) != 0) {
l = Level.WARNING;
} else if ((fe.getType() & FrameworkEvent.INFO) != 0) {
l = Level.INFO;
}
LogRecord lr = new LogRecord(l, "framework event {0} type {1}");
lr.setParameters(new Object[]{fe.getBundle().getSymbolicName(), fe.getType()});
lr.setThrown(fe.getThrowable());
lr.setLoggerName(NetbinoxFactory.LOG.getName());
NetbinoxFactory.LOG.log(lr);
}
/**
* notify all framework listeners.
*
* @param state the new state.
* @param bundle the bundle.
* @param throwable a throwable.
*/
static void notifyFrameworkListeners(final int state, final Bundle bundle, final Throwable throwable) {
if (frameworkListeners.isEmpty()) {
return;
}
final FrameworkEvent event = new FrameworkEvent(state);
final FrameworkListener[] listeners = frameworkListeners.toArray(new FrameworkListener[frameworkListeners.size()]);
for (int i = 0; i < listeners.length; i++) {
final FrameworkListener listener = listeners[i];
listener.frameworkEvent(event);
}
}
private static void refreshBundles(Set<Bundle> toRefresh, FrameworkWiring frameworkWiring) {
if (!toRefresh.isEmpty()) {
JavaLanguageServerPlugin.logInfo("Refresh the bundles");
final CountDownLatch latch = new CountDownLatch(1);
frameworkWiring.refreshBundles(toRefresh, new FrameworkListener() {
@Override
public void frameworkEvent(FrameworkEvent event) {
if (event.getType() == FrameworkEvent.PACKAGES_REFRESHED) {
latch.countDown();
} else if (event.getType() == FrameworkEvent.ERROR) {
JavaLanguageServerPlugin.logException("Error happens when refreshing the bundles", event.getThrowable());
latch.countDown();
}
}
});
try {
latch.await();
} catch (InterruptedException e) {
JavaLanguageServerPlugin.logException("InterruptedException happened when refreshing", e);
}
JavaLanguageServerPlugin.logInfo("Finished Refreshing bundles");
}
}
/**
* NOTE: This method is no longer used by the Jdisc container framework, but kept for completeness.
*/
@Override
public void refreshPackages() {
FrameworkWiring wiring = felix.adapt(FrameworkWiring.class);
final CountDownLatch latch = new CountDownLatch(1);
wiring.refreshBundles(null,
event -> {
switch (event.getType()) {
case FrameworkEvent.PACKAGES_REFRESHED:
latch.countDown();
break;
case FrameworkEvent.ERROR:
log.log(Level.SEVERE, "ERROR FrameworkEvent received.", event.getThrowable());
break;
}
});
try {
long TIMEOUT_SECONDS = 60L;
if (!latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
log.warning("No PACKAGES_REFRESHED FrameworkEvent received within " + TIMEOUT_SECONDS +
" seconds of calling FrameworkWiring.refreshBundles()");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/**
* receive a <code>FrameworkEvent</code>.
*
* @param fEvent
* the framework event.
* @see org.osgi.framework.FrameworkListener#frameworkEvent(org.osgi.framework.FrameworkEvent)
*/
public void frameworkEvent(final FrameworkEvent fEvent) {
Dictionary props = new Hashtable();
props.put(EventConstants.EVENT, fEvent);
props.put(EventConstants.TIMESTAMP,
new Long(System.currentTimeMillis()));
final Bundle bundle;
if ((bundle = fEvent.getBundle()) != null) {
props.put("bundle.id", new Long(bundle.getBundleId()));
props.put(EventConstants.BUNDLE_SYMBOLICNAME, "null");
props.put("bundle", bundle);
}
final Throwable throwable;
if ((throwable = fEvent.getThrowable()) != null) {
props.put(EventConstants.EXECPTION_CLASS, throwable.getClass()
.getName());
props.put(EventConstants.EXCEPTION_MESSAGE, throwable.getMessage());
props.put(EventConstants.EXCEPTION, throwable);
}
int t = log2(fEvent.getType());
String type = t < 5 ? FRAMEWORK_EVENT[t] : "UNDEFINED";
Event event = new Event("org/osgi/framework/FrameworkEvent/" + type,
props);
postEvent(event);
}
/**
* @see org.osgi.framework.Bundle#loadClass(java.lang.String)
* @category Bundle
*/
public Class<?> loadClass(final String name) throws ClassNotFoundException {
if (state == Bundle.UNINSTALLED) {
throw new IllegalStateException("Bundle is uninstalled");
}
// is this actually a fragment?
if (currentRevision.isFragment()) {
throw new ClassNotFoundException(
"This bundle is a fragment and cannot load any classes.");
}
if (state == Bundle.INSTALLED) {
try {
currentRevision.resolve(true);
} catch (final BundleException be) {
framework.notifyFrameworkListeners(FrameworkEvent.ERROR, this,
be);
throw new ClassNotFoundException(name, be);
}
}
return currentRevision.classloader.findClass(name);
}
/**
* notify all framework listeners.
*
* @param state
* the new state.
* @param bundle
* the bundle.
* @param throwable
* a throwable.
*/
protected void notifyFrameworkListeners(final FrameworkListener[] listeners,
final int state, final Bundle bundle, final Throwable throwable) {
if (listeners.length == 0) {
return;
}
final FrameworkEvent event = new FrameworkEvent(state, bundle,
throwable);
for (int i = 0; i < listeners.length; i++) {
final FrameworkListener listener = listeners[i];
if (SECURITY_ENABLED) {
AccessController.doPrivileged(new PrivilegedAction<Object>() {
public Object run() {
listener.frameworkEvent(event);
return null;
}
});
} else {
listener.frameworkEvent(event);
}
}
}
/**
* Wait until this Framework has completely stopped.
*
* @param framework OSGi framework
* @throws java.lang.Exception
*/
private void waitForServerStop(Framework framework) throws Exception {
if (!isFrameworkActive()) {
return;
}
while (true) {
FrameworkEvent event = framework.waitForStop(0);
// We should not stop the framework if the user has updated the system bundle via the OSGi console or
// programmatically. In this case, framework will shutdown and start itself.
if (event.getType() != FrameworkEvent.STOPPED_UPDATE) {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "OSGi framework is stopped for update.");
}
break;
}
}
}
@Override
public synchronized void frameworkEvent(FrameworkEvent fe) {
if (fe.getType() == FrameworkEvent.STARTLEVEL_CHANGED) {
levelChanged = true;
notifyAll();
}
}
public @Override void start(final BundleContext context) throws Exception {
if (System.getProperty("netbeans.home") != null) {
throw new IllegalStateException("Should not be run from inside regular NetBeans module system");
}
String storage = context.getProperty(Constants.FRAMEWORK_STORAGE);
if (storage != null) {
System.setProperty("netbeans.user", storage);
}
System.setProperty("TopSecurityManager.disable", "true");
NbBundle.setBranding(System.getProperty("branding.token"));
OSGiMainLookup.initialize(context);
queue = new DependencyQueue<String,Bundle>();
this.context = context;
framework = ((Framework) context.getBundle(0));
if (framework.getState() == Bundle.STARTING) {
LOG.fine("framework still starting");
final AtomicReference<FrameworkListener> frameworkListener = new AtomicReference<FrameworkListener>();
frameworkListener.set(new FrameworkListener() {
public @Override void frameworkEvent(FrameworkEvent event) {
if (event.getType() == FrameworkEvent.STARTED) {
// System.err.println("framework started");
context.removeFrameworkListener(frameworkListener.get());
context.addBundleListener(Activator.this);
processLoadedBundles();
}
}
});
context.addFrameworkListener(frameworkListener.get());
} else {
LOG.fine("framework already started");
context.addBundleListener(this);
processLoadedBundles();
}
}
private static BundleFile createBundleFile(Object content, BaseData sourcedata) {
try {
return sourcedata.getAdaptor().createBundleFile(content, sourcedata);
} catch (IOException e) {
sourcedata.getAdaptor().getEventPublisher().publishFrameworkEvent(FrameworkEvent.ERROR, sourcedata.getBundle(), e);
}
return null;
}
@Override
public void frameworkEvent(FrameworkEvent event) {
switch (event.getType()) {
case 0:/* STARTING */
starting();
break;
case FrameworkEvent.STARTED:
started();
break;
case FrameworkEvent.STARTLEVEL_CHANGED:
case FrameworkEvent.PACKAGES_REFRESHED:
case FrameworkEvent.ERROR:
}
}
S factorService(final Bundle theBundle, boolean count){
@SuppressWarnings("unchecked")
final ServiceFactory<S> factory = (ServiceFactory<S>) service;
final S factoredService;
try {
if(count)
incrementCounter(theBundle);
marker = true;
factoredService = factory.getService(theBundle,
registration);
marker = false;
checkService(factoredService,
(String[]) properties.get(Constants.OBJECTCLASS));
// catch failed check and exceptions thrown in factory
} catch (final IllegalArgumentException iae) {
if(count)
decrementCounter(theBundle);
framework.notifyFrameworkListeners(FrameworkEvent.ERROR,
bundle, new ServiceException(
"Invalid service object",
ServiceException.FACTORY_ERROR));
return null;
} catch (final Throwable t) {
if(count)
decrementCounter(theBundle);
framework.notifyFrameworkListeners(FrameworkEvent.ERROR,
bundle, new ServiceException(
"Exception while factoring the service",
ServiceException.FACTORY_EXCEPTION, t));
return null;
}
return factoredService;
}
public void ungetService(S s) {
if(isPrototype){
if(services.remove(s)) {
try {
final ServiceFactory<S> factory = (ServiceFactory<S>) service;
factory.ungetService(b, (ServiceRegistration<S>) registration, s);
} catch (final Throwable t) {
framework.notifyFrameworkListeners(
FrameworkEvent.ERROR, b, t);
}
if(services.size() == 0){
if(useCounters.get(b) == 0){
useCounters.remove(b);
}
}
} else {
throw new IllegalArgumentException("Service object was not provided "
+ "by this ServiceObjects instance");
}
} else {
// in case of bundle scope, only unget if this is from the right bundle
if(isServiceFactory) {
if(s != cachedServices.get(b)){
throw new IllegalArgumentException("Service object was not provided "
+ "by this ServiceObjects instance");
}
}
ServiceReferenceImpl.this.ungetService(b);
}
}
/**
* @see org.osgi.framework.startlevel.FrameworkStartLevel#setStartLevel(int,
* org.osgi.framework.FrameworkListener[])
* @category FrameworkStartLevel
*/
public void setStartLevel(final int targetLevel,
final FrameworkListener... listeners) {
// TODO: check AdminPermission(this, STARTLEVEL);
// cannot set the startlevel during init - required for extension bundle activators
if(state == STARTING){
throw new IllegalStateException("Cannot set the start level while starting");
}
if (targetLevel <= 0) {
throw new IllegalArgumentException(
"Start level " + targetLevel + " is not a valid level");
}
new Thread() {
public void run() {
setLevel(bundles.toArray(new Bundle[bundles.size()]),
targetLevel, false);
notifyFrameworkListeners(FrameworkEvent.STARTLEVEL_CHANGED,
Concierge.this, null);
if (listeners != null) {
notifyFrameworkListeners(listeners,
FrameworkEvent.STARTLEVEL_CHANGED, Concierge.this,
null);
}
storeMetadata();
}
}.start();
}
private void informListenerHooks(
final Collection<ServiceReferenceImpl<ListenerHook>> hooks,
final ServiceListenerEntry[] entries, final boolean added) {
if (hooks == null || hooks.isEmpty()) {
return;
}
if (!added) {
for (final ServiceListenerEntry entry : entries) {
entry.removed = true;
}
}
final Collection<ListenerInfo> c = new ConciergeCollections.RemoveOnlyList<ListenerInfo>(
Arrays.asList(entries));
for (final Iterator<ServiceReferenceImpl<ListenerHook>> iter = hooks
.iterator(); iter.hasNext();) {
final ServiceReferenceImpl<ListenerHook> hookRef = iter.next();
final ListenerHook hook = getService(hookRef);
try {
if (added) {
hook.added(c);
} else {
hook.removed(c);
}
} catch (final Throwable t) {
notifyFrameworkListeners(FrameworkEvent.ERROR,
Concierge.this, t);
}
ungetService(hookRef);
}
}
private boolean checkHook(final String clazz,
final ServiceReference<?> sref, final boolean add) {
@SuppressWarnings("unchecked")
final List<ServiceReference<?>> hookList = (List<ServiceReference<?>>) hooks
.get(clazz);
if (hookList == null) {
return false;
}
if (add) {
hookList.add(sref);
// not required for collision hook, weaving hook,
// resolverHookFactory...
Collections.sort(hookList, Collections.reverseOrder());
} else {
// FIXME: remove!
}
// special case: ListenerHook
if (add && (Object) hookList == (Object) serviceListenerHooks) {
@SuppressWarnings("unchecked")
final ServiceReferenceImpl<ListenerHook> hookRef = (ServiceReferenceImpl<ListenerHook>) sref;
if (serviceListeners != null) {
try {
informListenerHooks(Collections.singletonList(hookRef),
serviceListeners.toArray(
new ServiceListenerEntry[serviceListeners
.size()]),
true);
} catch (final Throwable t) {
notifyFrameworkListeners(FrameworkEvent.ERROR,
sref.getBundle(), t);
}
}
}
return true;
}
void callWeavingHooks(final WovenClassImpl wovenClass) {
Collections.sort(weavingHooks, Collections.reverseOrder());
final List<ServiceReferenceImpl<WeavingHook>> wHooks = new ArrayList<ServiceReferenceImpl<WeavingHook>>();
wHooks.addAll(weavingHooks);
for (final ServiceReferenceImpl<WeavingHook> sref : wHooks) {
final WeavingHook hook = sref.getService(this);
try {
hook.weave(wovenClass);
} catch (final Throwable t) {
if (!(t instanceof WeavingException)) {
// blacklist the hook
weavingHooks.remove(sref);
}
// framework event
notifyFrameworkListeners(FrameworkEvent.ERROR, sref.bundle, t);
// mark as complete
wovenClass.setTransformingFailed();
notifyWovenClassListeners(wovenClass);
final ClassFormatError err = new ClassFormatError(
"Error while invoking weaving hook");
err.initCause(t);
throw err;
} finally {
sref.ungetService(this);
}
}
wovenClass.setTransformed();
notifyWovenClassListeners(wovenClass);
}
public void stopFramework() throws Exception {
// it may happen that framework has not been set
if (this.framework != null) {
if (stayInShell()) {
this.framework.waitForStop(0);
} else {
this.framework.stop();
FrameworkEvent event = framework.waitForStop(10000);
Assert.assertThat(FrameworkEvent.STOPPED, is(event.getType()));
// force a GC to allow cleanup of files
// on Mac from time to time files from storage can not be
// deleted
// until a GC has been run
System.gc();
// We have from time to time problems when shutdown the
// framework, that next tests are failing
// for CI build we can define a timeout to wait here. A good
// value is 100ms
String propValue = System
.getProperty(PROPERTY_WAIT_AFTER_FRAMEWORK_SHUTDOWN);
// we use a default timeout of 100 ms now
int timeout = -1;
if ((propValue != null) && (propValue.length() > 0)) {
try {
timeout = Integer.valueOf(propValue);
} catch (NumberFormatException ex) {
// ignore
}
}
if (timeout > 0) {
Thread.sleep(timeout);
}
}
}
}
public void frameworkEvent(FrameworkEvent e)
{
try {
if (e.getType() == FrameworkEvent.STARTED) {
activate();
}
} catch (final Exception e1) {
}
}
/**
* The framework event callback method inserts all framework events into
* the log. Events of type <code>error</code> are logged at the error
* level other event types are logged on the info level.
* <p/>
* FrameworkListener callback.
*
* @param fe
* the framework event that has occurred.
*/
public void frameworkEvent(FrameworkEvent fe) {
int level = LogService.LOG_INFO;
String msg = null;
// We always include the Exception even though
// the specification says differently
Throwable thr = fe.getThrowable();
switch (fe.getType()) {
case FrameworkEvent.ERROR:
msg = "FrameworkEvent ERROR";
level = LogService.LOG_ERROR;
break;
case FrameworkEvent.STARTED:
msg = "FrameworkEvent STARTED";
level = LogService.LOG_INFO;
break;
case FrameworkEvent.STARTLEVEL_CHANGED:
msg = "FrameworkEvent STARTLEVEL_CHANGED";
level = LogService.LOG_INFO;
break;
case FrameworkEvent.PACKAGES_REFRESHED:
msg = "FrameworkEvent PACKAGES_REFRESHED";
level = LogService.LOG_INFO;
break;
case FrameworkEvent.WARNING:
msg = "FrameworkEvent WARNING";
level = LogService.LOG_INFO; // sic! According to spec.
break;
case FrameworkEvent.INFO:
msg = "FrameworkEvent INFO";
level = LogService.LOG_INFO;
break;
default:
msg = "FrameworkEvent <" + fe.getType() + ">";
level = LogService.LOG_WARNING;
break;
}
lrsf.log(new LogEntryImpl(fe.getBundle(), level, msg, thr));
}
void refreshBundles(final Bundle[] b)
{
final Bundle systemBundle = Activator.getTargetBC().getBundle(0);
final FrameworkWiring fw = systemBundle.adapt(FrameworkWiring.class);
if (fw != null) {
final ArrayList<Bundle> bundles = new ArrayList<Bundle>();
final boolean refreshAll = b == null || 0 == b.length;
final StringBuffer sb = new StringBuffer("Desktop-RefreshPackages ");
if (refreshAll) {
sb.append("all packages pending removal");
} else {
sb.append("bundle packages for ");
for (int i = 0; i < b.length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(b[i].getBundleId());
bundles.add(b[i]);
}
}
final FrameworkListener refreshListener = new FrameworkListener() {
@Override
public void frameworkEvent(FrameworkEvent event)
{
Activator.log.info(sb.toString() + " DONE.");
}
};
try {
fw.refreshBundles(bundles, refreshListener);
} catch (final Exception e) {
showErr(sb.toString() + " failed to refresh bundles: " + e, e);
}
}
}
@Override
public void frameworkEvent(FrameworkEvent ev)
{
if (!alive) {
return;
}
switch (ev.getType()) {
case FrameworkEvent.STARTLEVEL_CHANGED:
updateStartLevel();
break;
}
}
public void runTest() throws Throwable {
fw = bc.getBundle(0).adapt(FrameworkWiring.class);
FrameworkListener fl = new FrameworkListener() {
@Override
public void frameworkEvent(FrameworkEvent event) {
synchronized (this) {
notifyAll();
}
}
};
try {
synchronized (fl) {
fw.refreshBundles(null, fl);
fl.wait(3000);
}
buCUC1 = Util.installBundle(bc, "bundleCUC1_test-1.0.0.jar");
assertNotNull(buCUC1);
buCUC2 = Util.installBundle(bc, "bundleCUC2_test-2.0.0.jar");
assertNotNull(buCUC2);
buCUP1 = Util.installBundle(bc, "bundleCUP1_test-1.0.0.jar");
assertNotNull(buCUP1);
buCUP2 = Util.installBundle(bc, "bundleCUP2_test-2.0.0.jar");
assertNotNull(buCUP2);
} catch (Exception e) {
fail("Failed to refresh packages: " + e);
}
}
/**
* Shutting down is done.
*/
void systemShuttingdownDone(final FrameworkEvent fe) {
synchronized (lock) {
if (state != INSTALLED) {
state = RESOLVED;
operation = IDLE;
lock.notifyAll();
}
stopEvent = fe;
}
}
/**
* This method start a thread that stop this Framework, stopping all started
* bundles.
*
* <p>
* If the framework is not started, this method does nothing. If the framework
* is started, this method will:
* <ol>
* <li>Set the state of the FrameworkContext to <i>inactive</i>.</li>
* <li>Suspended all started bundles as described in the
* {@link Bundle#stop(int)} method except that the persistent state of the
* bundle will continue to be started. Reports any exceptions that occur
* during stopping using <code>FrameworkErrorEvents</code>.</li>
* <li>Disable event handling.</li>
* </ol>
* </p>
*
*/
void shutdown(final boolean restart) {
synchronized (lock) {
boolean wasActive = false;
switch (state) {
case Bundle.INSTALLED:
case Bundle.RESOLVED:
shutdownDone(false);
break;
case Bundle.ACTIVE:
wasActive = true;
// Fall through
case Bundle.STARTING:
if (shutdownThread == null) {
try {
final boolean wa = wasActive;
shutdownThread = new Thread(fwCtx.threadGroup, "Framework shutdown") {
@Override
public void run() {
shutdown0(restart, wa);
}
};
shutdownThread.setDaemon(false);
shutdownThread.start();
} catch (final Exception e) {
systemShuttingdownDone(new FrameworkEvent(FrameworkEvent.ERROR, this, e));
}
}
break;
case Bundle.STOPPING:
// Shutdown already inprogress
break;
}
}
}
/**
* Stop this FrameworkContext, suspending all started contexts. This method
* suspends all started contexts so that they can be automatically restarted
* when this FrameworkContext is next launched.
*
* <p>
* If the framework is not started, this method does nothing. If the framework
* is started, this method will:
* <ol>
* <li>Set the state of the FrameworkContext to <i>inactive</i>.</li>
* <li>Stop all started bundles as described in the {@link Bundle#stop(int)}
* method except that the persistent state of the bundle will continue to be
* started. Reports any exceptions that occur during stopping using
* <code>FrameworkErrorEvents</code>.</li>
* <li>Disable event handling.</li>
* </ol>
* </p>
*
*/
private void shutdown0(final boolean restart, final boolean wasActive) {
try {
synchronized (lock) {
waitOnOperation(lock, "Framework." + (restart ? "update" : "stop"), true);
operation = DEACTIVATING;
state = STOPPING;
}
fwCtx.listeners.bundleChanged(new BundleEvent(BundleEvent.STOPPING, this));
if (wasActive) {
stopAllBundles();
saveClasspaths();
}
extensionCallStop();
synchronized (lock) {
fwCtx.uninit();
shutdownThread = null;
shutdownDone(restart);
}
if (restart) {
if (wasActive) {
start();
} else {
init();
}
}
} catch (final Exception e) {
shutdownThread = null;
systemShuttingdownDone(new FrameworkEvent(FrameworkEvent.ERROR, this, e));
}
}
/**
* Tell system bundle shutdown finished.
*/
private void shutdownDone(boolean restart) {
int t;
if (bootClassPathHasChanged) {
t = FrameworkEvent.STOPPED_BOOTCLASSPATH_MODIFIED;
} else {
t = restart ? FrameworkEvent.STOPPED_UPDATE : FrameworkEvent.STOPPED;
}
systemShuttingdownDone(new FrameworkEvent(t, this, null));
}
/**
*
*/
private void frameworkEvent(final ListenerEntry le, FrameworkEvent evt) {
try {
((FrameworkListener)le.listener).frameworkEvent(evt);
} catch (final Exception pe) {
// Don't report Error events again, since probably would go into an infinite loop.
if (evt.getType() != FrameworkEvent.ERROR) {
fwCtx.frameworkError(le != null ? le.bc : null, pe);
}
}
}
public void frameworkEvent(FrameworkEvent event)
{
if (FrameworkEvent.PACKAGES_REFRESHED == event.getType()) {
log("refresh bundles completed");
refreshRunning = false;
// We need to run another refresh bundles here to handle updates during
// the previous refresh.
refreshUpdatedBundles();
}
}