下面列出了org.osgi.framework.ServiceListener#org.osgi.framework.Filter 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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 () );
}
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;
}
}
/**
* Constructs a condition that tries to match the passed Bundle's location
* to the location pattern.
*
* @param bundle The Bundle being evaluated.
* @param info The ConditionInfo from which to construct the condition. The
* ConditionInfo must specify one or two arguments. The first
* argument of the ConditionInfo specifies the location pattern
* against which to match the bundle location. Matching is done
* according to the filter string matching rules. Any '*' characters
* in the first argument are used as wildcards when matching bundle
* locations unless they are escaped with a '\' character. The
* Condition is satisfied if the bundle location matches the pattern.
* The second argument of the ConditionInfo is optional. If a second
* argument is present and equal to "!", then the satisfaction of the
* Condition is negated. That is, the Condition is satisfied if the
* bundle location does NOT match the pattern. If the second argument
* is present but does not equal "!", then the second argument is
* ignored.
* @return Condition object for the requested condition.
*/
static public Condition getCondition(final Bundle bundle, final ConditionInfo info) {
if (!CONDITION_TYPE.equals(info.getType()))
throw new IllegalArgumentException("ConditionInfo must be of type \"" + CONDITION_TYPE + "\"");
String[] args = info.getArgs();
if (args.length != 1 && args.length != 2)
throw new IllegalArgumentException("Illegal number of args: " + args.length);
String bundleLocation = AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return bundle.getLocation();
}
});
Filter filter = null;
try {
filter = FrameworkUtil.createFilter("(location=" + escapeLocation(args[0]) + ")");
} catch (InvalidSyntaxException e) {
// this should never happen, but just in case
throw new RuntimeException("Invalid filter: " + e.getFilter(), e);
}
Dictionary<String, String> matchProps = new Hashtable<String, String>(2);
matchProps.put("location", bundleLocation);
boolean negate = (args.length == 2) ? "!".equals(args[1]) : false;
return (negate ^ filter.match(matchProps)) ? Condition.TRUE : Condition.FALSE;
}
/**
* creates a new EventHandlerSubscription instance.
*
* @param handler
* an <code>EventHandler</code> that wants to subscribe.
* @param topics
* an array of strings representing the topics.
* @param filter
* a <code>Filter</code> for matching event properties.
*/
Subscription(final EventHandler eventHandler, final String[] topics,
final Filter filter) {
// security check
if (EventAdminImpl.security != null) {
ArrayList checkedTopics = new ArrayList(topics.length);
for (int i = 0; i < topics.length; i++) {
try {
EventAdminImpl.security
.checkPermission(new TopicPermission(topics[i],
TopicPermission.SUBSCRIBE));
checkedTopics.add(topics[i]);
} catch (SecurityException se) {
System.err
.println("Bundle does not have permission for subscribing to "
+ topics[i]);
}
}
this.topics = (String[]) checkedTopics
.toArray(new String[checkedTopics.size()]);
} else {
this.topics = topics;
}
this.handler = eventHandler;
this.filter = filter;
}
@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();
}
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;
}
/**
* check if the filter equals another object.
*
* @param obj
* the other object.
* @return true if the object is an instance of RFC1960Filter and the
* filters are equal.
* @see java.lang.Object#equals(java.lang.Object)
* @category Object
*/
public boolean equals(final Object obj) {
if (obj instanceof RFC1960Filter) {
final RFC1960Filter filter = (RFC1960Filter) obj;
if (operands.size() != filter.operands.size()) {
return false;
}
final Filter[] operandArray = operands
.toArray(new Filter[operands.size()]);
final Filter[] operandArray2 = filter.operands
.toArray(new Filter[operands.size()]);
for (int i = 0; i < operandArray.length; i++) {
if (!operandArray[i].equals(operandArray2[i])) {
return false;
}
}
return true;
}
return false;
}
/**
* Constructs a condition that tries to match the passed Bundle's location
* to the location pattern.
*
* @param bundle The Bundle being evaluated.
* @param info The ConditionInfo from which to construct the condition. The
* ConditionInfo must specify one or two arguments. The first
* argument of the ConditionInfo specifies the location pattern
* against which to match the bundle location. Matching is done
* according to the filter string matching rules. Any '*' characters
* in the first argument are used as wildcards when matching bundle
* locations unless they are escaped with a '\' character. The
* Condition is satisfied if the bundle location matches the pattern.
* The second argument of the ConditionInfo is optional. If a second
* argument is present and equal to "!", then the satisfaction of the
* Condition is negated. That is, the Condition is satisfied if the
* bundle location does NOT match the pattern. If the second argument
* is present but does not equal "!", then the second argument is
* ignored.
* @return Condition object for the requested condition.
*/
static public Condition getCondition(final Bundle bundle, final ConditionInfo info) {
if (!CONDITION_TYPE.equals(info.getType()))
throw new IllegalArgumentException("ConditionInfo must be of type \"" + CONDITION_TYPE + "\"");
String[] args = info.getArgs();
if (args.length != 1 && args.length != 2)
throw new IllegalArgumentException("Illegal number of args: " + args.length);
String bundleLocation = AccessController.doPrivileged(new PrivilegedAction<String>() {
public String run() {
return bundle.getLocation();
}
});
Filter filter = null;
try {
filter = FrameworkUtil.createFilter("(location=" + escapeLocation(args[0]) + ")");
} catch (InvalidSyntaxException e) {
// this should never happen, but just in case
throw new RuntimeException("Invalid filter: " + e.getFilter(), e);
}
Dictionary<String, String> matchProps = new Hashtable<String, String>(2);
matchProps.put("location", bundleLocation);
boolean negate = (args.length == 2) ? "!".equals(args[1]) : false;
return (negate ^ filter.match(matchProps)) ? Condition.TRUE : Condition.FALSE;
}
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception
{
bundleContext = mock(BundleContext.class);
doThrow(new InvalidSyntaxException("", "")).when(bundleContext).createFilter(anyString());
Filter filter = mock(Filter.class);
when(filter.toString()).thenReturn(OSGI_FILTER);
doReturn(filter).when(bundleContext).createFilter(OSGI_FILTER);
when(bundleContext.getServiceReferences(eq(Service.class.getName()), anyString())).thenReturn(new ServiceReference[]{mock(ServiceReference.class)});
when(bundleContext.getService(any(ServiceReference.class))).thenReturn(mock(Service.class));
mapper = JsonMapper.builder()
.addModule(new OsgiJacksonModule(bundleContext))
.build();
}
/**
* 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);
}
}
private void addToProvidersIfMatching(Resource res, List<Capability> providers, Requirement req) {
String f = req.getDirectives().get(Namespace.REQUIREMENT_FILTER_DIRECTIVE);
Filter filter = null;
if(f != null) {
try {
filter = bc.createFilter(f);
} catch (InvalidSyntaxException e) {
// TODO log filter failure, skip
System.err.println("Failed, " + f + ". " + e);
return;
}
}
for(Capability c : res.getCapabilities(req.getNamespace())) {
if(filter != null && !filter.matches(c.getAttributes())) {
continue;
}
providers.add(c);
}
}
/**
* Internal implies method. Used by the implies and the permission
* collection implies methods.
*
* @param requested The requested EndpointPermission which has already be
* validated as a proper argument. The requested EndpointPermission
* must not have a filter expression.
* @param effective The effective actions with which to start.
* @return {@code true} if the specified permission is implied by this
* object; {@code false} otherwise.
*/
boolean implies0(EndpointPermission requested, int effective) {
/* check actions first - much faster */
effective |= action_mask;
final int desired = requested.action_mask;
if ((effective & desired) != desired) {
return false;
}
/* if we have no filter */
Filter f = filter;
if (f == null) {
// it's "*"
return true;
}
return f.matchCase(requested.getProperties());
}
/**
*
*/
void serviceEvent(ServiceReference<?> s, ServiceEvent se) {
Filter f = getTargetFilter();
boolean match = f == null || f.match(s);
if (match && ReferenceDescription.SCOPE_PROTOTYPE_REQUIRED.equals(ref.getScope())) {
match = Constants.SCOPE_PROTOTYPE.equals(s.getProperty(Constants.SERVICE_SCOPE));
}
int type = se.getType();
if (!match) {
if (type != ServiceEvent.UNREGISTERING && serviceRefs.contains(s)) {
type = ServiceEvent.MODIFIED_ENDMATCH;
} else {
return;
}
}
serviceChanged(new RefServiceEvent(type, s, se));
}
/**
* Get filter string for finding this reference.
*/
private String getFilter() {
final Filter target = getTargetFilter();
boolean addScope = ReferenceDescription.SCOPE_PROTOTYPE_REQUIRED.equals(ref.getScope());
if (addScope || target != null) {
StringBuilder sb = new StringBuilder("(&(");
sb.append(Constants.OBJECTCLASS).append('=').append(getInterface()).append(')');
if (addScope) {
sb.append('(').append(Constants.SERVICE_SCOPE).append('=').append(Constants.SCOPE_PROTOTYPE).append(')');
}
if (target != null) {
sb.append(target);
}
sb.append(')');
return sb.toString();
} else {
return "(" + Constants.OBJECTCLASS + "=" + getInterface() +")";
}
}
/**
* 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();
}
private Configuration[] getConfigurationsMatchingFilters(ConfigurationAdmin cm,
Filter[] filters)
throws Exception
{
final Configuration[] cs = cm.listConfigurations(null);
if (cs == null || cs.length == 0) {
return new Configuration[0];
}
if (filters == null || filters.length == 0) {
return cs;
}
final List<Configuration> matching = new ArrayList<Configuration>();
for (final Configuration cfg : cs) {
for (final Filter filter : filters) {
if (filter.match(cfg.getProperties())) {
matching.add(cfg);
break;
}
}
}
return matching.toArray(new Configuration[matching.size()]);
}
/**
* Create an import package entry.
*/
ImportPkg(ExportPkg p) {
this.name = p.name;
this.bpkgs = p.bpkgs;
this.resolution = Constants.RESOLUTION_MANDATORY;
this.bundleSymbolicName = null;
if (p.version == Version.emptyVersion) {
this.packageRange = null;
} else {
this.packageRange = new VersionRange(p.version.toString());
}
this.bundleRange = null;
this.attributes = p.attributes;
// TODO, should we import unknown directives?
final Map<String,String> dirs = new HashMap<String, String>();
final Filter filter = toFilter();
if (null!=filter) {
dirs.put(Constants.FILTER_DIRECTIVE, filter.toString());
}
this.directives = Collections.unmodifiableMap(dirs);
this.parent = null;
}
private static Filter buildFilter() {
Filter filter;
String stringFilter = String.format("(&(port=*)(node=*)(endpoint=*))");
try {
filter = FuchsiaUtils.getFilter(stringFilter);
} catch (InvalidFilterException e) {
e.printStackTrace();
throw new IllegalStateException(e);
}
return filter;
}
@Test
public void testIDecPropFilterFail() {
DefaultExportationLinker il = new DefaultExportationLinker(bundleContext);
il.start();
setProperties(il, "TestedLinker", "(scope=generic", "(instance.name=TestExporter)");
assertThat(il.getName()).isEqualTo("TestedLinker");
il.updated();
Filter exportDeclarationFilter = field("exportDeclarationFilter").ofType(Filter.class).in(il).get();
assertThat(exportDeclarationFilter).isNull();
assertThat(field("state").ofType(boolean.class).in(il).get()).isFalse();
}
@SuppressWarnings("unchecked")
public Collection<BundleCapability> findProviders(Requirement requirement) {
final String namespace = requirement.getNamespace();
final String filterStr = requirement.getDirectives().get("filter");
Filter filter;
if (filterStr != null) {
try {
filter = FrameworkUtil.createFilter(filterStr);
} catch (InvalidSyntaxException ise) {
final String msg = "Invalid filter directive '" + filterStr + "': " + ise;
throw new IllegalArgumentException(msg, ise);
}
} else {
filter = null;
}
HashSet<BundleCapability> res = new HashSet<BundleCapability>();
for (BundleGeneration bg : fwCtx.bundles.getBundleGenerations(null)) {
BundleRevisionImpl bri = bg.bundleRevision;
if (bri != null) {
for (BundleCapability bc : bri.getDeclaredCapabilities(namespace)) {
if (null == filter || filter.matches(bc.getAttributes())) {
res.add(bc);
}
}
}
}
return res;
}
protected static Filter createFilter ( final String operand, final Map<String, String> parameters ) throws InvalidSyntaxException
{
final StringBuilder sb = new StringBuilder ();
sb.append ( "(" );
sb.append ( operand );
for ( final Map.Entry<String, String> entry : parameters.entrySet () )
{
addPair ( sb, entry.getKey (), entry.getValue () );
}
sb.append ( ")" );
return FrameworkUtil.createFilter ( sb.toString () );
}
@Test
public void testIServPropFilterFail() {
DefaultImportationLinker il = new DefaultImportationLinker(bundleContext);
il.start();
setProperties(il, "TestedLinker", "(scope=generic)", "(instance.name=TestImporter");
assertThat(il.getName()).isEqualTo("TestedLinker");
il.updated();
Filter importerServiceFilter = field("importerServiceFilter").ofType(Filter.class).in(il).get();
assertThat(importerServiceFilter).isNull();
assertThat(field("state").ofType(boolean.class).in(il).get()).isFalse();
}
private static Filter buildFilter() {
Filter filter;
String stringFilter = String.format("(&(%s=*)(%s=*)(%s=*))",
ID, FUCHSIA_EXPORT_JSONRPC_CLASS, FUCHSIA_EXPORT_JSONRPC_INSTANCE);
try {
filter = FuchsiaUtils.getFilter(stringFilter);
} catch (InvalidFilterException e) {
throw new IllegalStateException(e);
}
return filter;
}
public AbstractConnectionManager ( final BundleContext context, final ConnectionInformation connectionInformation, final String connectionId, final Integer autoReconnectDelay, final boolean initialOpen )
{
super ();
this.context = context;
this.connectionInformation = connectionInformation;
this.connectionId = connectionId;
this.autoReconnectDelay = autoReconnectDelay;
this.initialOpen = initialOpen;
final String interfaceName = this.connectionInformation.getInterface ();
final String driverName = this.connectionInformation.getDriver ();
Filter filter;
try
{
final Map<String, String> parameters = new HashMap<String, String> ();
parameters.put ( DriverFactory.INTERFACE_NAME, interfaceName );
parameters.put ( DriverFactory.DRIVER_NAME, driverName );
filter = FilterUtil.createAndFilter ( DriverFactory.class.getName (), parameters );
logger.debug ( "Created filter: {}", filter );
}
catch ( final InvalidSyntaxException e )
{
filter = null;
logger.warn ( "Failed to create filter", e );
}
if ( filter != null )
{
this.tracker = new SingleServiceTracker<DriverFactory> ( this.context, filter, this );
this.tracker.open ();
}
else
{
this.tracker = null;
}
}
public EventProcessor ( final Filter filter, final BundleContext context )
{
this.filter = filter;
this.context = context;
this.tracker = new SingleServiceTracker<EventService> ( this.context, this.filter, new SingleServiceListener<EventService> () {
@Override
public void serviceChange ( final ServiceReference<EventService> reference, final EventService service )
{
EventProcessor.this.setService ( service );
}
} );
}
private static Filter buildFilter() {
Filter filter;
String stringFilter = String.format("(&(%s=*)(%s=*)(%s=*))", ID, CXF_EXPORT_TYPE, CXF_EXPORT_WEB_CONTEXT);
try {
filter = FuchsiaUtils.getFilter(stringFilter);
} catch (InvalidFilterException e) {
throw new IllegalStateException(e);
}
return filter;
}
Location getInstanceLocation() {
if (instanceLocationTracker == null) {
Filter filter;
try {
filter = bundleContext.createFilter(Location.INSTANCE_FILTER);
} catch (InvalidSyntaxException e) {
LogHelper.log(e);
return null;
}
instanceLocationTracker = new ServiceTracker<Location, Location>(bundleContext, filter, null);
instanceLocationTracker.open();
}
return instanceLocationTracker.getService();
}
Filter getAuthFilter() throws InvalidSyntaxException {
StringBuilder sb = new StringBuilder("("); //$NON-NLS-1$
sb.append(ServerConstants.CONFIG_AUTH_NAME);
sb.append('=');
sb.append(getAuthName());
sb.append(')');
return FrameworkUtil.createFilter(sb.toString());
}
public ServiceReferenceFilteredPublisher(
Publisher<? super CachingServiceReference<?>> publisher,
Filter filter) {
_publisher = publisher;
_filter = filter;
}
public Collection<ServiceReferenceDTO> getServiceReferences(String filter) throws InvalidSyntaxException {
Filter f = context.createFilter(filter);
List<ServiceReferenceDTO> filtered = new ArrayList<ServiceReferenceDTO>();
for(ServiceReferenceDTO r : getServiceReferences()){
if(f.matches(r.properties)){
filtered.add(r);
}
}
return filtered;
}