From b888fcf47bc48193438e5236e5cd785ff9700aae Mon Sep 17 00:00:00 2001 From: Gian Tschingt Date: Mon, 16 Nov 2026 18:24:03 +0100 Subject: [PATCH 1/2] Version handling: Maven versions, ranges, no pre-releases, errors are reported - toVersion accepts the Maven spelling of a version (33.8.0-jre, 2.17, 3.0-rc5) - getBundleAsURL tries the version as given first, then the OSGi spelling and 2.17 for 2.17.0 - latestVersion only returns a version inside the range and skips pre-releases (rc, alpha, beta, snapshot, milestones, ...) unless the range asks for one; it throws with the reason instead of returning null - a missing bundle or package keeps the whole range of the requirement (bundle-version>=X is not the exact version X), the newest local match is used before anything is downloaded - when the dependencies cannot be loaded, the reasons are part of the exception - downloads have a read timeout and use a unique temp file, the readers cache is a ConcurrentHashMap - packages of jackson-core, jackson-databind and guava failureaccess are mapped to their bundles, and a package is mapped to a bundle with the same name --- .../lucee/extension/osgi/BundleProvider.java | 194 +++++++++---- .../lucee/extension/osgi/OSGiServiceImpl.java | 268 ++++++++++++++---- 2 files changed, 348 insertions(+), 114 deletions(-) diff --git a/source/java/src/org/lucee/extension/osgi/BundleProvider.java b/source/java/src/org/lucee/extension/osgi/BundleProvider.java index e34091c..e05c6a9 100644 --- a/source/java/src/org/lucee/extension/osgi/BundleProvider.java +++ b/source/java/src/org/lucee/extension/osgi/BundleProvider.java @@ -33,7 +33,7 @@ public final class BundleProvider { private static final Map tokens = new ConcurrentHashMap(); private URL[] details; - private static Map readers = new HashMap<>(); + private static final Map readers = new ConcurrentHashMap<>(); static { try { @@ -483,19 +483,44 @@ public static Map getMappings() { return mappings; } - /** the newest version of the artifact a bundle is mapped to, read from the maven metadata, null when unknown */ - public String latestVersion(String bundleName) { + /** + * the newest release of the artifact a bundle is mapped to, read from the maven metadata, null when + * the bundle is not mapped to a Maven artifact + */ + public String latestVersion(String bundleName) throws IOException { + return latestVersion(bundleName, null); + } + + /** + * the newest version of the artifact a bundle is mapped to that is inside the range (all versions + * when the range is null), read from the maven metadata. Pre-releases (rc, alpha, beta, snapshot, + * milestones) are skipped, unless the range itself asks for one. The version is returned in the + * spelling of Maven (33.8.0-jre, 2.20). Null when the bundle is not mapped to a Maven artifact. + * + * @throws IOException when the bundle is mapped, but no version in the range could be found, with + * the reason for each repository + */ + public String latestVersion(String bundleName, org.osgi.framework.VersionRange range) throws IOException { Info[] infos = getMappings().get(bundleName); if (infos == null) return null; + boolean allowPreRelease = range != null && (isPreRelease(range.getLeft()) || isPreRelease(range.getRight())); + List problems = new ArrayList<>(); + boolean mapped = false; for (Info info: infos) { if (!info.isMaven()) continue; + mapped = true; for (URL repo: getDefaultProviderDetailMvn()) { + URL url = null; try { - URL url = new URL(repo, info.groupId.replace('.', '/') + "/" + info.artifactId + "/maven-metadata.xml"); + url = new URL(repo, info.groupId.replace('.', '/') + "/" + info.artifactId + "/maven-metadata.xml"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(CONNECTION_TIMEOUT); conn.setReadTimeout(CONNECTION_TIMEOUT * 3); - if (conn.getResponseCode() != 200) continue; + int code = conn.getResponseCode(); + if (code != 200) { + problems.add("[" + url + "] returned status code " + code); + continue; + } StringBuilder sb = new StringBuilder(); try (BufferedReader r = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"))) { String line; @@ -503,16 +528,45 @@ public String latestVersion(String bundleName) { sb.append(line); } } - for (String tag: new String[] { "release", "latest" }) { - java.util.regex.Matcher m = java.util.regex.Pattern.compile("<" + tag + ">([^<]+)").matcher(sb); - if (m.find()) return m.group(1).trim(); + String best = null; + Version bestVersion = null; + java.util.regex.Matcher m = VERSION_TAG.matcher(sb); + while (m.find()) { + String raw = m.group(1).trim(); + if (!allowPreRelease && isPreRelease(raw)) continue; + Version v = toVersion(raw, null); + if (v == null) continue; + if (range != null && !range.includes(v)) continue; + if (bestVersion == null || v.compareTo(bestVersion) > 0) { + best = raw; + bestVersion = v; + } } + if (best != null) return best; + problems.add("[" + url + "] has no " + (allowPreRelease ? "version" : "release") + (range == null ? "" : " inside the range " + range)); } catch (Exception e) { + problems.add("[" + (url == null ? repo : url) + "] failed: " + e); } } } - return null; + if (!mapped) return null; + throw new IOException("no version of the bundle [" + bundleName + "]" + (range == null ? "" : " inside the range " + range) + " found: " + String.join("; ", problems)); + } + + private static final java.util.regex.Pattern VERSION_TAG = java.util.regex.Pattern.compile("([^<]+)"); + private static final java.util.regex.Pattern PRE_RELEASE = java.util.regex.Pattern + .compile("(?i)(?:^|[.\\-_])(?:snapshot|alpha|beta|rc|cr|m|milestone|ea|preview|pre|dev|a|b)\\d*(?:[.\\-_]|$)"); + + /** true for versions like 3.0-rc5, 2.0.0-M1, 1.0-SNAPSHOT, 5.4.0.Beta1 or 1.0.0-ALPHA */ + public static boolean isPreRelease(Object version) { + if (version == null) return false; + String str = version instanceof Version ? ((Version) version).getQualifier() : version.toString(); + if (str == null || str.isEmpty()) return false; + // the numeric part does not count, only the qualifier + java.util.regex.Matcher m = java.util.regex.Pattern.compile("^\\d+(?:\\.\\d+)*").matcher(str); + String rest = m.find() ? str.substring(m.end()) : str; + return !rest.isEmpty() && PRE_RELEASE.matcher(rest.startsWith(".") || rest.startsWith("-") || rest.startsWith("_") ? rest : "." + rest).find(); } private static String createToken(String prefix, String name) { @@ -604,22 +658,13 @@ public URL getBundleAsURL(String bundleName, String bundleVersion) throws IOExce Info[] infos = getMappings().get(bd.name); if (infos != null && infos.length > 0) { - String v; for (Info info: infos) { if (!info.isMaven()) continue; for (URL repo: getDefaultProviderDetailMvn()) { - v = bd.getVersionAsString(); - url = validate(createURL(repo, info, v), null); - if (url != null) { - return url; - } - if (v != null && v.endsWith(".0")) { - v = v.substring(0, v.length() - 2); + for (String v: bd.getMavenVersions()) { url = validate(createURL(repo, info, v), null); - if (url != null) { - return url; - } + if (url != null) return url; } } } @@ -631,8 +676,10 @@ public URL getBundleAsURL(String bundleName, String bundleVersion) throws IOExce String last = index == -1 ? bd.name : bd.name.substring(index + 1); for (URL repo: getDefaultProviderDetailMvn()) { - url = validate(new URL(repo, bd.name.replace('.', '/') + "/" + bd.version + "/" + last + "-" + bd.version + ".jar"), null); - if (url != null) return url; + for (String v: bd.getMavenVersions()) { + url = validate(new URL(repo, bd.name.replace('.', '/') + "/" + v + "/" + last + "-" + v + ".jar"), null); + if (url != null) return url; + } } } // S3: we check for a direct match @@ -641,7 +688,7 @@ public URL getBundleAsURL(String bundleName, String bundleVersion) throws IOExce if (url != null) return url; } - throw new IOException("no URL found for bundle [" + bd.name + ":" + bd.version + "]"); + throw new IOException("no URL found for bundle [" + bd.name + ":" + bd.getRawVersion() + "]"); } private static Map readIni(java.io.InputStream ini) throws IOException { @@ -716,6 +763,7 @@ private static URL validate(URL url, URL defaultValue) { conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.setConnectTimeout(BundleProvider.CONNECTION_TIMEOUT); + conn.setReadTimeout(BundleProvider.CONNECTION_TIMEOUT); conn.connect(); int code = conn.getResponseCode(); if (code >= 200 && code < 300) return url; @@ -785,21 +833,48 @@ public static class BundleDefinition { private static final int QUALIFIER_APPENDIX_STABLE = 5; private String name; private Version version; + private String rawVersion; public BundleDefinition(String name, Version version) { this.name = name; this.version = version; + this.rawVersion = version == null ? null : version.toString(); } public BundleDefinition(String name, String version) throws BundleException { this.name = name; this.version = toVersion(version); + this.rawVersion = version == null ? null : version.trim(); } public String getVersionAsString() { return version == null ? null : version.toString(); } + /** the version as it was given, for example 33.8.0-jre */ + public String getRawVersion() { + return rawVersion; + } + + /** + * the spellings of the version a Maven artifact may use, the given one first: 33.8.0-jre (as given), + * 33.8.0.jre (OSGi), and for 2.17.0 also 2.17 + */ + public List getMavenVersions() { + java.util.LinkedHashSet set = new java.util.LinkedHashSet<>(); + if (rawVersion != null && !rawVersion.isEmpty()) set.add(rawVersion); + if (version != null) { + String q = version.getQualifier(); + String base = version.getMajor() + "." + version.getMinor() + "." + version.getMicro(); + if (!q.isEmpty() && !Character.isDigit(q.charAt(0))) set.add(base + "-" + q); + set.add(version.toString()); + if (q.isEmpty() && version.getMicro() == 0) { + set.add(version.getMajor() + "." + version.getMinor()); + } + } + return new ArrayList<>(set); + } + public int compare(BundleDefinition bd) { // name int cmp = name.compareTo(bd.name); @@ -872,51 +947,46 @@ public Pair(long lastModified, BundleProvider bundleProvider) { } } - private static Version toVersion(String version, Version defaultValue) { - if (Util.isEmpty(version)) return defaultValue; - // String[] arr = ListUtil.listToStringArray(version, '.'); - String[] arr; + /** + * a version as OSGi version, this also accepts the Maven spelling: 33.8.0-jre becomes 33.8.0.jre, + * 2.17 becomes 2.17.0, 3.0-rc5 becomes 3.0.0.rc5 and 1.0.0.5 stays + */ + static Version toVersion(String version, Version defaultValue) { + if (Util.isEmpty(version, true)) return defaultValue; + version = version.trim(); + int[] nums = new int[3]; + int count = 0; + int i = 0; + int len = version.length(); try { - - arr = version.split("\\."); - ; - } - catch (Exception e) { - return defaultValue; // should not happen + while (count < 3 && i < len && Character.isDigit(version.charAt(i))) { + int start = i; + while (i < len && Character.isDigit(version.charAt(i))) i++; + nums[count++] = Integer.parseInt(version.substring(start, i)); + // a dot followed by a number continues the numeric part + if (count < 3 && i + 1 < len && version.charAt(i) == '.' && Character.isDigit(version.charAt(i + 1))) i++; + else break; + } } - - Integer major, minor, micro; - String qualifier; - - if (arr.length == 1) { - major = Integer.parseInt(arr[0]); - minor = 0; - micro = 0; - qualifier = null; + catch (NumberFormatException nfe) { + return defaultValue; } - else if (arr.length == 2) { - major = Integer.parseInt(arr[0]); - minor = Integer.parseInt(arr[1]); - micro = 0; - qualifier = null; + if (count == 0) return defaultValue; + String qualifier = i < len ? version.substring(i) : ""; + // the separator between the numbers and the qualifier + if (!qualifier.isEmpty() && (qualifier.charAt(0) == '.' || qualifier.charAt(0) == '-' || qualifier.charAt(0) == '_')) qualifier = qualifier.substring(1); + if (qualifier.isEmpty()) return new Version(nums[0], nums[1], nums[2]); + // OSGi only allows letters, digits, _ and - in the qualifier + StringBuilder sb = new StringBuilder(qualifier.length()); + for (char c: qualifier.toCharArray()) { + sb.append(Character.isLetterOrDigit(c) || c == '_' || c == '-' ? c : '_'); } - else if (arr.length == 3) { - major = Integer.parseInt(arr[0]); - minor = Integer.parseInt(arr[1]); - micro = Integer.parseInt(arr[2]); - qualifier = null; + try { + return new Version(nums[0], nums[1], nums[2], sb.toString()); } - else { - major = Integer.parseInt(arr[0]); - minor = Integer.parseInt(arr[1]); - micro = Integer.parseInt(arr[2]); - qualifier = arr[3]; + catch (IllegalArgumentException iae) { + return defaultValue; } - - if (major == null || minor == null || micro == null) return defaultValue; - - if (qualifier == null) return new Version(major, minor, micro); - return new Version(major, minor, micro, qualifier); } private static Version toVersion(String version) throws BundleException { diff --git a/source/java/src/org/lucee/extension/osgi/OSGiServiceImpl.java b/source/java/src/org/lucee/extension/osgi/OSGiServiceImpl.java index bdffc10..628d8e7 100644 --- a/source/java/src/org/lucee/extension/osgi/OSGiServiceImpl.java +++ b/source/java/src/org/lucee/extension/osgi/OSGiServiceImpl.java @@ -28,6 +28,7 @@ import org.osgi.framework.BundleException; import org.osgi.framework.BundleReference; import org.osgi.framework.Constants; +import org.osgi.framework.VersionRange; import org.osgi.framework.launch.Framework; import org.osgi.framework.launch.FrameworkFactory; import org.osgi.framework.wiring.BundleRevision; @@ -196,7 +197,15 @@ private static boolean matches(String symbolicName, org.osgi.framework.Version b if (!name.equals(symbolicName)) return false; if (version == null || version.trim().isEmpty()) return true; String v = version.trim(); - return v.equalsIgnoreCase(toLucee(bundleVersion)) || v.equalsIgnoreCase(bundleVersion.toString()); + if (v.equalsIgnoreCase(toLucee(bundleVersion)) || v.equalsIgnoreCase(bundleVersion.toString())) return true; + // the Maven spelling of the same version (33.8.0-jre is 33.8.0.jre, 2.17 is 2.17.0) + org.osgi.framework.Version parsed = BundleProvider.toVersion(v, null); + return parsed != null && parsed.equals(bundleVersion); + } + + private static boolean matches(String symbolicName, org.osgi.framework.Version bundleVersion, String name, VersionRange range) { + if (!name.equals(symbolicName)) return false; + return range == null || range.includes(bundleVersion); } private static Bundle find(BundleContext ctx, String name, String version) { @@ -209,6 +218,17 @@ private static Bundle find(BundleContext ctx, String name, String version) { return best; } + /** the newest installed bundle with that name inside the range, any version when the range is null */ + private static Bundle find(BundleContext ctx, String name, VersionRange range) { + if (ctx == null) return null; + Bundle best = null; + for (Bundle b: ctx.getBundles()) { + if (b.getState() == Bundle.UNINSTALLED || !matches(b.getSymbolicName(), b.getVersion(), name, range)) continue; + if (best == null || b.getVersion().compareTo(best.getVersion()) > 0) best = b; + } + return best; + } + private static void startIfNecessary(Bundle b) throws BundleException { if (b.getState() == Bundle.ACTIVE || b.getState() == Bundle.STARTING) return; BundleRevision rev = b.adapt(BundleRevision.class); @@ -252,6 +272,33 @@ private static File findJar(File dir, String name, String version) { return best; } + /** the jar with the newest version of the bundle inside the range, any version when the range is null */ + private static File findJar(File dir, String name, VersionRange range) { + File[] jars = dir == null ? null : dir.listFiles((d, n) -> n.endsWith(".jar")); + if (jars == null) return null; + File best = null; + org.osgi.framework.Version bestVersion = null; + for (File jar: jars) { + Object[] nv = read(jar); + if (nv == null || !matches((String) nv[0], (org.osgi.framework.Version) nv[1], name, range)) continue; + org.osgi.framework.Version v = (org.osgi.framework.Version) nv[1]; + if (best == null || v.compareTo(bestVersion) > 0) { + best = jar; + bestVersion = v; + } + } + return best; + } + + private Bundle install(BundleContext ctx, File jar) throws IOException { + try { + return ctx.installBundle(jar.toURI().toString()); + } + catch (BundleException e) { + throw new IOException(e.getMessage(), e); + } + } + /** * the installed bundle, installing it from the local bundle directory, one of the given directories or a * download when necessary @@ -262,7 +309,7 @@ private static File findJar(File dir, String name, String version) { private Bundle load(String name, String version, File[] dirs, boolean versionOnlyMatters) throws IOException { BundleContext ctx = context(); Bundle b = find(ctx, name, version); - if (b == null && versionOnlyMatters) b = find(ctx, name, null); + if (b == null && versionOnlyMatters) b = find(ctx, name, (String) null); if (b != null) return b; File jar = findJar(bundleDirectory, name, version); @@ -272,14 +319,35 @@ private Bundle load(String name, String version, File[] dirs, boolean versionOnl if (jar != null) break; } } - if (jar == null && versionOnlyMatters) jar = findJar(bundleDirectory, name, null); + if (jar == null && versionOnlyMatters) jar = findJar(bundleDirectory, name, (String) null); if (jar == null) jar = download(name, version); - try { - return ctx.installBundle(jar.toURI().toString()); + return install(ctx, jar); + } + + /** + * the newest bundle with that name inside the range (any version when the range is null) that is + * installed, in the local bundle directory or in one of the given directories, otherwise the newest + * release inside the range is downloaded + */ + private Bundle load(String name, VersionRange range, File[] dirs) throws IOException { + BundleContext ctx = context(); + Bundle b = find(ctx, name, range); + if (b != null) return b; + + File jar = findJar(bundleDirectory, name, range); + if (dirs != null) { + for (File dir: dirs) { + File candidate = findJar(dir, name, range); + if (candidate != null && (jar == null || ((org.osgi.framework.Version) read(candidate)[1]).compareTo((org.osgi.framework.Version) read(jar)[1]) > 0)) jar = candidate; + } } - catch (BundleException e) { - throw new IOException(e.getMessage(), e); + if (jar == null) { + String version = BundleProvider.getInstance().latestVersion(name, range); + // not a Maven artifact we know, the lower end of the range is the best guess + if (version == null && range != null && range.getLeftType() == VersionRange.LEFT_CLOSED) version = toLucee(range.getLeft()); + jar = download(name, version); } + return install(ctx, jar); } /** download a bundle into the bundle directory */ @@ -294,28 +362,40 @@ private File download(String name, String version) throws IOException { catch (BundleException | RuntimeException e) { throw new IOException("no download for the bundle [" + name + ":" + version + "]: " + e.getMessage(), e); } - File tmp = new File(bundleDirectory, name + "-" + version + ".jar.tmp"); - try (InputStream is = url.openStream(); OutputStream os = new FileOutputStream(tmp)) { - byte[] buf = new byte[8192]; - int len; - while ((len = is.read(buf)) != -1) { - os.write(buf, 0, len); + // a unique file, the same bundle may be downloaded by two threads at the same time + File tmp = File.createTempFile(safe(name) + "-", ".jar.tmp", bundleDirectory); + try { + java.net.URLConnection conn = url.openConnection(); + conn.setConnectTimeout(BundleProvider.CONNECTION_TIMEOUT); + conn.setReadTimeout(BundleProvider.CONNECTION_TIMEOUT * 3); + try (InputStream is = conn.getInputStream(); OutputStream os = new FileOutputStream(tmp)) { + byte[] buf = new byte[8192]; + int len; + while ((len = is.read(buf)) != -1) { + os.write(buf, 0, len); + } } + Object[] nv = read(tmp); + if (nv == null) throw new IOException("the file downloaded from [" + url + "] is not an OSGi bundle"); + File target = new File(bundleDirectory, nv[0] + "-" + toLucee((org.osgi.framework.Version) nv[1]) + ".jar"); + if (!target.isFile() && !tmp.renameTo(target) && !target.isFile()) throw new IOException("failed to move the downloaded bundle to [" + target + "]"); + return target; } - Object[] nv = read(tmp); - if (nv == null) { - tmp.delete(); - throw new IOException("the file downloaded from [" + url + "] is not an OSGi bundle"); + finally { + if (tmp.isFile()) tmp.delete(); } - File target = new File(bundleDirectory, nv[0] + "-" + toLucee((org.osgi.framework.Version) nv[1]) + ".jar"); - if (target.isFile()) tmp.delete(); - else if (!tmp.renameTo(target)) throw new IOException("failed to move the downloaded bundle to [" + target + "]"); - return target; + } + + private static String safe(String name) { + String str = name.replaceAll("[^A-Za-z0-9._-]", "_"); + // createTempFile needs a prefix of at least 3 characters + return str.length() < 3 ? str + "___" : str; } private Bundle loadAndStart(String name, String version, File[] dirs, boolean versionOnlyMatters) throws IOException { Bundle b = load(name, version, dirs, versionOnlyMatters); Set tried = new HashSet<>(); + List problems = new ArrayList<>(); while (true) { try { startIfNecessary(b); @@ -323,13 +403,71 @@ private Bundle loadAndStart(String name, String version, File[] dirs, boolean ve } catch (BundleException be) { // a bundle this bundle depends on may be missing, load it and try again - if (!loadMissing(be.getMessage(), dirs, tried)) throw new IOException(be.getMessage(), be); + if (!loadMissing(be.getMessage(), dirs, tried, problems)) { + String msg = be.getMessage(); + if (!problems.isEmpty()) msg += " (failed to load what is missing: " + String.join("; ", problems) + ")"; + throw new IOException(msg, be); + } } } } - private static final Pattern MISSING_BUNDLE = Pattern.compile("osgi\\.wiring\\.bundle=([^)]+)\\)(?:\\(bundle-version>=([^)]+)\\))?"); - private static final Pattern MISSING_PACKAGE = Pattern.compile("osgi\\.wiring\\.package=([^)]+)\\)"); + // one requirement from the message of a failed start, for example + // (&(osgi.wiring.bundle=a.b)(bundle-version>=2.17.0)(!(bundle-version>=3.0.0))) + // (&(osgi.wiring.package=a.b)(version>=2.17.0)(!(version>=3.0.0))) + private static final Pattern MISSING = Pattern.compile("osgi\\.wiring\\.(bundle|package)=([^)]+)\\)((?:\\((?:!\\()?(?:bundle-)?version[<>]?=[^)]+\\)\\)?)*)"); + private static final Pattern CONSTRAINT = Pattern.compile("\\((!\\()?(?:bundle-)?version([<>]?=)([^)]+)\\)"); + + /** + * the version range of the constraints of a requirement filter, like (version>=2.17.0)(!(version>=3.0.0)), + * null when there is no constraint + */ + static VersionRange toRange(String constraints) { + if (constraints == null || constraints.isEmpty()) return null; + org.osgi.framework.Version floor = null, ceiling = null; + boolean floorClosed = true, ceilingClosed = false; + Matcher m = CONSTRAINT.matcher(constraints); + boolean any = false; + while (m.find()) { + boolean not = m.group(1) != null; + String op = m.group(2); + org.osgi.framework.Version v; + try { + v = org.osgi.framework.Version.parseVersion(m.group(3).trim()); + } + catch (IllegalArgumentException iae) { + continue; + } + any = true; + if ("=".equals(op) && !not) { + floor = ceiling = v; + floorClosed = ceilingClosed = true; + } + else if (">=".equals(op)) { + if (not) { // (!(version>=X)) is version tried) { + /** + * loads the bundles and packages the message of a failed start says are missing, false when nothing + * could be loaded, the reasons are added to problems + */ + private boolean loadMissing(String message, File[] dirs, Set tried, List problems) { boolean loaded = false; - Matcher m = MISSING_BUNDLE.matcher(message); + Matcher m = MISSING.matcher(message); while (m.find()) { - String name = m.group(1).trim(); - String version = m.group(2) == null ? null : m.group(2).trim(); - if (!tried.add("b:" + name + ":" + version)) continue; + boolean isBundle = "bundle".equals(m.group(1)); + String name = m.group(2).trim(); + VersionRange range = toRange(m.group(3)); + if (!tried.add((isBundle ? "b:" : "p:") + name + ":" + range)) continue; try { - load(name, version, dirs, true); - loaded = true; - } - catch (IOException e) { - } - } - m = MISSING_PACKAGE.matcher(message); - while (m.find()) { - String pkg = m.group(1).trim(); - if (!tried.add("p:" + pkg)) continue; - try { - File jar = findExporting(bundleDirectory, pkg); + if (isBundle) { + load(name, range, dirs); + loaded = true; + continue; + } + // a package + File jar = findExporting(bundleDirectory, name, range); if (jar != null) { context().installBundle(jar.toURI().toString()); loaded = true; continue; } - String name = PACKAGE_BUNDLE.get(pkg); - if (name != null) { - load(name, null, dirs, true); + String bundle = PACKAGE_BUNDLE.get(name); + // a bundle that has the name of the package, like com.google.gson + if (bundle == null && BundleProvider.getMappings().containsKey(name)) bundle = name; + if (bundle != null) { + // the version of the package is the version of the bundle for most bundles + try { + load(bundle, range, dirs); + } + catch (IOException e) { + if (range == null) throw e; + load(bundle, (VersionRange) null, dirs); + } loaded = true; } + else { + problems.add("no bundle known that exports the package [" + name + "]" + (range == null ? "" : " " + range)); + } } - catch (IOException | BundleException e) { + catch (IOException | BundleException | RuntimeException e) { + problems.add((isBundle ? "bundle [" : "package [") + name + "]" + (range == null ? "" : " " + range) + ": " + e.getMessage()); } } return loaded; } - /** a bundle in the directory that exports the package */ - private static File findExporting(File dir, String pkg) { + /** a bundle in the directory that exports the package in a version inside the range */ + private static File findExporting(File dir, String pkg, VersionRange range) { File[] jars = dir == null ? null : dir.listFiles((d, n) -> n.endsWith(".jar")); if (jars == null) return null; for (File jar: jars) { @@ -400,10 +553,21 @@ private static File findExporting(File dir, String pkg) { String exports = mf == null ? null : mf.getMainAttributes().getValue("Export-Package"); if (exports == null) continue; for (String part: exports.split(",(?=[^\"]*(?:\"[^\"]*\"[^\"]*)*$)")) { - String name = part.trim(); - int idx = name.indexOf(';'); - if (idx != -1) name = name.substring(0, idx); - if (pkg.equals(name.trim())) return jar; + String[] attrs = part.split(";(?=[^\"]*(?:\"[^\"]*\"[^\"]*)*$)"); + if (!pkg.equals(attrs[0].trim())) continue; + if (range == null) return jar; + org.osgi.framework.Version v = org.osgi.framework.Version.emptyVersion; + for (int i = 1; i < attrs.length; i++) { + String a = attrs[i].trim(); + if (a.startsWith("version=")) { + try { + v = org.osgi.framework.Version.parseVersion(removeQuotes(a.substring(8))); + } + catch (IllegalArgumentException iae) { + } + } + } + if (range.includes(v)) return jar; } } catch (IOException e) { From 7b5608d1ef04302a4bbab927bac9bf636f35c82e Mon Sep 17 00:00:00 2001 From: Gian Tschingt Date: Tue, 17 Nov 2026 11:09:43 +0100 Subject: [PATCH 2/2] Address review comments on version handling - drop the null-range fallback in loadMissing, so a package range cannot load an out-of-range bundle; local jars still have to export the package in range - latestVersion only considers the same flavour (jre or android) when the range asks for one - add unit tests for isPreRelease, toRange, getMavenVersions, flavour and the unmapped lower-bound limitation; the isPreRelease table has no false positives, so the regex is unchanged - document toVersion extra segments and overflow, and point addFelixDefaults at the system-property override in framework() - keep the best jar version in a variable instead of re-reading manifests --- source/java/pom.xml | 13 ++ .../lucee/extension/osgi/BundleProvider.java | 33 ++++- .../lucee/extension/osgi/OSGiServiceImpl.java | 55 ++++++--- .../extension/osgi/VersionHandlingTest.java | 113 ++++++++++++++++++ 4 files changed, 199 insertions(+), 15 deletions(-) create mode 100644 source/java/test/org/lucee/extension/osgi/VersionHandlingTest.java diff --git a/source/java/pom.xml b/source/java/pom.xml index 1f736cd..2fc2947 100644 --- a/source/java/pom.xml +++ b/source/java/pom.xml @@ -37,6 +37,7 @@ src + test @@ -129,6 +130,12 @@ + + org.apache.maven.plugins + maven-surefire-plugin + 3.2.5 + + org.apache.maven.plugins maven-compiler-plugin @@ -200,6 +207,12 @@ ${lucee.version} provided + + org.junit.jupiter + junit-jupiter + 5.11.4 + test + diff --git a/source/java/src/org/lucee/extension/osgi/BundleProvider.java b/source/java/src/org/lucee/extension/osgi/BundleProvider.java index e05c6a9..1fcfbe2 100644 --- a/source/java/src/org/lucee/extension/osgi/BundleProvider.java +++ b/source/java/src/org/lucee/extension/osgi/BundleProvider.java @@ -504,6 +504,7 @@ public String latestVersion(String bundleName, org.osgi.framework.VersionRange r Info[] infos = getMappings().get(bundleName); if (infos == null) return null; boolean allowPreRelease = range != null && (isPreRelease(range.getLeft()) || isPreRelease(range.getRight())); + String requiredFlavour = flavour(range); List problems = new ArrayList<>(); boolean mapped = false; for (Info info: infos) { @@ -534,6 +535,7 @@ public String latestVersion(String bundleName, org.osgi.framework.VersionRange r while (m.find()) { String raw = m.group(1).trim(); if (!allowPreRelease && isPreRelease(raw)) continue; + if (!requiredFlavour.isEmpty() && !requiredFlavour.equals(flavour(raw))) continue; Version v = toVersion(raw, null); if (v == null) continue; if (range != null && !range.includes(v)) continue; @@ -569,6 +571,31 @@ public static boolean isPreRelease(Object version) { return !rest.isEmpty() && PRE_RELEASE.matcher(rest.startsWith(".") || rest.startsWith("-") || rest.startsWith("_") ? rest : "." + rest).find(); } + private static final java.util.regex.Pattern FLAVOUR = java.util.regex.Pattern.compile("(?i)^(jre|android)\\d*$"); + + /** + * the mutually exclusive classifier of a version, currently "jre" or "android" (as used by Guava), + * otherwise empty. When a range asks for one of these, {@link #latestVersion} only considers + * versions with the same flavour. + */ + static String flavour(Object version) { + if (version == null) return ""; + if (version instanceof org.osgi.framework.VersionRange) { + org.osgi.framework.VersionRange range = (org.osgi.framework.VersionRange) version; + String left = flavour(range.getLeft()); + return !left.isEmpty() ? left : flavour(range.getRight()); + } + String q; + if (version instanceof Version) q = ((Version) version).getQualifier(); + else { + Version v = toVersion(version.toString(), null); + q = v == null ? "" : v.getQualifier(); + } + if (q == null || q.isEmpty()) return ""; + java.util.regex.Matcher m = FLAVOUR.matcher(q); + return m.matches() ? m.group(1).toLowerCase() : ""; + } + private static String createToken(String prefix, String name) { String str = prefix + ":" + name; String lock = tokens.putIfAbsent(str, str); @@ -949,7 +976,11 @@ public Pair(long lastModified, BundleProvider bundleProvider) { /** * a version as OSGi version, this also accepts the Maven spelling: 33.8.0-jre becomes 33.8.0.jre, - * 2.17 becomes 2.17.0, 3.0-rc5 becomes 3.0.0.rc5 and 1.0.0.5 stays + * 2.17 becomes 2.17.0, 3.0-rc5 becomes 3.0.0.rc5 and 1.0.0.5 stays. + * Extra numeric segments become the qualifier with dots replaced by underscores (1.2.3.4.5 + * becomes 1.2.3.4_5), so two different Maven spellings can compare equal after parsing. + * A numeric part that does not fit in an int (for example 20030203000129) returns + * {@code defaultValue} silently; {@link #latestVersion} skips that entry. */ static Version toVersion(String version, Version defaultValue) { if (Util.isEmpty(version, true)) return defaultValue; diff --git a/source/java/src/org/lucee/extension/osgi/OSGiServiceImpl.java b/source/java/src/org/lucee/extension/osgi/OSGiServiceImpl.java index 628d8e7..e42e9b5 100644 --- a/source/java/src/org/lucee/extension/osgi/OSGiServiceImpl.java +++ b/source/java/src/org/lucee/extension/osgi/OSGiServiceImpl.java @@ -129,6 +129,7 @@ static void addFelixDefaults(Map config, Class felixClass) th for (String key: props.stringPropertyNames()) { if (!config.containsKey(key)) config.put(key, props.getProperty(key)); } + // system properties and environment variables still override these values later in framework() // the values above contain placeholders like ${jre-${felix.detect.jpms}} if (!config.containsKey("felix.systempackages.substitution")) config.put("felix.systempackages.substitution", "true"); } @@ -193,6 +194,17 @@ static String toLucee(org.osgi.framework.Version v) { return base + (c >= '0' && c <= '9' ? "." : "-") + q; } + /** + * the version to download when the bundle is not mapped to a Maven artifact. For a closed + * lower bound this is the lower bound itself, so a requirement of ">=X" is treated as the + * exact version X. Null when there is no range or the lower bound is open; download() then + * fails with a readable message. + */ + static String unmappedVersion(VersionRange range) { + if (range != null && range.getLeftType() == VersionRange.LEFT_CLOSED) return toLucee(range.getLeft()); + return null; + } + private static boolean matches(String symbolicName, org.osgi.framework.Version bundleVersion, String name, String version) { if (!name.equals(symbolicName)) return false; if (version == null || version.trim().isEmpty()) return true; @@ -272,8 +284,23 @@ private static File findJar(File dir, String name, String version) { return best; } + private static final class JarVersion { + final File jar; + final org.osgi.framework.Version version; + + JarVersion(File jar, org.osgi.framework.Version version) { + this.jar = jar; + this.version = version; + } + } + /** the jar with the newest version of the bundle inside the range, any version when the range is null */ private static File findJar(File dir, String name, VersionRange range) { + JarVersion best = findJarVersion(dir, name, range); + return best == null ? null : best.jar; + } + + private static JarVersion findJarVersion(File dir, String name, VersionRange range) { File[] jars = dir == null ? null : dir.listFiles((d, n) -> n.endsWith(".jar")); if (jars == null) return null; File best = null; @@ -287,7 +314,7 @@ private static File findJar(File dir, String name, VersionRange range) { bestVersion = v; } } - return best; + return best == null ? null : new JarVersion(best, bestVersion); } private Bundle install(BundleContext ctx, File jar) throws IOException { @@ -334,17 +361,20 @@ private Bundle load(String name, VersionRange range, File[] dirs) throws IOExcep Bundle b = find(ctx, name, range); if (b != null) return b; - File jar = findJar(bundleDirectory, name, range); + JarVersion best = findJarVersion(bundleDirectory, name, range); if (dirs != null) { for (File dir: dirs) { - File candidate = findJar(dir, name, range); - if (candidate != null && (jar == null || ((org.osgi.framework.Version) read(candidate)[1]).compareTo((org.osgi.framework.Version) read(jar)[1]) > 0)) jar = candidate; + JarVersion candidate = findJarVersion(dir, name, range); + if (candidate != null && (best == null || candidate.version.compareTo(best.version) > 0)) best = candidate; } } + File jar = best == null ? null : best.jar; if (jar == null) { String version = BundleProvider.getInstance().latestVersion(name, range); - // not a Maven artifact we know, the lower end of the range is the best guess - if (version == null && range != null && range.getLeftType() == VersionRange.LEFT_CLOSED) version = toLucee(range.getLeft()); + // not a Maven artifact we know, the lower end of a closed range is used as the exact + // version (a documented limitation: ">=X" is still exact X for unmapped bundles). + // an open lower bound leaves version null and download() fails with a readable message. + if (version == null) version = unmappedVersion(range); jar = download(name, version); } return install(ctx, jar); @@ -522,14 +552,11 @@ private boolean loadMissing(String message, File[] dirs, Set tried, List // a bundle that has the name of the package, like com.google.gson if (bundle == null && BundleProvider.getMappings().containsKey(name)) bundle = name; if (bundle != null) { - // the version of the package is the version of the bundle for most bundles - try { - load(bundle, range, dirs); - } - catch (IOException e) { - if (range == null) throw e; - load(bundle, (VersionRange) null, dirs); - } + // the version of the package is the version of the bundle for most bundles. + // do not fall back to any version when nothing fits the range (that would + // load a 3.x for a [2.17,3) package). local jars are only used when + // findExporting confirms Export-Package is inside the range. + load(bundle, range, dirs); loaded = true; } else { diff --git a/source/java/test/org/lucee/extension/osgi/VersionHandlingTest.java b/source/java/test/org/lucee/extension/osgi/VersionHandlingTest.java new file mode 100644 index 0000000..e75a7d2 --- /dev/null +++ b/source/java/test/org/lucee/extension/osgi/VersionHandlingTest.java @@ -0,0 +1,113 @@ +package org.lucee.extension.osgi; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.osgi.framework.BundleException; +import org.osgi.framework.Version; +import org.osgi.framework.VersionRange; + +class VersionHandlingTest { + + @ParameterizedTest(name = "{0} pre-release={1}") + @CsvSource({ + "33.8.0-jre, false", + "33.8.0-android, false", + "1.0.0.Final, false", + "1.0.0.RELEASE, false", + "1.2.3.sp1, false", + "1.0.0.v20230101, false", + "2.17.0, false", + "2.0.0-M1, true", + "5.4.0.Beta2, true", + "3.0-rc5, true", + "1.0-SNAPSHOT, true", + "1.0.0-ALPHA, true" + }) + void isPreReleaseTable(String version, boolean expected) { + assertEquals(expected, BundleProvider.isPreRelease(version), version); + } + + @Test + void toRangeFromGreaterEqualAndNotGreaterEqual() { + VersionRange r = OSGiServiceImpl.toRange("(version>=2.17.0)(!(version>=3.0.0))"); + assertEquals(VersionRange.LEFT_CLOSED, r.getLeftType()); + assertEquals(new Version(2, 17, 0), r.getLeft()); + assertEquals(new Version(3, 0, 0), r.getRight()); + assertEquals(VersionRange.RIGHT_OPEN, r.getRightType()); + assertTrue(r.includes(new Version(2, 17, 0))); + assertTrue(r.includes(new Version(2, 23, 0))); + assertFalse(r.includes(new Version(3, 0, 0))); + } + + @Test + void toRangeLessOrEqual() { + VersionRange r = OSGiServiceImpl.toRange("(version<=3.0.0)"); + assertEquals(Version.emptyVersion, r.getLeft()); + assertEquals(VersionRange.LEFT_CLOSED, r.getLeftType()); + assertEquals(new Version(3, 0, 0), r.getRight()); + assertEquals(VersionRange.RIGHT_CLOSED, r.getRightType()); + } + + @Test + void toRangeNotLessOrEqualIsOpenLowerBound() { + VersionRange r = OSGiServiceImpl.toRange("(!(version<=2.17.0))"); + assertEquals(new Version(2, 17, 0), r.getLeft()); + assertEquals(VersionRange.LEFT_OPEN, r.getLeftType()); + assertTrue(r.getRight() == null || !r.includes(r.getRight())); + assertFalse(r.includes(new Version(2, 17, 0))); + assertTrue(r.includes(new Version(2, 17, 1))); + } + + @Test + void toRangeEqualsIsExactVersion() { + VersionRange r = OSGiServiceImpl.toRange("(version=2.17.0)"); + assertEquals(new Version(2, 17, 0), r.getLeft()); + assertEquals(new Version(2, 17, 0), r.getRight()); + assertEquals(VersionRange.LEFT_CLOSED, r.getLeftType()); + assertEquals(VersionRange.RIGHT_CLOSED, r.getRightType()); + assertTrue(r.includes(new Version(2, 17, 0))); + assertFalse(r.includes(new Version(2, 17, 1))); + } + + @Test + void getMavenVersionsPrefersTheGivenSpelling() throws BundleException { + List jre = new BundleProvider.BundleDefinition("com.google.guava", "33.8.0-jre").getMavenVersions(); + assertEquals("33.8.0-jre", jre.get(0)); + assertTrue(jre.contains("33.8.0.jre")); + + List shortVersion = new BundleProvider.BundleDefinition("com.google.gson", "2.17.0").getMavenVersions(); + assertEquals("2.17.0", shortVersion.get(0)); + assertTrue(shortVersion.contains("2.17")); + } + + @Test + void flavourMatchesJreAndAndroid() { + assertEquals("jre", BundleProvider.flavour("33.8.0-jre")); + assertEquals("android", BundleProvider.flavour("33.8.0-android")); + assertEquals("", BundleProvider.flavour("33.8.0")); + assertEquals("jre", BundleProvider.flavour(VersionRange.valueOf("[33.8.0.jre,34.0.0)"))); + assertEquals("", BundleProvider.flavour(VersionRange.valueOf("[33.8.0,34.0.0)"))); + } + + @Test + void unmappedVersionUsesTheClosedLowerBound() { + assertEquals("2.17.0", OSGiServiceImpl.unmappedVersion(VersionRange.valueOf("[2.17.0,3.0.0)"))); + assertNull(OSGiServiceImpl.unmappedVersion(VersionRange.valueOf("(2.17.0,3.0.0)"))); + assertNull(OSGiServiceImpl.unmappedVersion(null)); + } + + @Test + void toVersionDocumentsExtraSegmentsAndOverflow() { + assertEquals(new Version(1, 2, 3, "4_5"), BundleProvider.toVersion("1.2.3.4.5", null)); + assertNull(BundleProvider.toVersion("1.2.20030203000129", null)); + assertEquals(new Version(0, 0, 0), BundleProvider.toVersion("1.2.20030203000129", Version.emptyVersion)); + } +}