下面列出了java.net.ContentHandler#org.osgi.framework.ServiceReference 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Bind(aggregate = true, optional = true, filter = "(protocol=bluetooth)")
public void bindBluetoothProxyFactories(Factory f, ServiceReference<Factory> sr) {
LOG.warn("Found one factory : " + f.getName());
String friendlyName = (String) sr.getProperty("device_name");
if (friendlyName == null) {
return;
}
bluetoothProxiesFactories.put(friendlyName, f);
Map.Entry<String, ImportDeclaration> unresolvedImportDeclaration;
ImportDeclaration iDec = null;
String fn = null;
Iterator<Map.Entry<String, ImportDeclaration>> iterator = unresolvedImportDeclarations.entrySet().iterator();
while (iterator.hasNext()) {
unresolvedImportDeclaration = iterator.next();
fn = unresolvedImportDeclaration.getKey();
if (fn.startsWith(friendlyName)) {
iDec = unresolvedImportDeclaration.getValue();
ComponentInstance proxy = createProxy(iDec, f);
iDec.handle(this.serviceReference);
iterator.remove();
resolvedImportDeclarations.put(fn, iDec);
proxyComponentInstances.put(iDec, proxy);
}
}
}
public static String getRelativeUrl() {
BundleContext context = CarbonUIUtil.getBundleContext();
ServiceReference reference =
context.getServiceReference(RegistryService.class.getName());
RegistryService registryService = (RegistryService) context.getService(reference);
String url = null;
try {
Registry systemRegistry = registryService.getConfigSystemRegistry();
Resource resource = systemRegistry.get(RegistryResources.CONNECTION_PROPS);
String servicePath = resource.getProperty("service-path");
String contextRoot = resource.getProperty("context-root");
contextRoot = contextRoot.equals("/") ? "" : contextRoot;
url = contextRoot + servicePath + "/WSDL2CodeService";
} catch (Exception e) {
log.error(e);
}
return url;
}
public List<Bus> getBusses() {
List<Bus> busses = new ArrayList<>();
try {
Collection<ServiceReference<Bus>> references = bundleContext.getServiceReferences(Bus.class, null);
if (references != null) {
for (ServiceReference<Bus> reference : references) {
if (reference != null) {
Bus bus = bundleContext.getService(reference);
if (bus != null) {
busses.add(bus);
}
}
}
}
} catch (Exception e) {
LOG.log(Level.INFO, "Cannot retrieve the list of CXF Busses.", e);
}
return busses;
}
public FileManager getFileManager() {
if (fileManager == null) {
// Get all Services implement FileManager interface
try {
ServiceReference<?>[] references = this.context
.getAllServiceReferences(FileManager.class.getName(),
null);
for (ServiceReference<?> ref : references) {
return (FileManager) this.context.getService(ref);
}
return null;
}
catch (InvalidSyntaxException e) {
LOGGER.warning("Cannot load FileManager on JpaGeoOperationsImpl.");
return null;
}
}
else {
return fileManager;
}
}
public GeoOperations getGeoOperations() {
if (operations == null) {
// Get all Services implement GeoOperations interface
try {
ServiceReference[] references = context
.getAllServiceReferences(GeoOperations.class.getName(),
null);
for (ServiceReference ref : references) {
operations = (GeoOperations) context.getService(ref);
return operations;
}
return null;
}
catch (InvalidSyntaxException e) {
LOGGER.warning("Cannot load GeoOperations on DependencyListenerImpl.");
return null;
}
}
else {
return operations;
}
}
@Test
public void testRegistryServiceDynamicLoadOfComponent() throws BundleException, MalformedURLException, URISyntaxException {
// inside eclipse the bundle context can be retrieved from the Activator.start method or using the FrameworkUtil
// class.
BundleContext bundleContext = FrameworkUtil.getBundle(getClass()).getBundleContext();
ServiceReference<DefinitionRegistryService> compServiceRef = bundleContext
.getServiceReference(DefinitionRegistryService.class);
if (compServiceRef != null) {
DefinitionRegistryService defService = bundleContext.getService(compServiceRef);
assertNotNull(defService);
assertEquals(0, defService.getDefinitionsMapByType(Definition.class).size());
installNewComponentBundle(bundleContext);
assertEquals(1, defService.getDefinitionsMapByType(Definition.class).size());
} else {
fail("Failed to retrieve the Component service");
}
}
@Override
public <T> T create(Class<T> serviceType, Supplier<T> supplier) {
LOG.finest("TAMAYA Creating service: " + serviceType.getName());
ServiceReference<T> ref = this.osgiServiceLoader.getBundleContext().getServiceReference(serviceType);
if(ref!=null){
try {
return (T)this.osgiServiceLoader.getBundleContext().getService(ref).getClass().getConstructor()
.newInstance();
} catch (Exception e) {
if(supplier!=null){
return supplier.get();
}
return null;
}
}
if(supplier!=null){
return supplier.get();
}
return null;
}
@Override
public void start ( final BundleContext context ) throws Exception
{
this.scheduler = Executors.newSingleThreadScheduledExecutor ( new NamedThreadFactory ( context.getBundle ().getSymbolicName () ) );
final String driver = DataSourceHelper.getDriver ( DS_PREFIX, DataSourceHelper.DEFAULT_PREFIX );
if ( driver == null )
{
logger.error ( "JDBC driver is not set" );
throw new IllegalStateException ( "JDBC driver name is not set" );
}
this.dataSourceFactoryTracker = new DataSourceFactoryTracker ( context, driver, new SingleServiceListener<DataSourceFactory> () {
@Override
public void serviceChange ( final ServiceReference<DataSourceFactory> reference, final DataSourceFactory service )
{
unregister ();
if ( service != null )
{
register ( service, context );
}
}
} );
this.dataSourceFactoryTracker.open ( true );
}
@Test
void shouldLoadAValidPluginWithMultipleExtensions_ImplementingDifferentExtensions() throws Exception {
final GoPluginBundleDescriptor bundleDescriptor = new GoPluginBundleDescriptor(getPluginDescriptor("valid-plugin-with-multiple-extensions", validMultipleExtensionPluginBundleDir));
registry.loadPlugin(bundleDescriptor);
Bundle bundle = pluginOSGiFramework.loadPlugin(bundleDescriptor);
assertThat(bundle.getState()).isEqualTo(Bundle.ACTIVE);
BundleContext context = bundle.getBundleContext();
String taskExtensionFilter = String.format("(&(%s=%s)(%s=%s))", "PLUGIN_ID", "valid-plugin-with-multiple-extensions", Constants.BUNDLE_CATEGORY, "task");
String analyticsExtensionFilter = String.format("(&(%s=%s)(%s=%s))", "PLUGIN_ID", "valid-plugin-with-multiple-extensions", Constants.BUNDLE_CATEGORY, "analytics");
ServiceReference<?>[] taskExtensionServiceReferences = context.getServiceReferences(GoPlugin.class.getCanonicalName(), taskExtensionFilter);
assertThat(taskExtensionServiceReferences.length).isEqualTo(1);
assertThat(((GoPlugin) context.getService(taskExtensionServiceReferences[0])).pluginIdentifier().getExtension()).isEqualTo("task");
ServiceReference<?>[] analyticsExtensionServiceReferences = context.getServiceReferences(GoPlugin.class.getCanonicalName(), analyticsExtensionFilter);
assertThat(analyticsExtensionServiceReferences.length).isEqualTo(1);
assertThat(((GoPlugin) context.getService(analyticsExtensionServiceReferences[0])).pluginIdentifier().getExtension()).isEqualTo("analytics");
}
public ProjectOperations getProjectOperations() {
if (projectOperations == null) {
// Get all Services implement WebMetadataService interface
try {
ServiceReference<?>[] references = this.context
.getAllServiceReferences(
ProjectOperations.class.getName(), null);
for (ServiceReference<?> ref : references) {
return (ProjectOperations) this.context.getService(ref);
}
return null;
}
catch (InvalidSyntaxException e) {
LOGGER.warning("Cannot load ProjectOperations on DatatablesOperationsImpl.");
return null;
}
}
else {
return projectOperations;
}
}
/**
* Returns the reference to the implementation of the specified service.
*
* @param serviceClass service class
* @param <T> type of service
* @return service implementation
*/
public static <T> T getService(Class<T> serviceClass) {
Bundle bundle = FrameworkUtil.getBundle(serviceClass);
if (bundle != null) {
BundleContext bc = bundle.getBundleContext();
if (bc != null) {
ServiceReference<T> reference = bc.getServiceReference(serviceClass);
if (reference != null) {
T impl = bc.getService(reference);
if (impl != null) {
return impl;
}
}
}
}
throw new ServiceNotFoundException("Service " + serviceClass.getName() + " not found");
}
public TypeLocationService getTypeLocationService() {
if (typeLocationService == null) {
// Get all Services implement TypeLocationService interface
try {
ServiceReference<?>[] references = this.context
.getAllServiceReferences(
TypeLocationService.class.getName(), null);
for (ServiceReference<?> ref : references) {
return (TypeLocationService) this.context.getService(ref);
}
return null;
}
catch (InvalidSyntaxException e) {
LOGGER.warning("Cannot load TypeLocationService on JQueryOperationsImpl.");
return null;
}
}
else {
return typeLocationService;
}
}
public CommandProcessor addingService(ServiceReference<CommandProcessor> reference)
{
final CommandProcessor cmdProcessor = bc.getService(reference);
try {
closeSession();
commandSession = cmdProcessor.createSession(inStream,
outStream,
errStream);
readThread = new ReadThread(inStream, commandSession);
readThread.start();
} catch (Exception ioe) {
log(LogService.LOG_ERROR,
"Failed to start command session, can not continue");
}
return cmdProcessor;
}
synchronized void open() {
if(fwCtx.debug.hooks) {
fwCtx.debug.println("opening hooks");
}
listenerHookTracker = new ServiceTracker<ListenerHook,ListenerHook>
(fwCtx.systemBundle.bundleContext,
ListenerHook.class,
new ServiceTrackerCustomizer<ListenerHook,ListenerHook>() {
public ListenerHook addingService(ServiceReference<ListenerHook> reference) {
final ListenerHook lh = fwCtx.systemBundle.bundleContext.getService(reference);
try {
Collection<ServiceListenerEntry> c = getServiceCollection();
@SuppressWarnings({ "rawtypes", "unchecked" })
final Collection<ListenerInfo> li = (Collection) c;
lh.added(li);
} catch (final Exception e) {
fwCtx.debug.printStackTrace("Failed to call listener hook #" +
reference.getProperty(Constants.SERVICE_ID), e);
}
return lh;
}
public void modifiedService(ServiceReference<ListenerHook> reference, ListenerHook service) {
// noop
}
public void removedService(ServiceReference<ListenerHook> reference, ListenerHook service) {
fwCtx.systemBundle.bundleContext.ungetService(reference);
}
});
listenerHookTracker.open();
bOpen = true;
}
/**
* Create user groups for authors and testers.
*
* @param bundleContext The bundle context provided by the component.
*/
private void createGroups(BundleContext bundleContext){
ServiceReference SlingRepositoryFactoryReference = bundleContext.getServiceReference(SlingRepository.class.getName());
SlingRepository repository = (SlingRepository)bundleContext.getService(SlingRepositoryFactoryReference);
Session session = null;
if (repository != null) {
try {
session = repository.loginAdministrative(null);
if (session != null && session instanceof JackrabbitSession) {
UserManager userManager = ((JackrabbitSession)session).getUserManager();
ValueFactory valueFactory = session.getValueFactory();
Authorizable authors = userManager.getAuthorizable(PublickConstants.GROUP_ID_AUTHORS);
if (authors == null) {
authors = userManager.createGroup(PublickConstants.GROUP_ID_AUTHORS);
authors.setProperty(GROUP_DISPLAY_NAME, valueFactory.createValue(PublickConstants.GROUP_DISPLAY_AUTHORS));
}
Authorizable testers = userManager.getAuthorizable(PublickConstants.GROUP_ID_TESTERS);
if (testers == null) {
testers = userManager.createGroup(PublickConstants.GROUP_ID_TESTERS);
testers.setProperty(GROUP_DISPLAY_NAME, valueFactory.createValue(PublickConstants.GROUP_DISPLAY_TESTERS));
}
}
} catch (RepositoryException e) {
LOGGER.error("Could not get session", e);
} finally {
if (session != null && session.isLive()) {
session.logout();
session = null;
}
}
}
}
/**
* Test of compare method, of class OSGIServiceComparator.
*/
@Test
public void testCompare() {
ServiceReference low = new MockLowPriorityServiceReference();
ServiceReference nullPriority = new MockServiceReference();
ServiceReference high = new MockHighPriorityServiceReference();
OSGIServiceComparator instance = new OSGIServiceComparator();
assertThat(1).isEqualTo(instance.compare(low, high));
assertThat(-1).isEqualTo(instance.compare(high, low));
assertThat(0).isEqualTo(instance.compare(low, low));
assertThat(1).isEqualTo(instance.compare(nullPriority, high));
assertThat(-1).isEqualTo(instance.compare(high, nullPriority));
assertThat(0).isEqualTo(instance.compare(nullPriority, low));
}
/**
* Open this {@code ServiceTracker} and begin tracking services.
*
* <p>
* Services which match the search criteria specified when this
* {@code ServiceTracker} was created are now tracked by this
* {@code ServiceTracker}.
*
* @param trackAllServices If {@code true}, then this {@code ServiceTracker}
* will track all matching services regardless of class loader
* accessibility. If {@code false}, then this {@code ServiceTracker}
* will only track matching services which are class loader
* accessible to the bundle whose {@code BundleContext} is used by
* this {@code ServiceTracker}.
* @throws java.lang.IllegalStateException If the {@code BundleContext} with
* which this {@code ServiceTracker} was created is no longer valid.
* @since 1.3
*/
public void open(boolean trackAllServices) {
final Tracked t;
synchronized (this) {
if (tracked != null) {
return;
}
if (DEBUG) {
System.out.println("ServiceTracker.open: " + filter);
}
t = trackAllServices ? new AllTracked() : new Tracked();
synchronized (t) {
try {
context.addServiceListener(t, listenerFilter);
ServiceReference<S>[] references = null;
if (trackClass != null) {
references = getInitialReferences(trackAllServices, trackClass, null);
} else {
if (trackReference != null) {
if (trackReference.getBundle() != null) {
@SuppressWarnings("unchecked")
ServiceReference<S>[] single = new ServiceReference[] {trackReference};
references = single;
}
} else { /* user supplied filter */
references = getInitialReferences(trackAllServices, null, listenerFilter);
}
}
/* set tracked with the initial references */
t.setInitial(references);
} catch (InvalidSyntaxException e) {
throw new RuntimeException("unexpected InvalidSyntaxException: " + e.getMessage(), e);
}
}
tracked = t;
}
/* Call tracked outside of synchronized region */
t.trackInitial(); /* process the initial references */
}
/**
* @param sref
* @param level
* @param message
* @param exception
*/
private void log(final int level, final String message,
final Throwable exception, final ServiceReference<?> sref,
final Bundle bundle) {
this.level = level;
this.message = message;
this.exception = exception;
this.sref = sref;
this.bundle = bundle;
this.time = System.currentTimeMillis();
}
@Override
public AuthorizationService addingService ( final ServiceReference<AuthorizationService> reference )
{
final String[] serviceTypes = getServiceTypes ( reference );
final AuthorizationService service = this.context.getService ( reference );
this.authorizationManagerImpl.addService ( service, serviceTypes );
return service;
}
@Test
public void testLookupLdapProtocolCodecFactory()
{
ServiceReference<LdapProtocolCodecFactory> serviceReference = context.getServiceReference( LdapProtocolCodecFactory.class );
Object service = context.getService( serviceReference );
assertNotNull( service );
assertTrue( service instanceof LdapProtocolCodecFactory );
}
@Override
public void removedService( ServiceReference<LdapApiService> reference, LdapApiService service )
{
// TODO should we unregister the LdapProtocolCodecFactory at LdapApiService?
// ldapApiService.unregisterProtocolCodecFactory( factory );
registration.unregister();
}
public OperationUtils getOperationUtils() {
if (operationUtils == null) {
// Get all Services implement OperationUtils interface
try {
ServiceReference<?>[] references = this.context
.getAllServiceReferences(
OperationUtils.class.getName(), null);
for (ServiceReference<?> ref : references) {
operationUtils = (OperationUtils) this.context
.getService(ref);
return operationUtils;
}
return null;
}
catch (InvalidSyntaxException e) {
LOGGER.warning("Cannot load OperationUtils on WSImportMetadataProvider.");
return null;
}
}
else {
return operationUtils;
}
}
private static String makeId ( final ServiceReference<?> reference )
{
final Object id = reference.getProperty ( Constants.SERVICE_PID );
if ( id instanceof String )
{
return (String)id;
}
return "" + reference.getProperty ( Constants.SERVICE_ID );
}
void appendComponentRow(final StringBuffer sb,
final ServiceReference<ScrService> scrSR,
final Component component) {
final ScrUrl scrUrl = new ScrUrl(scrSR, component);
sb.append("<tr>\n");
sb.append("<td>");
if (scrServices.size()>1) {
scrUrl.scrLink(sb,
String.valueOf(component.getId()) +"@" +scrUrl.getSid());
} else {
scrUrl.scrLink(sb, String.valueOf(component.getId()));
}
sb.append("</td>");
sb.append("<td align='left'>");
sb.append(getComponentState(component));
sb.append("</td>");
sb.append("<td align='left'>");
scrUrl.scrLink(sb, component.getName());
sb.append("</td>");
sb.append("<td align='left'>");
sb.append(componentServices(component));
sb.append("</td>");
sb.append("</tr>\n");
}
private void addService ( final ServiceReference<?> serviceReference )
{
if ( serviceReference == null )
{
return;
}
this.service = (HttpService)this.context.getService ( serviceReference );
this.serviceReference = serviceReference;
if ( this.service != null )
{
configureService ();
}
}
void showLongService(ServiceReference<?> s, String pad, PrintWriter out) {
out.print(Util.showServiceClasses(s));
final String[] k = s.getPropertyKeys();
for (final String element : k) {
out.print("\n " + pad + element + " = "
+ Util.showObject(s.getProperty(element)));
}
}
/**
* Insert a ServiceReference to a ConfigurationPlugin in the correct Vector
* based on its ranking.
*
* @param serviceReference
* The ServiceReference.
* @param ranking
* The ranking the ServiceReference.
*/
private void insertPluginReference(ServiceReference<ConfigurationPlugin> serviceReference,
int ranking)
{
if (ranking < 0) {
insertPluginReference(serviceReference, ranking, preModificationPlugins);
} else if (0 <= ranking && ranking <= 1000) {
insertPluginReference(serviceReference, ranking, modifyingPlugins);
} else if (ranking > 1000) {
insertPluginReference(serviceReference, ranking, postModificationPlugins);
} else {
// Shouldn't happen
}
}
private void addReference ( final ServiceReference<?> ref )
{
logger.info ( "Adding service: {}", ref );
if ( this.references.add ( ref ) )
{
update ();
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
ComponentServiceObjectsImpl<?> getComponentServiceObjects(ServiceReference<?> sr, ReferenceListener rl) {
synchronized (cciBound) {
ComponentServiceObjectsImpl<?> cso = cciBound.get(sr);
if (cso == null) {
cso = new ComponentServiceObjectsImpl(this, sr, rl);
cciBound.put(sr, cso);
} else {
cso.addReferenceListener(rl);
}
return cso;
}
}
/**
* {@code ServiceListener} method for the {@code ServiceTracker} class.
* This method must NOT be synchronized to avoid deadlock potential.
*
* @param event {@code ServiceEvent} object from the framework.
*/
final public void serviceChanged(final ServiceEvent event) {
/*
* Check if we had a delayed call (which could happen when we
* close).
*/
if (closed) {
return;
}
@SuppressWarnings("unchecked")
final ServiceReference<S> reference = (ServiceReference<S>) event.getServiceReference();
if (DEBUG) {
System.out.println("ServiceTracker.Tracked.serviceChanged[" + event.getType() + "]: " + reference);
}
switch (event.getType()) {
case ServiceEvent.REGISTERED :
case ServiceEvent.MODIFIED :
track(reference, event);
/*
* If the customizer throws an unchecked exception, it is
* safe to let it propagate
*/
break;
case ServiceEvent.MODIFIED_ENDMATCH :
case ServiceEvent.UNREGISTERING :
untrack(reference, event);
/*
* If the customizer throws an unchecked exception, it is
* safe to let it propagate
*/
break;
}
}