Java Code Examples for org.osgi.framework.ServiceReference#getProperty()

The following examples show how to use org.osgi.framework.ServiceReference#getProperty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OSGIBusListener.java    From cxf with Apache License 2.0 6 votes vote down vote up
private boolean isExcluded(ServiceReference<?> ref) {
    String o = (String)ref.getProperty(SERVICE_PROPERTY_RESTRICTED);
    if (!StringUtils.isEmpty(o)) {
        // if the service's restricted-regex is set, the service is excluded when the app not matching that regex
        BundleContext app = bus.getExtension(BundleContext.class);
        try {
            if (app != null && !app.getBundle().getSymbolicName().matches(o)) {
                return true;
            }
        } catch (IllegalArgumentException e) {
            // ignore
        }
    }
    // if the excludes-regex is set, the service is excluded when matching that regex.
    return extensionBundlesExcludesPattern != null
        && extensionBundlesExcludesPattern.matcher(ref.getBundle().getSymbolicName()).matches();
}
 
Example 2
Source File: ChannelAspectProcessor.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
private static SortedSet<String> makeRequires ( final ServiceReference<ChannelAspectFactory> ref )
{
    final Object val = ref.getProperty ( ChannelAspectFactory.REQUIRES );

    if ( val instanceof String[] )
    {
        return new TreeSet<> ( Arrays.asList ( (String[])val ) );
    }
    if ( val instanceof String )
    {
        final String s = (String)val;
        if ( s.isEmpty () )
        {
            return null;
        }
        return new TreeSet<> ( Arrays.asList ( s.split ( "[\\p{Space},]+" ) ) );
    }
    return null;
}
 
Example 3
Source File: ContentHandlerWrapper.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private int compare(ServiceReference<?> ref1, ServiceReference<?> ref2) {
  final Object tmp1 = ref1.getProperty(Constants.SERVICE_RANKING);
  final Object tmp2 = ref2.getProperty(Constants.SERVICE_RANKING);

  final int r1 = (tmp1 instanceof Integer) ? ((Integer)tmp1).intValue() : 0;
  final int r2 = (tmp2 instanceof Integer) ? ((Integer)tmp2).intValue() : 0;

  if (r2 == r1) {
    final Long i1 = (Long)ref1.getProperty(Constants.SERVICE_ID);
    final Long i2 = (Long)ref2.getProperty(Constants.SERVICE_ID);
    return i1.compareTo(i2);

  } else {
    return r2 -r1;
  }
}
 
Example 4
Source File: AbstractBundle.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
protected final ServiceReferenceDTO getServiceReferenceDTO(ServiceReference ref){
	ServiceReferenceDTO dto = new ServiceReferenceDTO();
	dto.bundle = bundleId;
	dto.id = (Long) ref.getProperty(Constants.SERVICE_ID);
	dto.properties = new HashMap<String, Object>();
	for(String key : ref.getPropertyKeys()){
		Object val = ref.getProperty(key);
		dto.properties.put(key, getDTOValue(val));
	}
	Bundle[] usingBundles = ref.getUsingBundles();
	if(usingBundles == null){
		dto.usingBundles = new long[0];
	} else {
		dto.usingBundles = new long[usingBundles.length];
		for(int j=0;j<usingBundles.length;j++){
			dto.usingBundles[j] = usingBundles[j].getBundleId();
		}
	}
	return dto;
}
 
Example 5
Source File: ConfigurableServiceResource.java    From smarthome with Eclipse Public License 2.0 5 votes vote down vote up
private String getServiceId(ServiceReference<?> serviceReference) {
    Object pid = serviceReference.getProperty(Constants.SERVICE_PID);
    if (pid != null) {
        return (String) pid;
    } else {
        return (String) serviceReference.getProperty(ComponentConstants.COMPONENT_NAME);
    }
}
 
Example 6
Source File: ConsoleLogFormatter.java    From vespa with Apache License 2.0 5 votes vote down vote up
private static String getProperty(LogEntry entry, String name) {
    ServiceReference<?> ref = entry.getServiceReference();
    if (ref == null) {
        return null;
    }
    Object val = ref.getProperty(name);
    if (val == null) {
        return null;
    }
    return val.toString();
}
 
Example 7
Source File: JiniExportedService.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * DOCUMENT ME!
 *
 * @param serviceReference DOCUMENT ME!
 */
private void init(ServiceReference serviceReference) {
    // OSGi
    this.serviceReference = serviceReference;
    this.service = Activator.bc.getService(serviceReference);

    // Jini
    this.serviceID = Util.getServiceID((String) serviceReference.getProperty(
                JiniDriver.SERVICE_ID));
    this.entries = (Entry[]) serviceReference.getProperty(JiniDriver.ENTRIES);
}
 
Example 8
Source File: Concierge.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * get the service object.
 * 
 * @param reference
 *            the service reference.
 * @return the service object.
 * @see org.osgi.framework.BundleContext#getService(org.osgi.framework.ServiceReference)
 * 
 */
public <S> S getService(final ServiceReference<S> reference) {
	checkValid();
	if (reference == null) {
		throw new NullPointerException("Null service reference.");
	}

	if (SECURITY_ENABLED) {
		final String[] clazzes = (String[]) reference
				.getProperty(Constants.OBJECTCLASS);
		for (int i = 0; i < clazzes.length; i++) {
			try {
				AccessController.checkPermission(new ServicePermission(
						clazzes[i], ServicePermission.GET));
				return ((ServiceReferenceImpl<S>) reference)
						.getService(bundle);
			} catch (final SecurityException se) {
				continue;
			}
		}
		throw new SecurityException(
				"Caller does not have permissions for getting service from "
						+ reference);
	}

	return ((ServiceReferenceImpl<S>) reference).getService(bundle);
}
 
Example 9
Source File: EventHandlerFactoryTracker.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
private static String getFactoryId ( final ServiceReference<EventHandlerFactory> reference )
{
    final Object o = reference.getProperty ( EventHandlerFactory.FACTORY_ID );
    if ( o instanceof String )
    {
        return (String)o;
    }
    return null;
}
 
Example 10
Source File: Activator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private String showDevice(ServiceReference<?> sr)
{
  final StringBuffer sb = new StringBuffer();
  Object o =
    sr.getProperty(org.osgi.service.device.Constants.DEVICE_CATEGORY);
  if (o instanceof String) {
    sb.append(o);
  } else if (o instanceof String[]) {
    final String[] dca = (String[]) o;
    for (int i = 0; i < dca.length; i++) {
      if (i > 0) {
        sb.append('_');
      }
      sb.append(dca[i]);
    }
  }
  o = sr.getProperty(org.osgi.framework.Constants.SERVICE_ID);
  if (o != null) {
    sb.append(", sid=");
    sb.append(o);
  }
  final Bundle b = sr.getBundle();
  if (b != null) {
    sb.append(", bid=");
    sb.append(b.getBundleId());
  }
  return sb.toString();
}
 
Example 11
Source File: PluginManager.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void removePluginReference(Object serviceId,
                                   Vector<ServiceReference<ConfigurationPlugin>> pluginsVector)
{
  for (int i = 0; i < pluginsVector.size(); ++i) {
    ServiceReference<ConfigurationPlugin> serviceReference = pluginsVector.elementAt(i);
    Long currentId = (Long) serviceReference.getProperty(SERVICE_ID);
    if (currentId.equals(serviceId)) {
      pluginsVector.removeElementAt(i);
      return;
    }
  }
}
 
Example 12
Source File: UPnPDiscovery.java    From fuchsia with Apache License 2.0 5 votes vote down vote up
@Bind(id = "upnp-device", specification = UPnPDevice.class, aggregate = true)
public void addingService(ServiceReference reference) {
    String deviceID = (String) reference.getProperty(UPnPDevice.FRIENDLY_NAME);
    String deviceType = (String) reference.getProperty(UPnPDevice.TYPE);
    String udn = (String) reference.getProperty(UPnPDevice.ID);
    createImportationDeclaration(deviceID, deviceType, udn);
}
 
Example 13
Source File: GeneratorProcessor.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
private static String getString ( final ServiceReference<?> ref, final String name )
{
    final Object v = ref.getProperty ( name );
    if ( v == null )
    {
        return null;
    }
    return v.toString ();
}
 
Example 14
Source File: ConfigurableServiceResource.java    From openhab-core with Eclipse Public License 2.0 5 votes vote down vote up
private List<ConfigurableServiceDTO> getServicesByFilter(String filter) {
    List<ConfigurableServiceDTO> services = new ArrayList<>();
    ServiceReference<?>[] serviceReferences = null;
    try {
        serviceReferences = bundleContext.getServiceReferences((String) null, filter);
    } catch (InvalidSyntaxException ex) {
        logger.error("Cannot get service references because the syntax of the filter '{}' is invalid.", filter);
    }

    if (serviceReferences != null) {
        for (ServiceReference<?> serviceReference : serviceReferences) {
            String id = getServiceId(serviceReference);
            String label = (String) serviceReference.getProperty(ConfigurableService.SERVICE_PROPERTY_LABEL);
            if (label == null) { // for multi context services the label can be changed and must be read from config
                                 // admin.
                label = configurationService.getProperty(id, ConfigConstants.SERVICE_CONTEXT);
            }
            String category = (String) serviceReference.getProperty(ConfigurableService.SERVICE_PROPERTY_CATEGORY);
            String configDescriptionURI = (String) serviceReference
                    .getProperty(ConfigurableService.SERVICE_PROPERTY_DESCRIPTION_URI);

            if (configDescriptionURI == null) {
                String factoryPid = (String) serviceReference.getProperty(ConfigurationAdmin.SERVICE_FACTORYPID);
                configDescriptionURI = getConfigDescriptionByFactoryPid(factoryPid);
            }

            Object factoryProperty = serviceReference
                    .getProperty(ConfigurableService.SERVICE_PROPERTY_FACTORY_SERVICE);
            boolean multiple = factoryProperty instanceof Boolean ? (Boolean) factoryProperty
                    : Boolean.parseBoolean((String) factoryProperty);

            services.add(new ConfigurableServiceDTO(id, label, category, configDescriptionURI, multiple));
        }
    }
    return services;
}
 
Example 15
Source File: BluetoothImporter.java    From fuchsia with Apache License 2.0 5 votes vote down vote up
@Unbind
public void unbindBluetoothProxyFactories(Factory f, ServiceReference<Factory> sr) {
    String deviceName = (String) sr.getProperty("device_name");
    bluetoothProxiesFactories.remove(deviceName);
    ImportDeclaration idec = resolvedImportDeclarations.remove(deviceName);
    ComponentInstance proxy = proxyComponentInstances.remove(idec);

    idec.unhandle(serviceReference);
    proxy.dispose();

    unresolvedImportDeclarations.put(deviceName, idec);
}
 
Example 16
Source File: Axis2ConfigServiceListener.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
private void processRegisteredAxis2ConfigServices(ServiceReference sr, int eventType) {
    String configService = (String) sr.getProperty(AXIS2_CONFIG_SERVICE);
    if (configServiceProcessorMap != null) {
        ConfigurationServiceProcessor configServiceProcessor = configServiceProcessorMap.get(configService);
        if (configServiceProcessor != null) {
            try {
                configServiceProcessor.processConfigurationService(sr, eventType);
            } catch (AxisFault axisFault) {
                String msg = "Failed to process the configuration service :" + configService;
                log.error(msg, axisFault);
            }
        }
    }
}
 
Example 17
Source File: XMLParserActivator.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Creates a new XML Parser Factory object.
 * 
 * <p>
 * A unique XML Parser Factory object is returned for each call to this
 * method.
 * 
 * <p>
 * The returned XML Parser Factory object will be configured for validating
 * and namespace aware support as specified in the service properties of the
 * specified ServiceRegistration object.
 * 
 * This method can be overridden to configure additional features in the
 * returned XML Parser Factory object.
 * 
 * @param bundle The bundle using the service.
 * @param registration The {@code ServiceRegistration} object for the
 *        service.
 * @return A new, configured XML Parser Factory object or null if a
 *         configuration error was encountered
 */
public Object getService(Bundle bundle, ServiceRegistration registration) {
	ServiceReference sref = registration.getReference();
	String parserFactoryClassName = (String) sref.getProperty(FACTORYNAMEKEY);
	// need to set factory properties
	Object factory = getFactory(parserFactoryClassName);
	if (factory instanceof SAXParserFactory) {
		((SAXParserFactory) factory).setValidating(((Boolean) sref.getProperty(PARSER_VALIDATING)).booleanValue());
		((SAXParserFactory) factory).setNamespaceAware(((Boolean) sref.getProperty(PARSER_NAMESPACEAWARE)).booleanValue());
	} else {
		if (factory instanceof DocumentBuilderFactory) {
			((DocumentBuilderFactory) factory).setValidating(((Boolean) sref.getProperty(PARSER_VALIDATING)).booleanValue());
			((DocumentBuilderFactory) factory).setNamespaceAware(((Boolean) sref.getProperty(PARSER_NAMESPACEAWARE)).booleanValue());
		}
	}
	return factory;
}
 
Example 18
Source File: OSGiServiceCapabilityTracker.java    From carbon-kernel with Apache License 2.0 4 votes vote down vote up
@Override
public Object addingService(ServiceReference<Object> reference) {
    Object serviceObject = DataHolder.getInstance().getBundleContext().getService(reference);
    String serviceInterfaceClassName = ((String[]) reference.getProperty(OBJECT_CLASS))[0];
    String serviceImplClassName = serviceObject.getClass().getName();
    Bundle bundle = reference.getBundle();

    if (RequiredCapabilityListener.class.getName().equals(serviceInterfaceClassName)) {
        String componentKey = getNonEmptyStringAfterTrim((String) reference.getProperty(COMPONENT_NAME))
                .orElseThrow(() -> new StartOrderResolverException(COMPONENT_NAME + " value is missing in " +
                        "the services registered with the key " + serviceInterfaceClassName + ", " +
                        "implementation class name is " + serviceImplClassName));

        startupComponentManager.addRequiredCapabilityListener(
                (RequiredCapabilityListener) serviceObject, componentKey, reference.getBundle());

    } else if (CapabilityProvider.class.getName().equals(serviceInterfaceClassName)) {
        String capabilityName = getNonEmptyStringAfterTrim((String) reference.getProperty(CAPABILITY_NAME))
                .orElseThrow(() -> new StartOrderResolverException(CAPABILITY_NAME + " value is missing in " +
                        "the services registered with the key " + serviceInterfaceClassName + ", " +
                        "implementation class name is " + serviceImplClassName));

        CapabilityProviderCapability capabilityProvider = new CapabilityProviderCapability(
                CapabilityProvider.class.getName(),
                Capability.CapabilityType.OSGi_SERVICE,
                Capability.CapabilityState.AVAILABLE,
                capabilityName.trim(),
                bundle);

        startupComponentManager.addExpectedOrAvailableCapabilityProvider(capabilityProvider);

        CapabilityProvider provider = (CapabilityProvider) serviceObject;
        IntStream.range(0, provider.getCount())
                .forEach(count -> startupComponentManager.addExpectedCapability(
                        new OSGiServiceCapability(
                                capabilityName.trim(),
                                Capability.CapabilityType.OSGi_SERVICE,
                                Capability.CapabilityState.EXPECTED,
                                bundle,
                                true)));
    } else {
        if (Boolean.TRUE.equals(reference.getProperty(SKIP_CARBON_STARTUP_RESOLVER))) {
            logger.debug("Skipping tracking of service {} which implements {}.", serviceImplClassName,
                         serviceInterfaceClassName);
            return null;
        }

        logger.debug("Updating indirect dependencies in components for interface={} via the implementation={}",
                serviceInterfaceClassName, serviceImplClassName);
        startupComponentManager.updateCapability(new OSGiServiceCapability(
                serviceInterfaceClassName,
                Capability.CapabilityType.OSGi_SERVICE,
                Capability.CapabilityState.AVAILABLE,
                bundle,
                false));
    }

    return serviceObject;
}
 
Example 19
Source File: EndpointExporter.java    From neoscada with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected void exportService ( final ServiceReference<?> reference, final Object service )
{
    logger.info ( "Exporting service: {} -> {}", new Object[] { reference } );

    Endpoint e = null;
    final ClassLoader currentClassLoader = Thread.currentThread ().getContextClassLoader ();

    try
    {
        Thread.currentThread ().setContextClassLoader ( service.getClass ().getClassLoader () );

        final String[] clazzes = (String[])reference.getProperty ( Constants.OBJECTCLASS );

        for ( final String clazzName : clazzes )
        {
            final Class<?> clazz = reference.getBundle ().loadClass ( clazzName );

            final WebService webService = clazz.getAnnotation ( WebService.class );

            if ( webService != null )
            {
                e = Endpoint.create ( service );

                final String address = makeAddress ( reference, service, webService );
                e.publish ( address );
                e = this.endpoints.put ( reference, e );

                if ( e != null )
                {
                    // we found a previous export ... stop the old one
                    try
                    {
                        e.stop ();
                    }
                    catch ( final Throwable e2 )
                    {
                        logger.warn ( "Failed to stop previous export", e2 );
                    }
                    e = null;
                }

            }
            else
            {
                logger.warn ( "No webservice annotation found on {}", clazz );
            }

        }

    }
    catch ( final Exception ex )
    {
        logger.warn ( "Failed to export", ex );
    }
    finally
    {
        Thread.currentThread ().setContextClassLoader ( currentClassLoader );
        if ( e != null )
        {
            e.stop ();
        }
    }
}
 
Example 20
Source File: FilterMenuOperationsHook.java    From gvnix with GNU General Public License v3.0 2 votes vote down vote up
/**
 * Check if service reference is gvNIX {@link MenuOperations} implementation <br>
 * Uses {@link MenuOperationsImpl#GVNIX_COMPONENT} service property.
 * 
 * @param sr
 * @return
 */
public static boolean isGvNIXOperations(ServiceReference sr) {
    return sr.getProperty(MenuOperationsImpl.GVNIX_COMPONENT) != null;
}