private ServiceReference createReference(List<ServiceReference> references, String symbolicName) { ServiceReference ref = Mockito.mock(ServiceReference.class); Mockito.when(ref.getProperty("org.springframework.context.service.name")) .thenReturn(symbolicName); references.add(ref); return ref; }
@Override @SuppressWarnings("unchecked") public <T> T createProxy( BundleContext bundleContext, ServiceReference reference, ClassLoader classLoader) { Bundle exportingBundle = reference.getBundle(); if (exportingBundle == null) { throw new IllegalArgumentException( String.format("Service [%s] has been unregistered", reference)); } InvocationHandler handler = new OsgiInvocationHandler(bundleContext, reference); String[] classNames = (String[]) reference.getProperty(Constants.OBJECTCLASS); List<Class<?>> classes = new ArrayList<Class<?>>(classNames.length); for (String className : classNames) { try { Class<?> clazz = classLoader.loadClass(className); if (clazz.isInterface()) { classes.add(clazz); } } catch (ClassNotFoundException e) { throw new IllegalArgumentException( String.format( "Unable to find class [%s] with classloader [%s]", className, classLoader)); } } classes.add(OsgiProxy.class); classes.add(ServiceReference.class); return (T) Proxy.newProxyInstance(classLoader, classes.toArray(new Class<?>[classes.size()]), handler); }
@Override public int compare(ServiceReference<T> serviceReference1, ServiceReference<T> serviceReference2) { if (serviceReference1 == null) { if (serviceReference2 == null) { return 0; } else { return 1; } } else if (serviceReference2 == null) { return -1; } Object propertyValue1 = serviceReference1.getProperty(_propertyKey); Object propertyValue2 = serviceReference2.getProperty(_propertyKey); if (propertyValue1 == null) { if (propertyValue2 == null) { return 0; } else { return 1; } } else if (propertyValue2 == null) { return -1; } if (!(propertyValue2 instanceof Comparable)) { return serviceReference2.compareTo(serviceReference1); } Comparable<Object> propertyValueComparable2 = (Comparable<Object>) propertyValue2; return propertyValueComparable2.compareTo(propertyValue1); }
@Test public void testOwnerCannotSeeServiceClass() throws Exception { final Bundle bundleA = installBundle(getBundleArchiveA()); final Bundle bundleB = installBundle(getBundleArchiveB()); try { bundleA.start(); bundleB.start(); BundleContext contextA = bundleA.getBundleContext(); BundleContext contextB = bundleB.getBundleContext(); final CountDownLatch latch = new CountDownLatch(1); ServiceListener listener = new ServiceListener() { public void serviceChanged(ServiceEvent event) { latch.countDown(); } }; contextB.addServiceListener(listener); Object service = bundleB.loadClass(B.class.getName()).newInstance(); ServiceRegistration reg = contextA.registerService(B.class.getName(), service, null); ServiceReference ref = reg.getReference(); assertTrue(ref.isAssignableTo(bundleA, B.class.getName())); assertTrue(ref.isAssignableTo(bundleB, B.class.getName())); if (latch.await(5, TimeUnit.SECONDS) == false) throw new TimeoutException(); } finally { bundleA.uninstall(); bundleB.uninstall(); } }
private void createNotifier(String deviceId) { ServiceReference[] serviceListeners = null; ServiceReference serviceReference = null; Filter filter = null; String eventListenerFilter = "(" + Constants.OBJECTCLASS + "=" + UPnPEventListener.class.getName() + ")"; properties = new Properties(); properties.put(UPnPDevice.ID, deviceId); properties.put(UPnPService.ID, serviceId); try { serviceListeners = context.getServiceReferences(UPnPEventListener.class.getName(), null); if (serviceListeners != null && serviceListeners.length > 0) { for (int i = 0; i < serviceListeners.length; i++) { serviceReference = serviceListeners[i]; filter = (Filter) serviceReference.getProperty(UPnPEventListener.UPNP_FILTER); if (filter == null) { eventListeners.add(serviceReference); } else if (filter.match(properties)) { addNewListener(serviceReference); } } } } catch (Exception e) { } try { String filterString = eventListenerFilter; context.addServiceListener(this, filterString); } catch (Exception e) { } }
@Test public void testRegBundleIsRefBundle() throws Exception { Bundle bundle = installBundle(getBundleArchiveA()); try { bundle.start(); final CountDownLatch latch = new CountDownLatch(1); ServiceListener listener = new ServiceListener() { public void serviceChanged(ServiceEvent event) { latch.countDown(); } }; BundleContext context = bundle.getBundleContext(); context.addServiceListener(listener); Object service = bundle.loadClass(A.class.getName()).newInstance(); ServiceRegistration reg = context.registerService(A.class.getName(), service, null); ServiceReference ref = reg.getReference(); assertTrue(ref.isAssignableTo(bundle, A.class.getName())); if (latch.await(5, TimeUnit.SECONDS) == false) throw new TimeoutException(); } finally { bundle.uninstall(); } }
private static ServiceReferenceDTO getServiceReferenceDTO(ServiceReference<?> ref) { if (ref == null) { return null; } Bundle b = ref.getBundle(); if (b == null) { // service has been unregistered return null; } ServiceReferenceDTO dto = new ServiceReferenceDTO(); dto.bundle = b.getBundleId(); String[] keys = ref.getPropertyKeys(); Map<String, Object> properties = newMap(keys.length); for (String k : keys) { Object v = ref.getProperty(k); if (Constants.SERVICE_ID.equals(k)) { dto.id = ((Long) v).longValue(); } properties.put(k, mapValue(v)); } dto.properties = properties; Bundle[] using = ref.getUsingBundles(); final int length = (using == null) ? 0 : using.length; long[] usingBundles = new long[length]; for (int i = 0; i < length; i++) { usingBundles[i] = using[i].getBundleId(); } dto.usingBundles = usingBundles; return dto; }
@SuppressWarnings({"rawtypes", "unchecked", "unused"}) private void logServiceProperties(final Class<?> klaz, final Object instance) throws Exception { final BundleContext context = bundleContext(); final ServiceReference[] referenceArray = context.getAllServiceReferences(klaz.getName(), null); for (final ServiceReference reference : referenceArray) { final Object service = context.getService(reference); if (service == instance) { log.info("instance=" + instance); final String[] propKeyArray = reference.getPropertyKeys(); for (final String propKey : propKeyArray) { final Object propValue = reference.getProperty(propKey); log.info(propKey + "=" + propValue); } // final String[] nameArray = (String[]) reference // .getProperty("objectClass"); // for (final String name : nameArray) { // log.info("name=" + name); // } } } }
@Override public void start(BundleContext context) throws Exception { LOG.info("Starting Bundle"); // Get our name. String myName = context.getBundle().getSymbolicName(); // Find reference. ServiceReference<HelloService> ref = context.getServiceReference(HelloService.class); if (ref != null) { try { // Print service properties. String props = getServiceProperties(ref); LOG.info( "Calling HelloService#sayHello('{}') Published by {}. Props:\n{}", myName, ref.getBundle().getSymbolicName(), props); // Get the service HelloService service = context.getService(ref); if (service != null) { service.sayHello(myName); } } finally { // Release reference context.ungetService(ref); } } }
/** * An apform instance to represent a legacy component discovered in the OSGi registry * * @param ipojoInstance */ public ApformOSGiInstance(Specification specification, ServiceReference<?> reference) { super( new InstanceDeclaration( VersionedReference.any(generateImplementationName(specification, reference)), generateInstanceName(specification, reference))); this.specification = specification; for (PropertyDefinition property : specification.getDeclaration().getPropertyDefinitions()) { Object value = reference.getProperty(property.getName()); if (value != null) this.declaration.getProperties().put(property.getName(), value.toString()); } this.reference = reference; this.bundle = reference.getBundle(); this.bundleContext = AccessController.doPrivileged( new PrivilegedAction<BundleContext>() { public BundleContext run() { return bundle.getBundleContext(); } }); this.service = null; }
private Collection<CommandName> listCommands() { Set<CommandName> commands = new HashSet<>(); ServiceReference<?>[] refs; try { refs = context.getAllServiceReferences(null, "(osgi.command.scope=*)"); } catch (InvalidSyntaxException e) { // should never happen throw new RuntimeException(e); } for (ServiceReference<?> ref : refs) { String scope = (String) ref.getProperty("osgi.command.scope"); Object funcsObj = ref.getProperty("osgi.command.function"); String[] funcs; if (funcsObj instanceof String[]) funcs = (String[]) funcsObj; else if (funcsObj instanceof String) funcs = new String[] {(String) funcsObj}; else funcs = new String[0]; for (String func : funcs) { CommandName command = new CommandName(scope, func); commands.add(command); } } return commands; }
/** @param serviceReference */ private void addBatchProcessor(ServiceReference serviceReference) { SolrSearchBatchResultProcessor processor = (SolrSearchBatchResultProcessor) osgiComponentContext.locateService(SEARCH_BATCH_RESULT_PROCESSOR, serviceReference); Long serviceId = (Long) serviceReference.getProperty(Constants.SERVICE_ID); batchProcessorsById.put(serviceId, processor); String[] processorNames = getSetting(serviceReference.getProperty(REG_BATCH_PROCESSOR_NAMES), new String[0]); if (processorNames != null) { for (String processorName : processorNames) { batchProcessors.put(processorName, processor); } } // bit of a kludge until I can figure out why felix doesn't wire up the default // processor even though it finds a matching service. boolean defaultBatchProcessor = getSetting( serviceReference.getProperty( SolrSearchBatchResultProcessor.DEFAULT_BATCH_PROCESSOR_PROP), false); if (defaultBatchProcessor) { defaultSearchBatchProcessor = processor; } }
/** * Should only be called while holding a lock from {@link #lock} * * @return */ private Snapshot getSnapshot(boolean openingPrices) { lock.readLock().lock(); try { Availability availability = getCurrentAvailability(); /* Nothing we can check */ if (availability == Availability.NONE) { return new Snapshot(availability, null, Collections.<String, Double>emptyMap()); } /* Pick a random Jedis to call */ Map<ServiceReference<Endpoint>, JedisPool> toUse = new HashMap<ServiceReference<Endpoint>, JedisPool>(writableMap); toUse.putAll(readableMap); ServiceReference<Endpoint> ref = getARandomJedis(toUse); /* Get the prices */ Map<String, Double> prices = getPrices(toUse.get(ref), openingPrices); while (prices == null && !toUse.isEmpty()) { // This Jedis didn't work! toUse.remove(ref); ref = getARandomJedis(toUse); prices = getPrices(toUse.get(ref), openingPrices); } /* Return the data */ return (prices == null) ? new Snapshot(Availability.NONE, null, Collections.<String, Double>emptyMap()) : new Snapshot(availability, (String) ref.getProperty(Endpoint.URI), prices); } finally { lock.readLock().unlock(); } }
/** @param serviceReference */ private void removeBatchProcessor(ServiceReference serviceReference) { Long serviceId = (Long) serviceReference.getProperty(Constants.SERVICE_ID); SolrSearchResultProcessor processor = processorsById.remove(serviceId); if (processor != null) { List<String> toRemove = new ArrayList<String>(); for (Entry<String, SolrSearchResultProcessor> e : processors.entrySet()) { if (processor.equals(e.getValue())) { toRemove.add(e.getKey()); } } for (String r : toRemove) { processors.remove(r); } // bit of a kludge until I can figure out why felix doesn't wire up the default // processor even though it finds a matching service. boolean defaultBatchProcessor = getSetting( serviceReference.getProperty( SolrSearchBatchResultProcessor.DEFAULT_BATCH_PROCESSOR_PROP), false); if (defaultBatchProcessor) { defaultSearchBatchProcessor = null; } } }
public void serviceChanged(ServiceEvent serviceEvent) { int serviceEventType = serviceEvent.getType(); switch (serviceEventType) { case ServiceEvent.REGISTERED: { ServiceReference serviceReference = serviceEvent.getServiceReference(); Filter filter = (Filter) serviceReference.getProperty(UPnPEventListener.UPNP_FILTER); if (filter == null) { addNewListener(serviceReference); } else if (filter.match(properties)) { addNewListener(serviceReference); } } ; break; case ServiceEvent.MODIFIED: { } ; break; case ServiceEvent.UNREGISTERING: { removeListener(serviceEvent.getServiceReference()); } ; break; } }
public int compareTo(Object reference) { ServiceReference other = (ServiceReference) reference; Long id = (Long) getProperty(Constants.SERVICE_ID); Long otherId = (Long) other.getProperty(Constants.SERVICE_ID); if (id.equals(otherId)) { return 0; // same service } Object rankObj = getProperty(Constants.SERVICE_RANKING); Object otherRankObj = other.getProperty(Constants.SERVICE_RANKING); // If no rank, then spec says it defaults to zero. rankObj = (rankObj == null) ? new Integer(0) : rankObj; otherRankObj = (otherRankObj == null) ? new Integer(0) : otherRankObj; // If rank is not Integer, then spec says it defaults to zero. Integer rank = (rankObj instanceof Integer) ? (Integer) rankObj : new Integer(0); Integer otherRank = (otherRankObj instanceof Integer) ? (Integer) otherRankObj : new Integer(0); // Sort by rank in ascending order. if (rank.compareTo(otherRank) < 0) { return -1; // lower rank } else if (rank.compareTo(otherRank) > 0) { return 1; // higher rank } // If ranks are equal, then sort by service id in descending order. return (id.compareTo(otherId) < 0) ? 1 : -1; }
/** * * Call all plugins contained in a list and * optionally allow modifications. * * * * @param targetServiceReference Reference to the target ManagedService(Factory). * * @param servicePid The service PID corresponding to the current configuration * @param dictionary The configuration dictionary to process. * * @param plugins list of references to ConfigurationPlugins. * * @param allowModification Should modifications to the configuration dictionary be allowed. * * * @return The modified configuration dictionary. */ private ConfigurationDictionary callPlugins( ServiceReference targetServiceReference, String servicePid, ConfigurationDictionary dictionary, List plugins, boolean allowModification) { ConfigurationDictionary currentDictionary = dictionary; Iterator it = plugins.iterator(); while (it.hasNext()) { ServiceReference pluginReference = (ServiceReference) it.next(); // Only call the plugin if no cm.target is specified or if it // matches the pid of the target service String cmTarget = (String) pluginReference.getProperty(ConfigurationPlugin.CM_TARGET); if (cmTarget == null || cmTarget.equals(servicePid)) { ConfigurationPlugin plugin = (ConfigurationPlugin) context.getService(pluginReference); if (plugin == null) { continue; } ConfigurationDictionary dictionaryCopy = new ConfigurationDictionary(dictionary); try { plugin.modifyConfiguration(targetServiceReference, dictionaryCopy); if (allowModification) { currentDictionary = dictionaryCopy; } } catch (Exception exception) { LOG.error("[CM] Exception thrown by plugin: " + exception.getMessage()); } } } return currentDictionary; }
/** Handles service change events. */ public void serviceChanged(ServiceEvent event) { ServiceReference serviceRef = event.getServiceReference(); // if the event is caused by a bundle being stopped, we don't want to // know if (serviceRef.getBundle().getState() == Bundle.STOPPING) { return; } Object service = MUCActivator.bundleContext.getService(serviceRef); // we don't care if the source service is not a protocol provider if (!(service instanceof ProtocolProviderService)) { return; } switch (event.getType()) { case ServiceEvent.REGISTERED: addQueryToProviderPresenceListeners((ProtocolProviderService) service); break; case ServiceEvent.UNREGISTERING: removeQueryFromProviderPresenceListeners((ProtocolProviderService) service); break; } }
public String getText(Object obj) { if (obj instanceof ServiceReference) { ServiceReference r = (ServiceReference) obj; JanusModule m = (JanusModule) getBundleContext().getService(r); return m.getName() + " (Provider = " + r.getBundle().getSymbolicName() + ")"; } return obj.toString(); }
/** Generate the uniques name of the implementation associated with this instance in Apam */ private static ImplementationReference<?> generateImplementationName( Specification specification, ServiceReference<?> reference) { String bundle = reference.getBundle().getSymbolicName(); if (bundle == null) bundle = (String) reference.getBundle().getHeaders().get("Bundle-Name"); return new ApformOSGiImplementation.Reference( specification.getName() + "[provider.bundle=" + bundle + "]"); }
private void removePluginReference(Object serviceId, List pluginsList) { for (int i = 0; i < pluginsList.size(); ++i) { ServiceReference serviceReference = (ServiceReference) pluginsList.get(i); Long currentId = (Long) serviceReference.getProperty(Constants.SERVICE_ID); if (currentId.equals(serviceId)) { pluginsList.remove(i); return; } } }
private void printAppConfigurationDetails(PrintWriter pw) { Map<String, Realm> configs = getConfigurationDetails(); if (configs.isEmpty()) { pw.println("No JAAS LoginModule registered"); return; } pw.println("<p class=\"statline ui-state-highlight\">${Registered LoginModules}</p>"); pw.println("<table class=\"nicetable\">"); pw.println("<thead><tr>"); pw.println("<th class=\"header\">${Realm}</th>"); pw.println("<th class=\"header\">${Rank}</th>"); pw.println("<th class=\"header\">${Control Flag}</th>"); pw.println("<th class=\"header\">${Type}</th>"); pw.println("<th class=\"header\">${Classname}</th>"); pw.println("</tr></thead>"); for (Realm r : configs.values()) { String realmName = r.getRealmName(); pw.printf( "<tr class=\"ui-state-default\"><td>%s</td><td colspan=\"4\"></td></tr>", realmName); String rowClass = "odd"; for (AppConfigurationHolder ah : r.getConfigs()) { LoginModuleProvider lp = ah.getProvider(); String type = getType(lp); pw.printf("<tr class=\"%s ui-state-default\"><td></td><td>%d</td>", rowClass, lp.ranking()); pw.printf("<td>%s</td>", ControlFlag.toString(lp.getControlFlag())); pw.printf("<td>%s</td>", type); pw.printf("<td>"); pw.print(lp.getClassName()); if (lp instanceof OsgiLoginModuleProvider) { ServiceReference sr = ((OsgiLoginModuleProvider) lp).getServiceReference(); Object id = sr.getProperty(Constants.SERVICE_ID); pw.printf("<a href=\"${pluginRoot}/../services/%s\">(%s)</a>", id, id); } else if (lp instanceof ConfigLoginModuleProvider) { Map config = lp.options(); Object id = config.get(Constants.SERVICE_PID); pw.printf("<a href=\"${pluginRoot}/../configMgr/%s\">(Details)</a>", id); } pw.printf("</td>"); pw.println("</tr>"); if (rowClass.equals("odd")) { rowClass = "even"; } else { rowClass = "odd"; } } } pw.println("</table>"); }
/** * Creates a wrapper for the given service reference providing read only access to the reference * properties. */ public ReadOnlyDictionary(final ServiceReference serviceReference) { Hashtable properties = new Hashtable(); final String[] keys = serviceReference.getPropertyKeys(); if (keys != null) { for (int j = 0; j < keys.length; j++) { final String key = keys[j]; properties.put(key, serviceReference.getProperty(key)); } } m_delegatee = properties; }
/** @see UserAdminUtil#fireEvent(int, Role) */ @Override public void fireEvent(int type, Role role) { if (null == role) { throw new IllegalArgumentException("parameter role must not be null"); } ServiceReference<?> reference = userAdminRegistration.getReference(); final UserAdminEvent uaEvent = new UserAdminEvent(reference, type, role); // // send event to all listeners, asynchronously - in a separate thread!! // UserAdminListener[] eventListeners = listenerService.getServices(new UserAdminListener[0]); if (null != eventListeners) { for (Object listenerObject : eventListeners) { final UserAdminListener listener = (UserAdminListener) listenerObject; eventExecutor.execute( new Runnable() { @Override public void run() { listener.roleChanged(uaEvent); } }); } } // // send event to EventAdmin if present // EventAdmin eventAdmin = m_eventService.getService(); String name = getEventTypeName(type); if (null != eventAdmin && name != null) { Dictionary<String, Object> properties = new Hashtable<String, Object>(); properties.put("event", uaEvent); properties.put("role", role); properties.put("role.name", role.getName()); properties.put("role.type", role.getType()); properties.put("service", reference); properties.put("service.id", reference.getProperty(Constants.SERVICE_ID)); properties.put("service.objectClass", reference.getProperty(Constants.OBJECTCLASS)); properties.put("service.pid", reference.getProperty(Constants.SERVICE_PID)); // Event event = new Event(PaxUserAdminConstants.EVENT_TOPIC_PREFIX + name, properties); eventAdmin.postEvent(event); } else { String message = "No event service available or incompatible type - cannot send event of type '" + name + "' for role '" + role.getName() + "'"; logMessage(this, LogService.LOG_DEBUG, message); } }
@Override public BeanFactory getBeanFactory(Bundle bundle) { for (ServiceReference ref : bundle.getRegisteredServices()) { for (String clazz : ((String[]) ref.getProperty("objectClass"))) { if (clazz.equals(CONTAINER_KEY)) { return new BeanFactoryBlueprintImpl( (BlueprintContainer) bundle.getBundleContext().getService(ref)); } } } return null; }
/** * * Insert a ServiceReference in a list sorted on cm.ranking property. * * * * @param serviceReference The ServiceReference. * * @param pluginsList The list. */ private void insertPluginReference( ServiceReference serviceReference, int ranking, List pluginsList) { int i; for (i = 0; i < pluginsList.size(); ++i) { ServiceReference nextReference = (ServiceReference) pluginsList.get(i); Long serviceId = (Long) nextReference.getProperty(Constants.SERVICE_ID); Integer rankingOfNextReference = (Integer) pluginRankings.get(serviceId); if (ranking < rankingOfNextReference.intValue()) { break; } } pluginsList.set(i, serviceReference); }
/** @param serviceReference */ private void addProvider(ServiceReference serviceReference) { SolrSearchPropertyProvider provider = (SolrSearchPropertyProvider) osgiComponentContext.locateService(SEARCH_PROPERTY_PROVIDER, serviceReference); Long serviceId = (Long) serviceReference.getProperty(Constants.SERVICE_ID); propertyProviderById.put(serviceId, provider); String[] processorNames = getSetting(serviceReference.getProperty(REG_PROVIDER_NAMES), new String[0]); for (String processorName : processorNames) { propertyProvider.put(processorName, provider); } }
<T> T getService(URI bundleURI, Class<T> svcClazz) { Bundle bundle = get().get(bundleURI); if (bundle == null) { synchronized (this) { bundle = startBundle(bundleURI); } } BundleContext ctx = bundle.getBundleContext(); for (ServiceReference<?> ref : bundle.getRegisteredServices()) { if (ref.isAssignableTo(bundle, svcClazz.getName())) { return svcClazz.cast(ctx.getService(ref)); } } return null; }
protected void collectSupportedPublishingEvents( ServiceReference<Portlet> serviceReference, com.liferay.portal.model.Portlet portletModel) { Set<QName> publishingEvents = new HashSet<>(); PortletApp portletApp = portletModel.getPortletApp(); List<String> supportedPublishingEvents = StringPlus.asList(serviceReference.getProperty("javax.portlet.supported-publishing-event")); for (String supportedPublishingEvent : supportedPublishingEvents) { String name = supportedPublishingEvent; String qname = null; String[] parts = StringUtil.split(supportedPublishingEvent, StringPool.SEMICOLON); if (parts.length == 2) { name = parts[0]; qname = parts[1]; } QName qName = getQName(name, qname, portletApp.getDefaultNamespace()); publishingEvents.add(qName); } portletModel.setPublishingEvents(publishingEvents); }
public static String getString(final ServiceReference<?> ref, final String key) { final Object value = ref.getProperty(key); if (value instanceof String) { return (String) value; } return null; }