org.osgi.framework.VersionRange Java Examples

The following examples show how to use org.osgi.framework.VersionRange. 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: BundleUpgradeParserTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
@Test
public void testVersionRangesWithSnapshots() throws Exception {
    VersionRange from0lessThan1 = VersionRangedName.fromString("foo:[0,1)", false).getOsgiVersionRange();
    assertTrue(from0lessThan1.includes(Version.valueOf("0.1.0.SNAPSHOT")));
    assertTrue(from0lessThan1.includes(Version.valueOf(BrooklynVersionSyntax.toValidOsgiVersion("0.1.0-SNAPSHOT"))));
    assertTrue(from0lessThan1.includes(Version.valueOf("0.0.0.SNAPSHOT")));
    assertTrue(from0lessThan1.includes(Version.valueOf(BrooklynVersionSyntax.toValidOsgiVersion("0.0.0-SNAPSHOT"))));
    assertFalse(from0lessThan1.includes(Version.valueOf("1.0.0.SNAPSHOT")));
    assertFalse(from0lessThan1.includes(Version.valueOf(BrooklynVersionSyntax.toValidOsgiVersion("1.0.0-SNAPSHOT"))));
    
    VersionRange from1 = VersionRangedName.fromString("foo:[1,9999)", false).getOsgiVersionRange();
    assertTrue(from1.includes(Version.valueOf("1.0.0.SNAPSHOT")));
    assertTrue(from1.includes(Version.valueOf(BrooklynVersionSyntax.toValidOsgiVersion("1.SNAPSHOT"))));
    assertFalse(from1.includes(Version.valueOf("0.0.0.SNAPSHOT")));
    assertFalse(from1.includes(Version.valueOf("0.1.0.SNAPSHOT")));
}
 
Example #2
Source File: InstallableUnitTest.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
static private final Matcher<InstallableUnit> hasRequired ( final String namespace, final String name, final String versionRange, final boolean isOptional, final Boolean greedy, final String filter )
{
    return new CustomTypeSafeMatcher<InstallableUnit> ( "IU with 'required'-element [namespace= " + namespace + ", name= " + name + ", versionRange= " + versionRange + " ]" ) {

        @Override
        protected boolean matchesSafely ( final InstallableUnit item )
        {
            final List<Entry<org.eclipse.packagedrone.repo.aspect.common.p2.InstallableUnit.Requirement>> requires = item.getRequires ();
            for ( final Entry<org.eclipse.packagedrone.repo.aspect.common.p2.InstallableUnit.Requirement> require : requires )
            {

                if ( Objects.equals ( require.getNamespace (), namespace ) && Objects.equals ( require.getKey (), name ) )
                {
                    final org.eclipse.packagedrone.repo.aspect.common.p2.InstallableUnit.Requirement value = require.getValue ();
                    if ( Objects.equals ( value.getRange (), VersionRange.valueOf ( versionRange ) ) && Objects.equals ( value.getFilter (), filter ) && Objects.equals ( value.getGreedy (), greedy ) )
                    {
                        return true;
                    }
                }
            }
            return false;
        }
    };
}
 
Example #3
Source File: NativeRequirement.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
NativeCodeEntry(List<String> files, List<String> procs, List<String> oses, List<String> vers, List<String> langs, String sf)
  throws InvalidSyntaxException
{
  this.files = files;
  matchLang = langs != null;
  if (vers != null) {
    Version mv = null;
    List<VersionRange> vrs = new ArrayList<VersionRange>(vers.size());
    for (String s : vers) {
      VersionRange vr = new VersionRange(s);
      if (mv == null || mv.compareTo(vr.getLeft()) > 0) {
        mv = vr.getLeft();
      }
      vrs.add(vr);
    }
    minVersion = mv;
    filter = toFilter(procs, oses, vrs, langs, sf);
  } else {
    minVersion = null;
    filter = toFilter(procs, oses, null, langs, sf);
  }
}
 
Example #4
Source File: NativeRequirement.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private String orString(String key, List<?> vals) {
  if (vals == null) {
    return null;
  }
  final StringBuffer sb = new StringBuffer(80);
  if (vals.size() > 1) {
    sb.append("(|");
  }
  for (Object v : vals) {
    if (v instanceof VersionRange) {
      sb.append(((VersionRange)v).toFilterString(key));
    } else {
      sb.append('(');
      sb.append(key);
      sb.append("~=");
      sb.append(v.toString());
      sb.append(')');
    }
  }
  if (vals.size() > 1) {
    sb.append(')');
  }
  return sb.toString();
}
 
Example #5
Source File: NativeRequirement.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Filter toFilter(List<String> procs, List<String> oses, List<VersionRange> vers, List<String> langs, String sf)
  throws InvalidSyntaxException
{
  final StringBuffer sb = new StringBuffer(80);
  int elems = 0;
  
  elems = andAdd(sb, orString(NativeNamespace.CAPABILITY_PROCESSOR_ATTRIBUTE, procs));
  elems += andAdd(sb, orString(NativeNamespace.CAPABILITY_OSNAME_ATTRIBUTE, oses));
  elems += andAdd(sb, orString(NativeNamespace.CAPABILITY_OSVERSION_ATTRIBUTE, vers));
  elems += andAdd(sb, orString(NativeNamespace.CAPABILITY_LANGUAGE_ATTRIBUTE, langs));
  elems += andAdd(sb, sf);
  if (elems == 0) {
    return null;
  } else if (elems > 1) {
    sb.insert(0,"(&");
    sb.append(")");
  }
  return FrameworkUtil.createFilter(sb.toString());
}
 
Example #6
Source File: InstallableUnitTest.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
@Test
public void fragmentSpecificPropertiesAddedToIU () throws Exception
{
    final boolean notOptional = false;
    final Boolean nullGreedyBoolean = null;
    final String noFilter = null;
    final String hostBundleName = "org.host.bundle";
    final String ownVersion = "1.0.7";
    final String hostVersionRange = "[1.0.1,2.0.0)";
    final VersionRangedName hostBundle = new VersionRangedName ( hostBundleName, VersionRange.valueOf ( hostVersionRange ) );
    final BundleInformation bi = new BundleInformation ();
    bi.setFragmentHost ( hostBundle );
    bi.setVersion ( Version.parseVersion ( ownVersion ) );
    final P2MetaDataInformation p2info = new P2MetaDataInformation ();

    final InstallableUnit iu = InstallableUnit.fromBundle ( bi, p2info );

    assertThat ( iu, hasProvided ( "osgi.fragment", hostBundleName, ownVersion ) );
    assertThat ( iu, hasRequired ( "osgi.bundle", hostBundleName, hostVersionRange, notOptional, nullGreedyBoolean, noFilter ) );
    final String fragmentHostEntry = Constants.FRAGMENT_HOST + ": " + hostBundleName + ";" + Constants.BUNDLE_VERSION_ATTRIBUTE + "=\"" + hostVersionRange + "\"";
    final Map<String, String> touchpointInstructions = iu.getTouchpoints ().get ( 0 ).getInstructions ();
    assertThat ( touchpointInstructions, hasEntry ( "manifest", containsString ( fragmentHostEntry ) ) );
}
 
Example #7
Source File: ImportPkg.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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;
}
 
Example #8
Source File: InstallableUnit.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
private static String makeManifest ( final BundleInformation bundle ) throws IOException
{
    final Manifest mf = new Manifest ();
    mf.getMainAttributes ().put ( Attributes.Name.MANIFEST_VERSION, "1.0" );
    mf.getMainAttributes ().putValue ( Constants.BUNDLE_SYMBOLICNAME, bundle.getId () + ( bundle.isSingleton () ? ";" + SINGLETON_DIRECTIVE + ":=true" : "" ) );
    mf.getMainAttributes ().putValue ( Constants.BUNDLE_VERSION, "" + bundle.getVersion () );

    final VersionRangedName fragmentHost = bundle.getFragmentHost ();
    if ( fragmentHost != null && fragmentHost.getName () != null )
    {
        final String name = fragmentHost.getName ();
        final Optional<VersionRange> version = Optional.ofNullable ( fragmentHost.getVersionRange () );
        final Optional<String> versionStr = version.map ( vr -> ";" + Constants.BUNDLE_VERSION_ATTRIBUTE + "=\"" + vr.toString () + "\"" );
        mf.getMainAttributes ().putValue ( Constants.FRAGMENT_HOST, name + versionStr.orElse ( "" ) );
    }

    final ByteArrayOutputStream out = new ByteArrayOutputStream ();
    mf.write ( out );
    out.close ();
    return out.toString ( "UTF-8" );
}
 
Example #9
Source File: Bundles.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Get all bundles that has specified bundle symbolic name and
 * version range. Result is sorted in decreasing version order.
 *
 * @param name The symbolic name of bundles to get.
 * @param range Version range of bundles to get.
 * @return A List of current BundleGenerations.
 */
List<BundleGeneration> getBundles(String name, VersionRange range) {
  checkIllegalState();
  final List<BundleGeneration> res = getBundleGenerations(name);
  for (int i = 0; i < res.size(); ) {
    final BundleGeneration bg = res.remove(i);
    if (range == null || range.includes(bg.version)) {
      int j = i;
      while (--j >= 0) {
        if (bg.version.compareTo(res.get(j).version) <= 0) {
          break;
        }
      }
      res.add(j + 1, bg);
      i++;
    }
  }
  return res;
}
 
Example #10
Source File: PackageAdminImpl.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Bundle[] getBundles(String symbolicName, String versionRange) {
  final VersionRange vr = versionRange != null ? new VersionRange(versionRange.trim()) :
      null;
  final List<BundleGeneration> bgs = fwCtx.bundles.getBundles(symbolicName, vr);
  final int size = bgs.size();
  if (size > 0) {
    final Bundle[] res = new Bundle[size];
    final Iterator<BundleGeneration> i = bgs.iterator();
    for (int pos = 0; pos < size;) {
      res[pos++] = i.next().bundle;
    }
    return res;
  } else {
    return null;
  }
}
 
Example #11
Source File: BundleUpgradeParserTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseForceRemoveLegacyItemsHeader() throws Exception {
    Bundle bundle = newMockBundle(new VersionedName("mybundle", "1.0.0"));
    Supplier<Iterable<RegisteredType>> typeSupplier = Suppliers.ofInstance(ImmutableList.of(
            newMockRegisteredType("foo", "1.0.0"),
            newMockRegisteredType("bar", "1.0.0")));
    
    assertParseForceRemoveLegacyItemsHeader("\"foo:0.1.0\"", bundle, typeSupplier, ImmutableList.of(new VersionRangedName("foo", exactly0dot1)));
    assertParseForceRemoveLegacyItemsHeader("\"*\"", bundle, typeSupplier, ImmutableList.of(new VersionRangedName("foo", from0lessThan1), new VersionRangedName("bar", from0lessThan1)));
    assertParseForceRemoveLegacyItemsHeader("*", bundle, typeSupplier, ImmutableList.of(new VersionRangedName("foo", from0lessThan1), new VersionRangedName("bar", from0lessThan1)));
    assertParseForceRemoveLegacyItemsHeader("*:1.0.0.SNAPSHOT, \"foo:[0.1,1)", bundle, typeSupplier, 
        ImmutableList.of(new VersionRangedName("foo", VersionRange.valueOf("[1.0.0.SNAPSHOT,1.0.0.SNAPSHOT]")), new VersionRangedName("bar", VersionRange.valueOf("[1.0.0.SNAPSHOT,1.0.0.SNAPSHOT]")), 
            new VersionRangedName("foo", VersionRange.valueOf("[0.1,1)"))));
}
 
Example #12
Source File: PackageAdminImpl.java    From concierge with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * @see org.osgi.service.packageadmin.PackageAdmin#getBundles(java.lang.String,
 *      java.lang.String)
 */
public Bundle[] getBundles(final String symbolicName, final String versionRange) {
	if (symbolicName == null) {
		throw new IllegalArgumentException("symbolicName is null");
	}

	final VersionRange range = versionRange == null ? null : new VersionRange(versionRange);

	final Bundle[] bundles = context.getBundles();
	final ArrayList<Bundle> result = new ArrayList<Bundle>();

	for (final Bundle bundle : bundles) {
		if (symbolicName.equals(bundle.getSymbolicName())) {
			if (range == null || range.includes(bundle.getVersion())) {
				result.add(bundle);
			}
		}
	}

	if (result.isEmpty()) {
		return null;
	}

	Collections.sort(result, new Comparator<Bundle>() {
		public int compare(final Bundle b1, final Bundle b2) {
			return b2.getVersion().compareTo(b1.getVersion());
		}
	});

	return result.toArray(new Bundle[result.size()]);
}
 
Example #13
Source File: BundleUpgradeParserTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseForceRemoveBundlesHeader() throws Exception {
    Bundle bundle = newMockBundle(new VersionedName("foo.bar", "1.2.3"));
    
    assertParseForceRemoveBundlesHeader("\"foo:0.1.0\"", bundle, ImmutableList.of(new VersionRangedName("foo", exactly0dot1)));
    assertParseForceRemoveBundlesHeader("\"*\"", bundle, ImmutableList.of(new VersionRangedName("foo.bar", from0lessThan1_2_3)));
    assertParseForceRemoveBundlesHeader("*", bundle, ImmutableList.of(new VersionRangedName("foo.bar", from0lessThan1_2_3)));
    assertParseForceRemoveBundlesHeader("other:1, '*:[0,1)'", bundle, ImmutableList.of(
        new VersionRangedName("other", VersionRange.valueOf("[1.0.0,1.0.0]")), 
        new VersionRangedName("foo.bar", new VersionRange('[', Version.valueOf("0"), Version.valueOf("1"), ')'))));
}
 
Example #14
Source File: FeatureInformation.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
public VersionRange makeVersionRange ()
{
    if ( this.version == null )
    {
        return new VersionRange ( "0.0.0" );
    }
    else
    {
        return new VersionRange ( VersionRange.LEFT_CLOSED, this.version, this.version, VersionRange.RIGHT_CLOSED );
    }
}
 
Example #15
Source File: FeatureInformation.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
public VersionRange makeVersionRange ()
{
    if ( this.version == null )
    {
        return new VersionRange ( "0.0.0" );
    }
    else
    {
        return new VersionRange ( VersionRange.LEFT_CLOSED, this.version, this.version, VersionRange.RIGHT_CLOSED );
    }
}
 
Example #16
Source File: InstallableUnit.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
private String makeString ( final VersionRange range )
{
    if ( range == null )
    {
        return "0.0.0";
    }
    else
    {
        return range.toString ();
    }
}
 
Example #17
Source File: RepositoryCommandGroup.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public int cmdBundle(Dictionary<String,?> opts, Reader in, PrintWriter out,
    Session session) {
  final boolean verbose = (opts.get("-l") != null);
  final String bsn = (String) opts.get("symbolicname");
  final String ver = (String) opts.get("versionRange");
  BasicRequirement requirement;
  if (bsn != null) {
    requirement = new BasicRequirement(IdentityNamespace.IDENTITY_NAMESPACE, bsn);
  } else {
    requirement = new BasicRequirement(IdentityNamespace.IDENTITY_NAMESPACE);
  }
  if (ver != null) {
    requirement.addVersionRangeFilter(new VersionRange(ver)); 
  }
  requirement.addBundleIdentityFilter();
  List<Resource> resources = new ArrayList<Resource>();
  for (Capability c : getRepositoryManager().findProviders(requirement)) {
    resources.add(c.getResource());
  }
  if (resources.isEmpty()) {
    out.println("No bundles found!");
    return 1;
  } else {
    printBundleResources(out, resources, verbose);
  }
  return 0;
}
 
Example #18
Source File: InstallableUnit.java    From packagedrone with Eclipse Public License 1.0 5 votes vote down vote up
public Requirement ( final VersionRange range, final boolean optional, final Boolean greedy, final String filter )
{
    this.range = range;
    this.optional = optional;
    this.greedy = greedy;
    this.filter = filter;
}
 
Example #19
Source File: FeatureInformation.java    From packagedrone with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public VersionRange makeRange ( final Version version )
{
    return new VersionRange ( version.toString () );
}
 
Example #20
Source File: BundleGenerator.java    From concierge with Eclipse Public License 1.0 4 votes vote down vote up
public BundleGenerator addPackageImport(final String pkgImport,
		final VersionRange versionRange) {
	imports.add(pkgImport + ";version=\"" + versionRange.toString() + "\"");
	return this;
}
 
Example #21
Source File: ResolverStressTest.java    From concierge with Eclipse Public License 1.0 4 votes vote down vote up
public void run(final BundleContext context) throws BundleException,
		IOException {
	final Bundle[] bundles = new Bundle[NUM];

	long installationTime = 0;

	for (int i = 0; i < NUM; i++) {
		final BundleGenerator gen = new BundleGenerator("bundle" + i,
				new Version(1, 0, i));

		final int dirs = random.nextInt(MAX_IMPORTS_EXPORTS);

		final Set<String> imports = new HashSet<String>();
		final Set<String> exports = new HashSet<String>();

		for (int j = 0; j < dirs; j++) {
			if (random.nextBoolean()) {
				// IMPORT
				final int v1Major = MIN_VERSION_MAJOR
						+ random.nextInt(MAX_VERSION_MAJOR
								- MIN_VERSION_MAJOR + 1);
				final int v2Major = MIN_VERSION_MAJOR
						+ random.nextInt(MAX_VERSION_MAJOR
								- MIN_VERSION_MAJOR + 1);

				final Version v1 = new Version(v1Major, random.nextInt(10),
						random.nextInt(10));

				final Version v2 = new Version(v2Major, random.nextInt(10),
						random.nextInt(10));

				final Version lowerBound = v1.compareTo(v2) < 1 ? v1 : v2;
				final Version upperBound = v1.compareTo(v2) >= 1 ? v1 : v2;

				gen.addPackageImport(drawPackage(imports),
						new VersionRange('[', lowerBound, upperBound, ')'));
			} else {
				// EXPORT
				final Version version = new Version(
						random.nextInt(MAX_VERSION_MAJOR
								- MIN_VERSION_MAJOR + 1),
						random.nextInt(10), random.nextInt(10));

				gen.addPackageExport(drawPackage(exports), version);
			}
		}

		final long t = System.nanoTime();
		bundles[i] = gen.install(context);
		installationTime += (System.nanoTime() - t);
	}

	System.err.println("INSTALLATION TIME " + (installationTime / 1000000));

	final FrameworkWiring fw = context.getBundle(0).adapt(
			FrameworkWiring.class);

	System.err.println("RESOLVING");
	final long time = System.nanoTime();
	fw.resolveBundles(Arrays.asList(bundles));
	System.err.println("RESOLVE TIME " + (System.nanoTime() - time)
			/ 1000000);

}
 
Example #22
Source File: Utils.java    From concierge with Eclipse Public License 1.0 4 votes vote down vote up
public static String createFilter(final String namespace, final String req,
		final Map<String, Object> attributes) throws BundleException {
	final Object version = attributes.get(Constants.VERSION_ATTRIBUTE);

	if (PackageNamespace.PACKAGE_NAMESPACE.equals(namespace)) {
		if (version != null
				&& attributes.containsKey(SPECIFICATION_VERSION)) {
			if (!new Version(Utils.unQuote((String) attributes
					.get(SPECIFICATION_VERSION))).equals(version)) {
				throw new BundleException(
						"both version and specification-version are given for the import "
								+ req);
			} else {
				attributes.remove(SPECIFICATION_VERSION);
			}
		}
	}

	final StringBuffer buffer = new StringBuffer();
	buffer.append('(');
	buffer.append(namespace);
	buffer.append('=');
	buffer.append(req);
	buffer.append(')');

	if (attributes.size() == 0) {
		return buffer.toString();
	}

	buffer.insert(0, "(&");

	for (final Map.Entry<String, Object> attribute : attributes.entrySet()) {
		final String key = attribute.getKey();
		final Object value = attribute.getValue();

		if (Constants.VERSION_ATTRIBUTE.equals(key)
				|| Constants.BUNDLE_VERSION_ATTRIBUTE.equals(key)) {
			if (value instanceof String) {
				final VersionRange range = new VersionRange(
						Utils.unQuote((String) value));

				if (range.getRight() == null) {
					buffer.append('(');
					buffer.append(key);
					buffer.append(">=");
					buffer.append(range.getLeft());
					buffer.append(')');
				} else {
					boolean open = range.getLeftType() == VersionRange.LEFT_OPEN;
					buffer.append(open ? "(!(" : "(");
					buffer.append(key);
					buffer.append(open ? "<=" : ">=");
					buffer.append(range.getLeft());
					buffer.append(open ? "))" : ")");

					open = range.getRightType() == VersionRange.RIGHT_OPEN;
					buffer.append(open ? "(!(" : "(");
					buffer.append(key);
					buffer.append(open ? ">=" : "<=");
					buffer.append(range.getRight());
					buffer.append(open ? "))" : ")");
				}
			} else {
				buffer.append('(');
				buffer.append(key);
				buffer.append(">=");
				buffer.append(value);
				buffer.append(')');
			}
			continue;
		}

		buffer.append("(");
		buffer.append(key);
		buffer.append("=");
		buffer.append(value);
		buffer.append(")");
	}
	buffer.append(")");

	return buffer.toString();
}
 
Example #23
Source File: BundleUpgradeParser.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public VersionRange getOsgiVersionRange() {
    if (cachedOsgiVersionRange == null) {
        cachedOsgiVersionRange = VersionRange.valueOf(BrooklynVersionSyntax.toValidOsgiVersionRange(v));
    }
    return cachedOsgiVersionRange;
}
 
Example #24
Source File: BundleUpgradeParser.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
public VersionRangedName(String name, VersionRange v) {
    this.name = checkNotNull(name, "name").toString();
    this.v = checkNotNull(v, "versionRange").toString();
}
 
Example #25
Source File: Osgis.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
private boolean isVersionRange(String version) {
    return (version != null) && (version.length() > 2) 
            && (version.charAt(0) == VersionRange.LEFT_OPEN || version.charAt(0) == VersionRange.LEFT_CLOSED)
            && (version.charAt(version.length()-1) == VersionRange.RIGHT_OPEN || version.charAt(version.length()-1) == VersionRange.RIGHT_CLOSED);
}
 
Example #26
Source File: Osgis.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/** Finds all matching bundles, in decreasing version order. */
@SuppressWarnings("deprecation")
public List<Bundle> findAll() {
    boolean urlMatched = false;
    List<Bundle> result = MutableList.of();
    String v=null, vDep = null;
    VersionRange vRange = null;
    if (version!=null) {
        if (isVersionRange(version)) {
            vRange = VersionRange.valueOf(version);
        } else {
            v = BrooklynVersionSyntax.toValidOsgiVersion(version);
            vDep = OsgiUtils.toOsgiVersion(version);
        }
    }
    for (Bundle b: framework.getBundleContext().getBundles()) {
        if (symbolicName!=null && !symbolicName.equals(b.getSymbolicName())) continue;
        if (version!=null) {
            Version bv = b.getVersion();
            if (vRange != null) {
                if (!vRange.includes(bv)) {
                    continue;
                }
            } else {
                String bvString = bv.toString();
                if (!v.equals(bvString)) {
                    if (!vDep.equals(bvString)) {
                        continue;
                    }
                    LOG.warn("Legacy inferred OSGi version string '"+vDep+"' found to match "+symbolicName+":"+version+"; switch to '"+v+"' format to avoid issues with deprecated version syntax");
                }
            }
        }
        if (!Predicates.and(predicates).apply(b)) continue;

        // check url last, because if it isn't mandatory we should only clear if we find a url
        // for which the other items also match
        if (url!=null) {
            boolean matches = url.equals(b.getLocation());
            if (urlMandatory) {
                if (!matches) continue;
                else urlMatched = true;
            } else {
                if (matches) {
                    if (!urlMatched) {
                        result.clear();
                        urlMatched = true;
                    }
                } else {
                    if (urlMatched) {
                        // can't use this bundle as we have previously found a preferred bundle, with a matching url
                        continue;
                    }
                }
            }
        }
                        
        result.add(b);
    }
    
    if (symbolicName==null && url!=null && !urlMatched) {
        // if we only "preferred" the url, and we did not match it, and we did not have a symbolic name,
        // then clear the results list!
        result.clear();
    }

    Collections.sort(result, new Comparator<Bundle>() {
        @Override
        public int compare(Bundle o1, Bundle o2) {
            int r = NaturalOrderComparator.INSTANCE.compare(o1.getSymbolicName(), o2.getSymbolicName());
            if (r!=0) return r;
            return VersionComparator.INSTANCE.compare(o1.getVersion().toString(), o2.getVersion().toString());
        }
    });
    
    return result;
}
 
Example #27
Source File: BundleInformation.java    From packagedrone with Eclipse Public License 1.0 4 votes vote down vote up
public BundleRequirement ( final String id, final VersionRange versionRange, final boolean optional, final boolean reexport )
{
    super ( id, versionRange );
    this.optional = optional;
    this.reexport = reexport;
}
 
Example #28
Source File: BundleInformation.java    From packagedrone with Eclipse Public License 1.0 4 votes vote down vote up
public PackageImport ( final String name, final VersionRange versionRange, final boolean optional )
{
    super ( name, versionRange );
    this.optional = optional;
}
 
Example #29
Source File: BundleInformation.java    From packagedrone with Eclipse Public License 1.0 4 votes vote down vote up
public VersionRange getVersionRange ()
{
    return this.versionRange;
}
 
Example #30
Source File: BundleInformation.java    From packagedrone with Eclipse Public License 1.0 4 votes vote down vote up
public VersionRangedName ( final String name, final VersionRange versionRange )
{
    this.name = name;
    this.versionRange = versionRange;
}