Java 类org.osgi.framework.Filter 实例源码

项目:aries-jpa    文件:PersistenceProviderTracker.java   
private static Filter createFilter(BundleContext context, PersistenceUnit punit) {
    String filter;
    if (punit.getPersistenceProviderClassName() != null) {
        filter = String.format("(&(objectClass=%s)(%s=%s))",
                               PersistenceProvider.class.getName(),
                               JAVAX_PERSISTENCE_PROVIDER,
                               punit.getPersistenceProviderClassName());
    } else {
        filter = String.format("(objectClass=%s)", PersistenceProvider.class.getName());
    }

    try {
        return context.createFilter(filter);
    } catch (InvalidSyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}
项目:neoscada    文件:FilterUtil.java   
protected static Filter createFilter ( final String operand, final Filter... filters ) throws InvalidSyntaxException
{
    final StringBuilder sb = new StringBuilder ();

    sb.append ( "(" );
    sb.append ( operand );

    for ( final Filter filter : filters )
    {
        sb.append ( filter.toString () );
    }

    sb.append ( ")" );

    return FrameworkUtil.createFilter ( sb.toString () );
}
项目:neoscada    文件:ConnectionTracker.java   
protected Filter createFilter ()
{
    try
    {
        Class<?> filterClazz;
        if ( this.clazz != null )
        {
            filterClazz = this.clazz;
        }
        else
        {
            filterClazz = ConnectionService.class;
        }

        return FilterUtil.createAndFilter ( filterClazz.getName (), createFilterParameters () );
    }
    catch ( final InvalidSyntaxException e )
    {
        logger.warn ( "Failed to create filter", e );
        return null;
    }
}
项目:neoscada    文件:EventServiceImpl.java   
public EventServiceImpl ( final BundleContext context ) throws InvalidSyntaxException
{
    this.context = context;

    this.storeListener = new StoreListener () {

        @Override
        public void notify ( final Event event )
        {
            EventServiceImpl.this.eventStored ( event );
        }
    };

    final Filter filter = FilterUtil.createClassFilter ( Storage.class.getName () );
    this.storageTracker = new SingleServiceTracker<Storage> ( this.context, filter, new SingleServiceListener<Storage> () {

        @Override
        public void serviceChange ( final ServiceReference<Storage> reference, final Storage service )
        {
            setStorage ( service );
        }
    } );
    this.storageTracker.open ();
}
项目:osc-core    文件:InstallerIntegrationTest.java   
@Before
public void before() throws Exception {
    assertAllBundlesResolved();

    // Track ArtifactInstaller service ONLY from bundle org.osc.installer
    Bundle installerBundle = findBundle("osc-installer");
    Filter artifactInstallerTrackerFilter = FrameworkUtil.createFilter(String.format("(&(objectClass=%s)(service.bundleid=%d))", ArtifactInstaller.class.getName(), installerBundle.getBundleId()));
    this.artifactInstallerTracker = new ServiceTracker<>(this.bundleContext, artifactInstallerTrackerFilter, null);
    this.artifactInstallerTracker.open();

    // Wait up to 5 seconds for ArtifactInstaller to appear
    ArtifactInstaller artifactInstaller = this.artifactInstallerTracker.waitForService(5000);
    if (artifactInstaller == null) {
        fail("ArtifactInstaller service not available within 5 seconds");
    }

    this.fwkInstallerTracker = new ServiceTracker<>(this.bundleContext, FrameworkInstaller.class, null);
    this.fwkInstallerTracker.open();
}
项目:gemini.blueprint    文件:DependencyServiceManager.java   
private void sendInitialBootstrappingEvents(Set<MandatoryServiceDependency> deps) {
    // send the fine grained event
    List<OsgiServiceDependencyEvent> events = getUnsatisfiedDependenciesAsEvents(deps);
    for (OsgiServiceDependencyEvent nestedEvent : events) {
        BootstrappingDependencyEvent dependencyEvent =
                new BootstrappingDependencyEvent(context, context.getBundle(), nestedEvent);
        publishEvent(dependencyEvent);
    }

    // followed by the composite one
    String filterAsString = createDependencyFilter(deps);
    Filter filter = (filterAsString != null ? OsgiFilterUtils.createFilter(filterAsString) : null);
    BootstrappingDependenciesEvent event =
            new BootstrappingDependenciesEvent(context, context.getBundle(), events, filter, waitTime);

    publishEvent(event);
}
项目:gemini.blueprint    文件:BootstrappingDependenciesEvent.java   
/**
 * Constructs a new <code>BootstrappingDependencyEvent</code> instance.
 * 
 * @param source
 */
public BootstrappingDependenciesEvent(ApplicationContext source, Bundle bundle,
        Collection<OsgiServiceDependencyEvent> nestedEvents, Filter filter, long timeLeft) {
    super(source, bundle);
    Assert.notNull(nestedEvents);
    this.dependencyEvents = nestedEvents;
    this.dependenciesFilter = filter;
    this.timeLeft = timeLeft;

    List<String> depFilters = new ArrayList<String>(dependencyEvents.size());

    for (OsgiServiceDependencyEvent dependency : nestedEvents) {
        depFilters.add(dependency.getServiceDependency().getServiceFilter().toString());
    }

    dependencyFilters = Collections.unmodifiableCollection(depFilters);
}
项目:gemini.blueprint    文件:DefaultOsgiServiceDependency.java   
/**
 * Constructs a new <code>DefaultOsgiServiceDependency</code> instance.
 * 
 * @param beanName dependency bean name (can be null)
 * @param filter dependency OSGi filter (can be null)
 * @param mandatoryService flag indicating whether the dependency is
 * mandatory or not
 */
public DefaultOsgiServiceDependency(String beanName, Filter filter, boolean mandatoryService) {
    this.beanName = beanName;
    this.filter = filter;
    this.mandatoryService = mandatoryService;

    // calculate internal fields
    toString = "DependencyService[Name=" + (beanName != null ? beanName : "null") + "][Filter=" + filter
            + "][Mandatory=" + mandatoryService + "]";

    int result = 17;
    result = 37 * result + DefaultOsgiServiceDependency.class.hashCode();
    result = 37 * result + (filter == null ? 0 : filter.hashCode());
    result = 37 * result + (beanName == null ? 0 : beanName.hashCode());
    result = 37 * result + (mandatoryService ? 0 : 1);
    hashCode = result;
}
项目:liferay-devcon-2016-hystrix    文件:LiferayHystrixMetricsStreamServlet.java   
/**
 * OSGi component lifecycle listener for actication and modification of this
 * service.
 * 
 * @param componentContext
 *            OSGi component context.
 * @param properties
 *            OSGi configuration properties.
 * @throws Exception
 *             is thrown if the activation or modification of the service
 *             goes wrong.
 */
@Activate
@Modified
protected void activate(ComponentContext componentContext, Map<String, Object> properties) throws Exception {

    // Check if a service tracker for the context path exists and close it.
    if (_serviceTracker != null) {
        _serviceTracker.close();
    }

    // Create a filter for ServletContext components and start tracking.
    Filter filter = FrameworkUtil
            .createFilter("(&(objectClass=" + ServletContext.class.getName() + ")(osgi.web.contextpath=*))");

    _serviceTracker = new ServiceTracker<>(componentContext.getBundleContext(), filter, this);

    _serviceTracker.open();
}
项目:aries-rsa    文件:EndpointListenerNotifierTest.java   
@Test
public void testNotifyListener() throws InvalidSyntaxException {
    EndpointDescription endpoint1 = createEndpoint("myClass");
    EndpointDescription endpoint2 = createEndpoint("notMyClass");

    // Expect listener to be called for endpoint1 but not for endpoint2 
    EndpointListener epl = listenerExpects(endpoint1, "(objectClass=myClass)");

    EndpointRepository exportRepository = new EndpointRepository();
    EndpointListenerNotifier tm = new EndpointListenerNotifier(exportRepository);

    EasyMock.replay(epl);
    Set<Filter> filters = new HashSet<Filter>();
    filters.add(FrameworkUtil.createFilter("(objectClass=myClass)"));
    tm.add(epl, filters);
    tm.endpointAdded(endpoint1, null);
    tm.endpointAdded(endpoint2, null);
    tm.endpointRemoved(endpoint1, null);
    tm.endpointRemoved(endpoint2, null);
    EasyMock.verify(epl);
}
项目:aries-rsa    文件:EndpointListenerNotifierTest.java   
@Test
public void testNotifyListeners() throws InvalidSyntaxException {
    EndpointDescription endpoint1 = createEndpoint("myClass");

    EndpointListener epl = EasyMock.createStrictMock(EndpointListener.class);
    epl.endpointAdded(EasyMock.eq(endpoint1), EasyMock.eq("(objectClass=myClass)"));
    EasyMock.expectLastCall().once();
    epl.endpointRemoved(EasyMock.eq(endpoint1), EasyMock.eq("(objectClass=myClass)"));
    EasyMock.expectLastCall().once();

    EndpointRepository exportRepository = new EndpointRepository();
    EndpointListenerNotifier tm = new EndpointListenerNotifier(exportRepository);

    EasyMock.replay(epl);
    Set<Filter> filters = new HashSet<Filter>();
    filters.add(FrameworkUtil.createFilter("(objectClass=myClass)"));
    tm.add(epl, filters);
    tm.endpointAdded(endpoint1, null);
    tm.endpointRemoved(endpoint1, null);
    tm.remove(epl);
    EasyMock.verify(epl);
}
项目:aries-jax-rs-whiteboard    文件:TargetFilter.java   
@Override
public boolean test(CachingServiceReference<T> ref) {
    String target = (String)ref.getProperty(JAX_RS_WHITEBOARD_TARGET);

    if (target == null) {
        return true;
    }

    Filter filter;

    try {
        filter = FrameworkUtil.createFilter(target);
    }
    catch (InvalidSyntaxException ise) {
        if (_log.isErrorEnabled()) {
            _log.error("Invalid '{}' filter syntax in {}", JAX_RS_WHITEBOARD_TARGET, ref);
        }

        return false;
    }

    return filter.match(_serviceRuntimeReference);
}
项目:osgi-in-action    文件:DummyRegistry.java   
public Collection<RegistryServiceReference> findServices(String clazz, String filter) {
  ArrayList<RegistryServiceReference> refs = new ArrayList<RegistryServiceReference>();
  try {
    Filter f = filter == null ? null : ctx.createFilter(filter);

    for ( RegistryServiceReference ref : references.values() ) {
      if ( clazz == null || clazz.equals( ref.getInterface() ) ) {
        if ( f == null || f.match( new Hashtable(ref.getProperties()) ) ) {
          refs.add( ref );
        }
      }
    }
  } catch (InvalidSyntaxException e) {
    throw new IllegalStateException(e);
  }
  return refs;
}
项目:AtlasForAndroid    文件:BundleContextImpl.java   
public ServiceReference[] getServiceReferences(String str, String str2) throws InvalidSyntaxException {
    Collection collection;
    checkValid();
    Filter fromString = RFC1960Filter.fromString(str2);
    if (str == null) {
        collection = Framework.services;
    } else {
        List list = (List) Framework.classes_services.get(str);
        if (list == null) {
            return null;
        }
    }
    List arrayList = new ArrayList();
    ServiceReferenceImpl[] serviceReferenceImplArr = (ServiceReferenceImpl[]) collection.toArray(new ServiceReferenceImpl[collection.size()]);
    for (int i = 0; i < serviceReferenceImplArr.length; i++) {
        if (fromString.match(serviceReferenceImplArr[i])) {
            arrayList.add(serviceReferenceImplArr[i]);
        }
    }
    if (Framework.DEBUG_SERVICES && log.isInfoEnabled()) {
        log.info("Framework: REQUESTED SERVICES " + str + " " + str2);
        log.info("\tRETURNED " + arrayList);
    }
    return arrayList.size() == 0 ? null : (ServiceReference[]) arrayList.toArray(new ServiceReference[arrayList.size()]);
}
项目:AtlasForAndroid    文件:RFC1960Filter.java   
public boolean equals(Object obj) {
    if (!(obj instanceof RFC1960Filter)) {
        return false;
    }
    RFC1960Filter rFC1960Filter = (RFC1960Filter) obj;
    if (this.operands.size() != rFC1960Filter.operands.size()) {
        return false;
    }
    Filter[] filterArr = (Filter[]) this.operands.toArray(new Filter[this.operands.size()]);
    Filter[] filterArr2 = (Filter[]) rFC1960Filter.operands.toArray(new Filter[this.operands.size()]);
    for (int i = EQUALS; i < filterArr.length; i += PRESENT) {
        if (!filterArr[i].equals(filterArr2[i])) {
            return false;
        }
    }
    return true;
}
项目:osgi.ee    文件:Tracker.java   
/**
 * Create a tracker for a specific object/filter combination.
 *
 * @param context The bundle context. Must be the context of the bundle we are extending
 * @param type The type of the service
 * @param subfilter The sub-filter for the service
 * @param waitTime The time, in ms, to wait for a service to become available
 * @throws InvalidSyntaxException In case the filter is incorrect
 */
Tracker(BundleContext context, Class<? extends T> type, String subfilter, long waitTime) throws InvalidSyntaxException {
    // Get the wiring.
    BundleWiring wiring = Helper.getWiring(context.getBundle());
    // Get the filter from the class and the subfilter
    Filter filter = getFilter(type, subfilter);
    // Create a new proxy for this type. This proxy is used if a normal object is referenced.
    proxy = type.cast(Proxy.newProxyInstance(
            DelegatingClassLoader.from(Arrays.asList(wiring.getClassLoader(), type.getClassLoader())),
            new Class<?>[]{type},
            new Wrapper<>(this::_getService)));
    // Construct the container for the tracked services that is i.e. returned by the collections variant.
    this.services = new CopyOnWriteArrayList<>();
    this.trackedClass = type;
    this.waitTime = waitTime;
    // And start tracking the services.
    tracker = new ServiceTracker<>(context, filter, new Customizer<>(context, this.services));
    tracker.open();
}
项目:translationstudio8    文件:ConverterTracker.java   
/**
 * The Constructor.
 * @param bundleContext
 *            插件所在的 bundle context
 * @param direction
 *            取<code>Converter.DIRECTION_POSITIVE</code>或 <code>Converter.DIRECTION_REVERSE</code>
 */
public ConverterTracker(BundleContext bundleContext, String direction) {
    this.direction = direction;
    supportTypes = new ArrayList<ConverterBean>();
    this.context = bundleContext;
    String filterStr = new AndFilter(new EqFilter(Constants.OBJECTCLASS, Converter.class.getName()), new EqFilter(
            Converter.ATTR_DIRECTION, direction)).toString();
    Filter filter = null;
    try {
        filter = context.createFilter(filterStr);
    } catch (InvalidSyntaxException e) {
        // ignore the exception
        e.printStackTrace();
    }
    if (filter != null) {
        converterServiceTracker = new ServiceTracker(context, filter, new ConverterCustomizer());
    }
    converterServiceTracker.open();
}
项目:osgi-remote-jersey    文件:Activator.java   
@Override
public void start(final BundleContext context) throws Exception {
    JerseyExtenderImpl jerseyExtender = new JerseyExtenderImpl(context);
    Filter filter = FrameworkUtil.createFilter("(" + JerseyExtenderConstants.SERVICE_PROP_JERSEY_COMPONENT
            + "=true)");
    tracker = new ServiceTracker<Object, ServiceRegistration<Servlet>>(context, filter, jerseyExtender);
    tracker.open();
    jerseyExtenderSR = context.registerService(JerseyExtender.class, jerseyExtender,
            new Hashtable<String, Object>());
    JerseyExtenderWebConsolePlugin webConsolePlugin = new JerseyExtenderWebConsolePlugin(jerseyExtender);
    Hashtable<String, Object> webConsoleProps = new Hashtable<String, Object>();
    webConsoleProps.put("felix.webconsole.title", webConsolePlugin.getTitle());
    webConsoleProps.put("felix.webconsole.label", webConsolePlugin.getLabel());
    webConsolePluginSR = context.registerService(Servlet.class, webConsolePlugin, webConsoleProps);

}
项目:osgi-capability-collector    文件:AbstractCapabilityCollector.java   
private boolean areNewRequirementsSame(final RequirementDefinition<C>[] newRequirements) {
  if (newRequirements.length != suitings.length) {
    return false;
  }

  for (int i = 0, n = suitings.length; i < n; i++) {
    RequirementDefinition<C> oldRequirement = suitings[i].getRequirement();
    RequirementDefinition<C> newRequirement = newRequirements[i];
    Filter oldFilter = oldRequirement.getFilter();
    Filter newFilter = newRequirement.getFilter();
    if (oldRequirement != newRequirement
        || !oldRequirement.getRequirementId().equals(newRequirement.getRequirementId())
        || !Objects.equals(oldFilter, newFilter)
        || !oldRequirement.getAttributes().equals(newRequirement.getAttributes())) {
      return false;
    }
  }

  return true;
}
项目:osgi-capability-collector    文件:AbstractCapabilityCollector.java   
private C searchMatchingCapabilityForRequirement(final RequirementDefinition<C> requirement) {
  if (!opened) {
    return null;
  }

  C[] availableCapabilities = getAvailableCapabilities();

  if (availableCapabilities == null) {
    return null;
  }

  C matchingCapability = null;
  for (int i = 0, n = availableCapabilities.length; (i < n)
      && (matchingCapability == null); i++) {
    Filter filter = requirement.getFilter();
    if (matches(availableCapabilities[i], filter)) {
      matchingCapability = availableCapabilities[i];
    }
  }
  return matchingCapability;
}
项目:IoT-Gateway    文件:EventManager.java   
/**
 * Gets filter from an object
 *
 * @param object
 * @return filter
 */
private Filter getFilter(Object object) {
    if (object instanceof String) {
        try {
            return FrameworkUtil.createFilter((String) object);
        } catch (InvalidSyntaxException e) {
            throw new IllegalArgumentException("The filter string could not be parsed into a filter", e);
        }
    } else if (object instanceof Filter) {
        return (Filter) object;
    } else if (object == null) {
        return ALLOW_ALL;
    } else {
        throw new IllegalArgumentException("The filter must be null, string or Filter");
    }
}
项目:carbon-kernel    文件:OSGiServiceCapabilityTracker.java   
/**
 * Returns and instance of {@link Filter}.
 *
 * @param capabilityNameList all the required capability services.
 * @return LDAP like filter
 */
private Filter getORFilter(List<String> capabilityNameList) {
    StringBuilder orFilterBuilder = new StringBuilder();
    orFilterBuilder.append("(|");

    for (String service : capabilityNameList) {
        orFilterBuilder.append("(").append(OBJECT_CLASS).append("=").append(service).append(")");
    }

    orFilterBuilder.append(")");

    BundleContext bundleContext = DataHolder.getInstance().getBundleContext();
    try {
        return bundleContext.createFilter(orFilterBuilder.toString());
    } catch (InvalidSyntaxException e) {
        throw new StartOrderResolverException("Error occurred while creating the service filter", e);
    }
}
项目:tmxeditor8    文件:ConverterTracker.java   
/**
 * The Constructor.
 * @param bundleContext
 *            插件所在的 bundle context
 * @param direction
 *            取<code>Converter.DIRECTION_POSITIVE</code>或 <code>Converter.DIRECTION_REVERSE</code>
 */
public ConverterTracker(BundleContext bundleContext, String direction) {
    this.direction = direction;
    supportTypes = new ArrayList<ConverterBean>();
    this.context = bundleContext;
    String filterStr = new AndFilter(new EqFilter(Constants.OBJECTCLASS, Converter.class.getName()), new EqFilter(
            Converter.ATTR_DIRECTION, direction)).toString();
    Filter filter = null;
    try {
        filter = context.createFilter(filterStr);
    } catch (InvalidSyntaxException e) {
        // ignore the exception
        e.printStackTrace();
    }
    if (filter != null) {
        converterServiceTracker = new ServiceTracker(context, filter, new ConverterCustomizer());
    }
    converterServiceTracker.open();
}
项目:spring-osgi    文件:MandatoryServiceDependency.java   
public MandatoryServiceDependency(BundleContext bc, Filter serviceFilter, boolean isMandatory, String beanName) {
    filter = serviceFilter;
    this.filterAsString = filter.toString();
    this.isMandatory = isMandatory;
    bundleContext = bc;
    this.beanName = beanName;
    serviceDependency = new OsgiServiceDependency() {

        public String getBeanName() {
            return MandatoryServiceDependency.this.beanName;
        }

        public Filter getServiceFilter() {
            return MandatoryServiceDependency.this.filter;
        }

        public boolean isMandatory() {
            return MandatoryServiceDependency.this.isMandatory;
        }

    };
}
项目:spring-osgi    文件:AbstractOsgiServiceImportFactoryBean.java   
/**
 * Assembles the configuration properties into one unified OSGi filter. Note
 * that this implementation creates the filter on the first call and caches
 * it afterwards.
 * 
 * @return unified filter based on this factory bean configuration
 */
public Filter getUnifiedFilter() {
    if (unifiedFilter != null) {
        return unifiedFilter;
    }

    String filterWithClasses = OsgiFilterUtils.unifyFilter(interfaces, filter);

    boolean trace = log.isTraceEnabled();
    if (trace)
        log.trace("Unified classes=" + ObjectUtils.nullSafeToString(interfaces) + " and filter=[" + filter
                + "]  in=[" + filterWithClasses + "]");

    // add the serviceBeanName constraint
    String filterWithServiceBeanName = OsgiFilterUtils.unifyFilter(
        OsgiServicePropertiesResolver.BEAN_NAME_PROPERTY_KEY, new String[] { serviceBeanName }, filterWithClasses);

    if (trace)
        log.trace("Unified serviceBeanName [" + ObjectUtils.nullSafeToString(serviceBeanName) + "] and filter=["
                + filterWithClasses + "]  in=[" + filterWithServiceBeanName + "]");

    // create (which implies validation) the actual filter
    unifiedFilter = OsgiFilterUtils.createFilter(filterWithServiceBeanName);

    return unifiedFilter;
}
项目:spring-osgi    文件:DefaultOsgiServiceDependency.java   
/**
 * Constructs a new <code>DefaultOsgiServiceDependency</code> instance.
 * 
 * @param beanName dependency bean name (can be null)
 * @param filter dependency OSGi filter (can be null)
 * @param mandatoryService flag indicating whether the dependency is
 * mandatory or not
 */
public DefaultOsgiServiceDependency(String beanName, Filter filter, boolean mandatoryService) {
    this.beanName = beanName;
    this.filter = filter;
    this.mandatoryService = mandatoryService;

    // calculate internal fields
    toString = "DependencyService[Name=" + (beanName != null ? beanName : "null") + "][Filter=" + filter
            + "][Mandatory=" + mandatoryService + "]";

    int result = 17;
    result = 37 * result + DefaultOsgiServiceDependency.class.hashCode();
    result = 37 * result + (filter == null ? 0 : filter.hashCode());
    result = 37 * result + (beanName == null ? 0 : beanName.hashCode());
    result = 37 * result + (mandatoryService ? 0 : 1);
    hashCode = result;
}
项目:osgi_in_action-    文件:DummyRegistry.java   
public Collection<RegistryServiceReference> findServices(String clazz, String filter) {
  ArrayList<RegistryServiceReference> refs = new ArrayList<RegistryServiceReference>();
  try {
    Filter f = filter == null ? null : ctx.createFilter(filter);

    for ( RegistryServiceReference ref : references.values() ) {
      if ( clazz == null || clazz.equals( ref.getInterface() ) ) {
        if ( f == null || f.match( new Hashtable(ref.getProperties()) ) ) {
          refs.add( ref );
        }
      }
    }
  } catch (InvalidSyntaxException e) {
    throw new IllegalStateException(e);
  }
  return refs;
}
项目:service-jockey    文件:Rule.java   
public boolean matches(ServiceReference sr, BundleContext bc) throws Exception {
    if (getBSN() != null) {
        if (!bc.getBundle().getSymbolicName().matches(getBSN())) {
            return false;
        }
    }

    if (getBundleVersion() != null) {
        if (!bc.getBundle().getVersion().equals(getBundleVersion())) {
            return false;
        }
    }

    if (getServiceFilter() != null) {
        Filter f = bc.createFilter(getServiceFilter());
        return f.match(sr);
    } else {
        return false;
    }
}
项目:service-jockey    文件:ServiceHandlerCatalogTest.java   
public void testHideService() throws Exception {
    ServiceHandlerCatalog shc = new ServiceHandlerCatalog();
    RestrictRule r = new RestrictRule();
    r.setBSN(".*Foo");
    r.setServiceFilter("(objectClass=java.lang.String)");
    r.setExtraFilter("(test=blah)");
    shc.restrictRules.add(r);

    ServiceReference sr = mock(ServiceReference.class);
    BundleContext bc = mock(BundleContext.class);
    Bundle b = mock(Bundle.class);
    when(b.getSymbolicName()).thenReturn("TestFoo");
    when(bc.getBundle()).thenReturn(b);

    Filter filter = mock(Filter.class);
    when(filter.match(sr)).thenReturn(false);
    when(bc.createFilter("(test=blah)")).thenReturn(filter);

    Filter filter2 = mock(Filter.class);
    when(filter2.match(sr)).thenReturn(true);
    when(bc.createFilter("(objectClass=java.lang.String)")).thenReturn(filter2);

    assertTrue(shc.hideService(sr, bc));        
}
项目:service-jockey    文件:ServiceHandlerCatalogTest.java   
public void testDontHideService() throws Exception {
    ServiceHandlerCatalog shc = new ServiceHandlerCatalog();
    RestrictRule r = new RestrictRule();
    r.setServiceFilter("(objectClass=java.lang.String)");
    r.setExtraFilter("(test=blah)");
    shc.restrictRules.add(r);

    ServiceReference sr = mock(ServiceReference.class);

    BundleContext bc = mock(BundleContext.class);
    Filter filter = mock(Filter.class);
    when(filter.match(sr)).thenReturn(true);
    when(bc.createFilter("(test=blah)")).thenReturn(filter);

    Filter filter2 = mock(Filter.class);
    when(filter2.match(sr)).thenReturn(true);
    when(bc.createFilter("(objectClass=java.lang.String)")).thenReturn(filter2);

    assertFalse(shc.hideService(sr, bc));        
}
项目:fuchsia    文件:FuchsiaUtilsTest.java   
@Test
public void testGetFilterFromString() {
    Filter f = null;
    try {
        f = FuchsiaUtils.getFilter("(!(key=value))");
    } catch (InvalidFilterException e) {
        fail("GetFilter thrown an exception on a valid String filter", e);
    }
    assertThat(f).isNotNull().isInstanceOf(Filter.class);

    Map<String, Object> map = new HashMap<String, Object>();
    map.put("key", "value");
    assertThat(f.matches(map)).isFalse();

    map.clear();
    map.put("key", "not-value");
    assertThat(f.matches(map)).isTrue();

    map.clear();
    map.put("not-key", "value");
    assertThat(f.matches(map)).isTrue();
}
项目:sbt-osgi-manager    文件:RepoIndex.java   
/**
 * Constructor
 *
 * @param log
 *            the log service to use
 */
public RepoIndex(LogService log) {
    this.log = log;

    this.bundleAnalyzer = new BundleAnalyzer(log);
    this.frameworkAnalyzer = new OSGiFrameworkAnalyzer(log);
    this.scrAnalyzer = new SCRAnalyzer(log);
    this.blueprintAnalyzer = new BlueprintAnalyzer(log);

    try {
        Filter allFilter = createFilter("(name=*.jar)");

        addAnalyzer(bundleAnalyzer, allFilter);
        addAnalyzer(frameworkAnalyzer, allFilter);
        addAnalyzer(scrAnalyzer, allFilter);
        addAnalyzer(blueprintAnalyzer, allFilter);
    } catch (InvalidSyntaxException e) {
        throw new ExceptionInInitializerError("Unexpected internal error compiling filter");
    }
}
项目:sbt-osgi-manager    文件:RepoIndex.java   
public IndexResult indexFile(File file) throws Exception {
    IndexResult result = new IndexResult();
    result.resource = new JarResource(file);
    result.signature = getSignature();
    synchronized (analyzers) {
        for (Pair<ResourceAnalyzer, Filter> entry : analyzers) {
            ResourceAnalyzer analyzer = entry.getFirst();
            Filter filter = entry.getSecond();

            if (filter == null || filter.match(result.resource.getProperties())) {
                analyzer.analyzeResource(result.resource, result.capabilities, result.requirements);
            }
        }
    }
    return result;
}
项目:osgi-servicereference    文件:ReferenceTestImpl.java   
@Override
public void testExistingReference() {
    Hashtable<String, Object> properties = new Hashtable<String, Object>();
    properties.put("testservice", "true");

    @SuppressWarnings("rawtypes")
    ServiceRegistration<List> existingSR = bundleContext.registerService(List.class,
            new ArrayList<String>(Arrays.asList("Test")), properties);

    try {
        Filter filter = createTestFilter();
        Reference reference = new Reference(bundleContext, new Class<?>[] { List.class }, filter, 1);

        Assert.assertEquals(filter, reference.getFilter());

        reference.open();

        List<String> proxyInstance = reference.getProxyInstance();

        Assert.assertTrue(proxyInstance.contains("Test"));

        reference.close();
    } finally {
        existingSR.unregister();
    }
}
项目:osgi-servicereference    文件:Reference.java   
/**
 * A constructor that initializes the object and creates the necessary {@link ServiceTracker}. The {@link #open()}
 * function has to be called before using the {@link #proxyInstance}.
 * 
 * @param context
 *            The context of the bundle that needs the reference.
 * @param interfaces
 *            The interfaces that the {@link #proxyInstance} should be able to be casted.
 * @param filter
 *            The filter expression that the available services will be checked against.
 * @param timeout
 *            The timeout until the functions calls on {@link #proxyInstance} will wait if no service is available.
 */
public Reference(final BundleContext context, final Class<?>[] interfaces, final Filter filter,
        final long timeout) {
    if (filter == null) {
        throw new IllegalArgumentException("The filter parameter cannot be null");
    }
    if ((interfaces == null) || (interfaces.length == 0)) {
        throw new IllegalArgumentException("The number of required interfaces must be at least one.");
    }
    this.filter = filter;
    serviceTrackerCustomizer = new ReferenceTrackerCustomizer(context, interfaces);

    serviceTracker = new ServiceTracker<Object, Object>(context, filter, serviceTrackerCustomizer);
    referenceInvocationHandler =
            new ReferenceInvocationHandler(this, serviceTracker, filter.toString(), timeout);

    Bundle blueprintBundle = context.getBundle();
    ClassLoader classLoader = blueprintBundle.adapt(BundleWiring.class).getClassLoader();
    // TODO check if classloader is null and handle it. It could be null in case of special security circumstances.

    proxyInstance = Proxy.newProxyInstance(classLoader, interfaces,
            referenceInvocationHandler);
}
项目:target-baselines    文件:ApiToolsActivator.java   
/**
 * @return the instance Location service
 */
public Location getInstanceLocation()
{
    if (locationTracker == null)
    {
        Filter filter = null;
        try
        {
            filter = context.createFilter(Location.INSTANCE_FILTER);
        }
        catch (InvalidSyntaxException e)
        {
            // ignore this. It should never happen as we have tested the
            // above format.
        }
        locationTracker = new ServiceTracker<Location, Location>(context, filter, null);
        locationTracker.open();
    }
    return locationTracker.getService();
}
项目:aries-jpa    文件:DSFTracker.java   
static Filter createFilter(BundleContext context, String driverClass, String puName) {
    if (driverClass == null) {
        throw new IllegalArgumentException("No javax.persistence.jdbc.driver supplied in persistence.xml");
    }
    String filter = String.format("(&(objectClass=%s)(%s=%s))",
                                  DataSourceFactory.class.getName(),
                                  DataSourceFactory.OSGI_JDBC_DRIVER_CLASS,
                                  driverClass);
    LOGGER.info("Tracking DataSourceFactory for punit " + puName + " with filter " + filter);
    try {
        return context.createFilter(filter);
    } catch (InvalidSyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}
项目:aries-jpa    文件:DataSourceTracker.java   
static Filter createFilter(BundleContext context, String dsName, String puName) {
    if (dsName == null) {
        throw new IllegalArgumentException("No DataSource supplied in persistence.xml");
    }
    String subFilter = getSubFilter(dsName);
    String filter = String.format("(&(objectClass=%s)%s)",
                                  DataSource.class.getName(),
                                  subFilter);
    LOGGER.info("Tracking DataSource for punit " + puName + " with filter " + filter);
    try {
        return context.createFilter(filter);
    } catch (InvalidSyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}
项目:aries-jpa    文件:PropsConfigurationTest.java   
@SuppressWarnings("unchecked")
@Before
public void setup() throws Exception {

    when(punit.getPersistenceUnitName()).thenReturn("test-props");
    when(punit.getPersistenceProviderClassName())
        .thenReturn(ECLIPSE_PERSISTENCE_PROVIDER);
    when(punit.getTransactionType()).thenReturn(PersistenceUnitTransactionType.JTA);
    when(punit.getBundle()).thenReturn(punitBundle);
    when(punit.getProperties()).thenReturn(punitProperties);

    when(punitBundle.getBundleContext()).thenReturn(punitContext);
    when(punitBundle.getVersion()).thenReturn(Version.parseVersion("1.2.3"));

    when(containerContext.registerService(eq(ManagedService.class), 
            any(ManagedService.class), any(Dictionary.class))).thenReturn(msReg);
    when(containerContext.getService(dsfRef)).thenReturn(dsf);
    when(containerContext.getService(dsRef)).thenReturn(ds);
    when(containerContext.createFilter(Mockito.anyString()))
        .thenAnswer(new Answer<Filter>() {
            @Override
            public Filter answer(InvocationOnMock i) throws Throwable {
                return FrameworkUtil.createFilter(i.getArguments()[0].toString());
            }
        });

    when(punitContext.registerService(eq(EntityManagerFactory.class), any(EntityManagerFactory.class), 
            any(Dictionary.class))).thenReturn(emfReg);

    when(emf.isOpen()).thenReturn(true);


    Properties jdbcProps = new Properties();
    jdbcProps.setProperty("url", JDBC_URL);
    jdbcProps.setProperty("user", JDBC_USER);
    jdbcProps.setProperty("password", JDBC_PASSWORD);

    when(dsf.createDataSource(jdbcProps)).thenReturn(ds);

}
项目:neoscada    文件:ObjectPoolTracker.java   
public ObjectPoolTracker ( final BundleContext context, final String poolClass ) throws InvalidSyntaxException
{
    final Map<String, String> parameters = new HashMap<String, String> ();
    parameters.put ( ObjectPool.OBJECT_POOL_CLASS, poolClass );
    final Filter filter = FilterUtil.createAndFilter ( ObjectPool.class.getName (), parameters );

    this.poolTracker = new ServiceTracker<ObjectPool<S>, ObjectPool<S>> ( context, filter, new ServiceTrackerCustomizer<ObjectPool<S>, ObjectPool<S>> () {

        @Override
        public void removedService ( final ServiceReference<ObjectPool<S>> reference, final ObjectPool<S> service )
        {
            context.ungetService ( reference );
            ObjectPoolTracker.this.removePool ( service );
        }

        @Override
        public void modifiedService ( final ServiceReference<ObjectPool<S>> reference, final ObjectPool<S> service )
        {
            ObjectPoolTracker.this.modifyPool ( service, reference );
        }

        @Override
        public ObjectPool<S> addingService ( final ServiceReference<ObjectPool<S>> reference )
        {
            final ObjectPool<S> o = context.getService ( reference );
            ObjectPoolTracker.this.addPool ( o, reference );
            return o;
        }
    } );
}