Java Code Examples for org.osgi.framework.Filter#match()

The following examples show how to use org.osgi.framework.Filter#match() . 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: BundleLocationCondition.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 2
Source File: BundleLocationCondition.java    From concierge with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example 3
Source File: ReferenceListener.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 *
 */
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));
}
 
Example 4
Source File: CMCommands.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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()]);
}
 
Example 5
Source File: BundleLocationCondition.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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;
}
 
Example 6
Source File: BundleContextImpl.java    From AtlasForAndroid with MIT License 6 votes vote down vote up
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()]);
}
 
Example 7
Source File: ApplicationAdminPermission.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Checks if the specified {@code permission} is implied by this permission.
 * The method returns true under the following conditions:
 * <ul>
 * <li>This permission was created by specifying a filter (see
 * {@link #ApplicationAdminPermission(String, String)})</li>
 * <li>The implied {@code otherPermission} was created for a particular
 * {@link ApplicationDescriptor} (see
 * {@link #ApplicationAdminPermission(ApplicationDescriptor, String)})</li>
 * <li>The {@code filter} of this permission matches the
 * {@code ApplicationDescriptor} specified in the {@code otherPermission}.
 * If the filter in this permission is the {@code <<SELF>>} pseudo target,
 * then the currentApplicationId set in the {@code otherPermission} is
 * compared to the application Id of the target
 * {@code ApplicationDescriptor}.</li>
 * <li>The list of permitted actions in this permission contains all actions
 * required in the {@code otherPermission}</li>
 * </ul>
 * Otherwise the method returns false.
 * 
 * @param otherPermission the implied permission
 * @return true if this permission implies the {@code otherPermission},
 *         false otherwise.
 */
public boolean implies(Permission otherPermission) {
	if (otherPermission == null)
		return false;

	if (!(otherPermission instanceof ApplicationAdminPermission))
		return false;

	ApplicationAdminPermission other = (ApplicationAdminPermission) otherPermission;

	if (!filter.equals("*")) {
		if (other.applicationDescriptor == null)
			return false;

		if (filter.equals("<<SELF>>")) {
			if (other.applicationID == null)
				return false; /* it cannot be, this might be a bug */

			if (!other.applicationID.equals(other.applicationDescriptor.getApplicationId()))
				return false;
		} else {
			Hashtable props = new Hashtable();
			props.put("pid", other.applicationDescriptor.getApplicationId());
			props.put("signer", new SignerWrapper(other.applicationDescriptor));

			Filter flt = getFilter();
			if (flt == null)
				return false;

			if (!flt.match(props))
				return false;
		}
	}

	if (!actionsVector.containsAll(other.actionsVector))
		return false;

	return true;
}
 
Example 8
Source File: Concierge.java    From concierge with Eclipse Public License 1.0 4 votes vote down vote up
private final ServiceReference<?>[] getServiceReferences(
		final String clazz, final String filter, final boolean all)
				throws InvalidSyntaxException {
	checkValid();

	final Filter theFilter = RFC1960Filter.fromString(filter);
	final Collection<ServiceReference<?>> references;

	if (clazz == null) {
		references = serviceRegistry.getAllValues();
	} else {
		references = serviceRegistry.get(clazz);
	}

	final List<ServiceReference<?>> result = new ArrayList<ServiceReference<?>>();

	if (references != null) {
		final ServiceReferenceImpl<?>[] refs = references
				.toArray(new ServiceReferenceImpl[references.size()]);

		for (int i = 0; i < refs.length; i++) {
			if (theFilter.match(refs[i]) && (all
					|| refs[i].isAssignableTo(bundle, (String[]) refs[i]
							.getProperty(Constants.OBJECTCLASS)))) {
				result.add(refs[i]);
			}
		}
	}

	if (!serviceFindHooks.isEmpty()) {
		final Collection<ServiceReference<?>> c = new ConciergeCollections.RemoveOnlyList<ServiceReference<?>>(
				result);
		for (final Iterator<ServiceReferenceImpl<FindHook>> iter = serviceFindHooks
				.iterator(); iter.hasNext();) {
			final ServiceReferenceImpl<FindHook> hookRef = iter.next();
			final FindHook hook = getService(hookRef);
			try {
				hook.find(this, clazz, filter, all, c);
			} catch (final Throwable t) {
				notifyFrameworkListeners(FrameworkEvent.ERROR,
						Concierge.this, t);
			}
			ungetService(hookRef);
		}

		if(this != Concierge.this.context) {
			return c.size() == 0 ? null
				: (ServiceReference[]) c
						.toArray(new ServiceReference[c.size()]);
		}
	}

	if (LOG_ENABLED && DEBUG_SERVICES) {
		logger.log(LogService.LOG_INFO,
				"Framework: REQUESTED SERVICES "
						+ (clazz == null ? "(no class)" : clazz) + " "
						+ (filter == null ? "(no filter)"
								: "filter=" + filter));
		logger.log(LogService.LOG_INFO, "\tRETURNED " + result);
	}

	return result.size() == 0 ? null
			: (ServiceReference[]) result
					.toArray(new ServiceReference[result.size()]);
}
 
Example 9
Source File: ConfigurationAdminFactory.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
Configuration[] listConfigurations(String filterString,
                                   Bundle callingBundle,
                                   boolean activeOnly)
    throws IOException, InvalidSyntaxException
{
  final Enumeration<Object> configurationPids = store.listPids();
  final Vector<ConfigurationImpl> matchingConfigurations =
    new Vector<ConfigurationImpl>();
  final Filter filter =
    filterString == null ? null : Activator.bc.createFilter(filterString);
  while (configurationPids.hasMoreElements()) {
    final String pid = (String) configurationPids.nextElement();
    ConfigurationDictionary d;
    try {
      d = load(pid, null);
    } catch (IOException e) {
      continue;
    }
    if (d == null) {
      continue;
    }
    if (activeOnly && d.isNullDictionary()) {
      continue;
    }
    if (filter == null || filter.match(d)) {
      String configurationLocation = d.getLocation();
      configurationLocation =
        configurationLocation == null ? "*" : configurationLocation;
      if ((System.getSecurityManager() == null)
          || (callingBundle == null)
          || (callingBundle.getLocation().equals(configurationLocation))
          || (callingBundle
              .hasPermission(new ConfigurationPermission(
                                                         configurationLocation,
                                                         ConfigurationPermission.CONFIGURE)))) {
        matchingConfigurations
            .addElement(new ConfigurationImpl(callingBundle, d));
      }
    }
  }
  Configuration[] c = null;
  if (matchingConfigurations.size() > 0) {
    c = new Configuration[matchingConfigurations.size()];
    matchingConfigurations.copyInto(c);
  }
  return c;
}