blob: feca94f6c1c674cf6b32c32a9019656a3afd4310 [file] [log] [blame]
/*=============================================================================#
# Copyright (c) 2011, 2020 Stephan Wahlbrink and others.
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License 2.0 which is available at
# https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
# which is available at https://www.apache.org/licenses/LICENSE-2.0.
#
# SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
#
# Contributors:
# Stephan Wahlbrink <sw@wahlbrink.eu> - initial API and implementation
#=============================================================================*/
package org.eclipse.statet.ecommons.net.resourcemapping.core;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleListener;
import org.osgi.util.tracker.ServiceTracker;
import org.eclipse.core.runtime.Platform;
public class ResourceMappingUtils {
private static final String BUNDLE_ID= "org.eclipse.statet.ecommons.net.core"; //$NON-NLS-1$
private static class ManagerBundleListener implements BundleListener {
private final long bundleId;
public ManagerBundleListener(final Bundle bundle) {
this.bundleId= bundle.getBundleId();
}
@Override
public void bundleChanged(final BundleEvent event) {
if (event.getBundle().getBundleId() == this.bundleId
&& event.getType() == BundleEvent.STOPPED) {
final BundleContext context= event.getBundle().getBundleContext();
if (context != null) {
context.removeBundleListener(this);
}
synchronized (managerLock) {
if (managerTracker != null) {
managerTracker.close();
managerTracker= null;
}
}
}
}
}
private static final Object managerLock= new Object();
private static ServiceTracker<IResourceMappingManager, ?> managerTracker;
/**
* Returns the resource mapping manager service, if available
*
* @return the manager if available, otherwise <code>null</code>
*/
public static IResourceMappingManager getManager() {
synchronized (managerLock) {
if (managerTracker == null) {
final Bundle bundle= Platform.getBundle(BUNDLE_ID);
if (bundle.getState() != Bundle.ACTIVE) {
return null;
}
final BundleContext context= bundle.getBundleContext();
context.addBundleListener(new ManagerBundleListener(bundle));
managerTracker= new ServiceTracker<>(context,
IResourceMappingManager.class.getName(), null );
managerTracker.open();
}
return (IResourceMappingManager) managerTracker.getService();
}
}
private ResourceMappingUtils() {
}
}