1 package org
.argeo
.build
;
3 import static java
.lang
.System
.Logger
.Level
.DEBUG
;
4 import static java
.lang
.System
.Logger
.Level
.ERROR
;
5 import static java
.lang
.System
.Logger
.Level
.INFO
;
6 import static java
.lang
.System
.Logger
.Level
.TRACE
;
7 import static java
.lang
.System
.Logger
.Level
.WARNING
;
8 import static java
.nio
.file
.FileVisitResult
.CONTINUE
;
9 import static java
.nio
.file
.StandardOpenOption
.APPEND
;
10 import static java
.nio
.file
.StandardOpenOption
.CREATE
;
11 import static java
.util
.jar
.Attributes
.Name
.MANIFEST_VERSION
;
12 import static org
.argeo
.build
.Repackage
.ManifestHeader
.ARGEO_ORIGIN_DO_NOT_MODIFY
;
13 import static org
.argeo
.build
.Repackage
.ManifestHeader
.ARGEO_ORIGIN_M2
;
14 import static org
.argeo
.build
.Repackage
.ManifestHeader
.ARGEO_ORIGIN_M2_MERGE
;
15 import static org
.argeo
.build
.Repackage
.ManifestHeader
.ARGEO_ORIGIN_M2_REPO
;
16 import static org
.argeo
.build
.Repackage
.ManifestHeader
.ARGEO_ORIGIN_NO_METADATA_GENERATION
;
17 import static org
.argeo
.build
.Repackage
.ManifestHeader
.ARGEO_ORIGIN_SOURCES_URI
;
18 import static org
.argeo
.build
.Repackage
.ManifestHeader
.ARGEO_ORIGIN_URI
;
19 import static org
.argeo
.build
.Repackage
.ManifestHeader
.AUTOMATIC_MODULE_NAME
;
20 import static org
.argeo
.build
.Repackage
.ManifestHeader
.BUNDLE_LICENSE
;
21 import static org
.argeo
.build
.Repackage
.ManifestHeader
.BUNDLE_SYMBOLICNAME
;
22 import static org
.argeo
.build
.Repackage
.ManifestHeader
.BUNDLE_VERSION
;
23 import static org
.argeo
.build
.Repackage
.ManifestHeader
.ECLIPSE_SOURCE_BUNDLE
;
24 import static org
.argeo
.build
.Repackage
.ManifestHeader
.EXPORT_PACKAGE
;
25 import static org
.argeo
.build
.Repackage
.ManifestHeader
.IMPORT_PACKAGE
;
26 //import static org.argeo.build.Repackage.ManifestHeader.REQUIRE_BUNDLE;
27 import static org
.argeo
.build
.Repackage
.ManifestHeader
.SPDX_LICENSE_IDENTIFIER
;
29 import java
.io
.BufferedWriter
;
31 import java
.io
.FileNotFoundException
;
32 import java
.io
.IOException
;
33 import java
.io
.InputStream
;
34 import java
.io
.OutputStream
;
35 import java
.lang
.System
.Logger
;
37 import java
.net
.URISyntaxException
;
38 import java
.nio
.charset
.StandardCharsets
;
39 import java
.nio
.file
.DirectoryStream
;
40 import java
.nio
.file
.FileSystem
;
41 import java
.nio
.file
.FileSystems
;
42 import java
.nio
.file
.FileVisitResult
;
43 import java
.nio
.file
.Files
;
44 import java
.nio
.file
.Path
;
45 import java
.nio
.file
.PathMatcher
;
46 import java
.nio
.file
.Paths
;
47 import java
.nio
.file
.SimpleFileVisitor
;
48 import java
.nio
.file
.StandardCopyOption
;
49 import java
.nio
.file
.StandardOpenOption
;
50 import java
.nio
.file
.attribute
.BasicFileAttributes
;
51 import java
.util
.ArrayList
;
52 import java
.util
.HashMap
;
53 import java
.util
.Iterator
;
54 import java
.util
.List
;
56 import java
.util
.Objects
;
57 import java
.util
.Properties
;
59 import java
.util
.StringJoiner
;
60 import java
.util
.TreeMap
;
61 import java
.util
.TreeSet
;
62 import java
.util
.concurrent
.CompletableFuture
;
63 import java
.util
.jar
.Attributes
;
64 import java
.util
.jar
.JarEntry
;
65 import java
.util
.jar
.JarInputStream
;
66 import java
.util
.jar
.JarOutputStream
;
67 import java
.util
.jar
.Manifest
;
68 import java
.util
.zip
.Deflater
;
70 import aQute
.bnd
.osgi
.Analyzer
;
71 import aQute
.bnd
.osgi
.Jar
;
73 /** Repackages existing jar files into OSGi bundles in an A2 repository. */
74 public class Repackage
{
75 final static Logger logger
= System
.getLogger(Repackage
.class.getName());
78 * Environment variable on whether sources should be packaged separately or
79 * integrated in the bundles.
81 final static String ENV_SOURCE_BUNDLES
= "SOURCE_BUNDLES";
82 /** Environment variable on whether operations should be parallelised. */
83 final static String ENV_ARGEO_BUILD_SEQUENTIAL
= "ARGEO_BUILD_SEQUENTIAL";
85 /** Whether repackaging should run in parallel (default) or sequentially. */
86 final static boolean sequential
= Boolean
.parseBoolean(System
.getenv(ENV_ARGEO_BUILD_SEQUENTIAL
));
88 /** Main entry point. */
89 public static void main(String
[] args
) {
91 logger
.log(INFO
, "Build will be sequential");
92 if (args
.length
< 2) {
93 System
.err
.println("Usage: <path to a2 output dir> <category1> <category2> ...");
96 Path a2Base
= Paths
.get(args
[0]).toAbsolutePath().normalize();
97 Path descriptorsBase
= Paths
.get(".").toAbsolutePath().normalize();
98 Repackage factory
= new Repackage(a2Base
, descriptorsBase
);
100 List
<CompletableFuture
<Void
>> toDos
= new ArrayList
<>();
101 for (int i
= 1; i
< args
.length
; i
++) {
102 Path categoryPath
= Paths
.get(args
[i
]);
103 factory
.cleanPreviousFailedBuild(categoryPath
);
104 if (sequential
) // sequential processing happens here
105 factory
.processCategory(categoryPath
);
107 toDos
.add(CompletableFuture
.runAsync(() -> factory
.processCategory(categoryPath
)));
109 if (!sequential
)// parallel processing
110 CompletableFuture
.allOf(toDos
.toArray(new CompletableFuture
[toDos
.size()])).join();
113 StringBuilder sb
= new StringBuilder();
114 for (String licenseId
: licensesUsed
.keySet())
115 for (String name
: licensesUsed
.get(licenseId
))
116 sb
.append((licenseId
.equals("") ?
"Proprietary" : licenseId
) + "\t\t" + name
+ "\n");
117 logger
.log(INFO
, "# License summary:\n" + sb
);
120 /** Deletes remaining sub directories. */
121 void cleanPreviousFailedBuild(Path categoryPath
) {
122 Path outputCategoryPath
= a2Base
.resolve(categoryPath
);
123 if (!Files
.exists(outputCategoryPath
))
125 // clean previous failed build
127 for (Path subDir
: Files
.newDirectoryStream(outputCategoryPath
, (d
) -> Files
.isDirectory(d
))) {
128 if (Files
.exists(subDir
)) {
129 logger
.log(WARNING
, "Bundle dir " + subDir
130 + " already exists, probably from a previous failed build, deleting it...");
131 deleteDirectory(subDir
);
134 } catch (IOException e
) {
135 logger
.log(ERROR
, "Cannot clean previous build", e
);
139 /** MANIFEST headers. */
140 enum ManifestHeader
{
142 /** OSGi bundle symbolic name. */
143 BUNDLE_SYMBOLICNAME("Bundle-SymbolicName"), //
144 /** OSGi bundle version. */
145 BUNDLE_VERSION("Bundle-Version"), //
146 /** OSGi bundle license. */
147 BUNDLE_LICENSE("Bundle-License"), //
148 /** OSGi exported packages list. */
149 EXPORT_PACKAGE("Export-Package"), //
150 /** OSGi imported packages list. */
151 IMPORT_PACKAGE("Import-Package"), //
152 // /** OSGi required bundles. */
153 // REQUIRE_BUNDLE("Require-Bundle"), //
154 // /** OSGi path to embedded jar. */
155 // BUNDLE_CLASSPATH("Bundle-Classpath"), //
157 /** Java module name. */
158 AUTOMATIC_MODULE_NAME("Automatic-Module-Name"), //
160 /** Eclipse source bundle. */
161 ECLIPSE_SOURCE_BUNDLE("Eclipse-SourceBundle"), //
164 * SPDX license identifier.
166 * @see https://spdx.org/licenses/
168 SPDX_LICENSE_IDENTIFIER("SPDX-License-Identifier"), //
171 * Maven coordinates of the origin, possibly partial when using common.bnd or
174 ARGEO_ORIGIN_M2("Argeo-Origin-M2"), //
175 /** List of Maven coordinates to merge. */
176 ARGEO_ORIGIN_M2_MERGE("Argeo-Origin-M2-Merge"), //
177 /** Maven repository, if not the default one. */
178 ARGEO_ORIGIN_M2_REPO("Argeo-Origin-M2-Repo"), //
180 * Do not perform BND analysis of the origin component. Typically Import-Package
181 * and Export-Package will be kept untouched.
183 ARGEO_ORIGIN_NO_METADATA_GENERATION("Argeo-Origin-NoMetadataGeneration"), //
184 /** Keep JPMS module-info */
185 ARGEO_ORIGIN_KEEP_MODULE_INFO("Argeo-Origin-KeepModuleInfo"), //
187 // * Embed the original jar without modifying it (may be required by some
188 // * proprietary licenses, such as JCR Day License).
190 // ARGEO_ORIGIN_EMBED("Argeo-Origin-Embed"), //
192 * Do not modify original jar (may be required by some proprietary licenses,
193 * such as JCR Day License).
195 ARGEO_ORIGIN_DO_NOT_MODIFY("Argeo-Origin-Do-Not-Modify"), //
197 * Origin (non-Maven) URI of the component. It may be anything (jar, archive,
200 ARGEO_ORIGIN_URI("Argeo-Origin-URI"), //
202 * Origin (non-Maven) URI of the source of the component. It may be anything
203 * (jar, archive, code repository, etc.).
205 ARGEO_ORIGIN_SOURCES_URI("Argeo-Origin-Sources-URI"), //
208 final String headerName
;
210 private ManifestHeader(String headerName
) {
211 this.headerName
= headerName
;
215 public String
toString() {
219 /** Get the value from either a {@link Manifest} or a {@link Properties}. */
220 String
get(Object map
) {
221 if (map
instanceof Manifest manifest
)
222 return manifest
.getMainAttributes().getValue(headerName
);
223 else if (map
instanceof Properties props
)
224 return props
.getProperty(headerName
);
226 throw new IllegalArgumentException("Unsupported mapping " + map
.getClass());
229 /** Put the value into either a {@link Manifest} or a {@link Properties}. */
230 void put(Object map
, String value
) {
231 if (map
instanceof Manifest manifest
)
232 manifest
.getMainAttributes().putValue(headerName
, value
);
233 else if (map
instanceof Properties props
)
234 props
.setProperty(headerName
, value
);
236 throw new IllegalArgumentException("Unsupported mapping " + map
.getClass());
240 /** Name of the file centralising information for multiple M2 artifacts. */
241 final static String COMMON_BND
= "common.bnd";
242 /** Name of the file centralising information for mergin M2 artifacts. */
243 final static String MERGE_BND
= "merge.bnd";
245 * Subdirectory of the jar file where origin informations (changes, legal
246 * notices etc. are stored)
248 final static String ARGEO_ORIGIN
= "ARGEO-ORIGIN";
249 /** File detailing modifications to the original component. */
250 final static String CHANGES
= ARGEO_ORIGIN
+ "/changes";
252 * Name of the file at the root of the repackaged jar, which prominently
253 * notifies that the component has be repackaged.
255 final static String README_REPACKAGED
= "README.repackaged";
258 /** Summary of all license seen during the repackaging. */
259 final static Map
<String
, Set
<String
>> licensesUsed
= new TreeMap
<>();
261 /** Directory where to download archives */
262 final Path originBase
;
263 /** Directory where to download Maven artifacts */
264 final Path mavenBase
;
266 /** A2 repository base for binary bundles */
268 /** A2 repository base for source bundles */
269 final Path a2SrcBase
;
270 /** A2 base for native components */
271 final Path a2LibBase
;
272 /** Location of the descriptors driving the packaging */
273 final Path descriptorsBase
;
274 /** URIs of archives to download */
275 final Properties uris
= new Properties();
276 /** Mirrors for archive download. Key is URI prefix, value list of base URLs */
277 final Map
<String
, List
<String
>> mirrors
= new HashMap
<String
, List
<String
>>();
279 /** Whether sources should be packaged separately */
280 final boolean separateSources
;
282 /** Constructor initialises the various variables */
283 public Repackage(Path a2Base
, Path descriptorsBase
) {
284 separateSources
= Boolean
.parseBoolean(System
.getenv(ENV_SOURCE_BUNDLES
));
286 logger
.log(INFO
, "Sources will be packaged separately");
288 Objects
.requireNonNull(a2Base
);
289 Objects
.requireNonNull(descriptorsBase
);
290 this.originBase
= Paths
.get(System
.getProperty("user.home"), ".cache", "argeo/build/origin");
291 this.mavenBase
= Paths
.get(System
.getProperty("user.home"), ".m2", "repository");
293 // TODO define and use a build base
294 this.a2Base
= a2Base
;
295 this.a2SrcBase
= separateSources ? a2Base
.getParent().resolve(a2Base
.getFileName() + ".src") : a2Base
;
296 this.a2LibBase
= a2Base
.resolve("lib");
297 this.descriptorsBase
= descriptorsBase
;
298 if (!Files
.exists(this.descriptorsBase
))
299 throw new IllegalArgumentException(this.descriptorsBase
+ " does not exist");
302 Path urisPath
= this.descriptorsBase
.resolve("uris.properties");
303 if (Files
.exists(urisPath
)) {
304 try (InputStream in
= Files
.newInputStream(urisPath
)) {
306 } catch (IOException e
) {
307 throw new IllegalStateException("Cannot load " + urisPath
, e
);
312 Path eclipseMirrorsPath
= this.descriptorsBase
.resolve("eclipse.mirrors.txt");
313 List
<String
> eclipseMirrors
= new ArrayList
<>();
314 if (Files
.exists(eclipseMirrorsPath
)) {
316 eclipseMirrors
= Files
.readAllLines(eclipseMirrorsPath
, StandardCharsets
.UTF_8
);
317 } catch (IOException e
) {
318 throw new IllegalStateException("Cannot load " + eclipseMirrorsPath
, e
);
320 for (Iterator
<String
> it
= eclipseMirrors
.iterator(); it
.hasNext();) {
321 String value
= it
.next();
322 if (value
.strip().equals(""))
326 mirrors
.put("http://www.eclipse.org/downloads", eclipseMirrors
);
332 /** Process a whole category/group id. */
333 void processCategory(Path categoryRelativePath
) {
335 Path targetCategoryBase
= descriptorsBase
.resolve(categoryRelativePath
);
336 DirectoryStream
<Path
> bnds
= Files
.newDirectoryStream(targetCategoryBase
,
337 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
338 && !p
.getFileName().toString().equals(MERGE_BND
));
339 for (Path p
: bnds
) {
340 processSingleM2ArtifactDistributionUnit(p
);
343 DirectoryStream
<Path
> dus
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
344 for (Path duDir
: dus
) {
345 if (duDir
.getFileName().toString().startsWith("eclipse-")) {
346 processEclipseArchive(duDir
);
348 processM2BasedDistributionUnit(duDir
);
351 } catch (IOException e
) {
352 throw new RuntimeException("Cannot process category " + categoryRelativePath
, e
);
356 /** Process a standalone Maven artifact. */
357 void processSingleM2ArtifactDistributionUnit(Path bndFile
) {
359 Path categoryRelativePath
= descriptorsBase
.relativize(bndFile
.getParent());
360 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
362 Properties fileProps
= new Properties();
363 try (InputStream in
= Files
.newInputStream(bndFile
)) {
366 // use file name as symbolic name
367 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
368 String symbolicName
= bndFile
.getFileName().toString();
369 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
370 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
373 String m2Coordinates
= fileProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
374 if (m2Coordinates
== null)
375 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile
);
376 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
378 Path downloaded
= downloadMaven(fileProps
, artifact
);
380 boolean doNotModify
= Boolean
381 .parseBoolean(fileProps
.getOrDefault(ARGEO_ORIGIN_DO_NOT_MODIFY
.toString(), "false").toString());
383 processNotModified(targetCategoryBase
, downloaded
, fileProps
, artifact
);
387 // regular processing
388 A2Origin origin
= new A2Origin();
389 Path bundleDir
= processBndJar(downloaded
, targetCategoryBase
, fileProps
, artifact
, origin
);
390 downloadAndProcessM2Sources(fileProps
, artifact
, bundleDir
, false, false);
391 createJar(bundleDir
, origin
);
392 } catch (Exception e
) {
393 throw new RuntimeException("Cannot process " + bndFile
, e
);
398 * Process multiple Maven artifacts coming from a same project and therefore
399 * with information in common (typically the version), generating single bundles
400 * or merging them if necessary.
405 void processM2BasedDistributionUnit(Path duDir
) {
407 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
408 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
410 Path mergeBnd
= duDir
.resolve(MERGE_BND
);
411 if (Files
.exists(mergeBnd
)) // merge
412 mergeM2Artifacts(mergeBnd
);
414 Path commonBnd
= duDir
.resolve(COMMON_BND
);
415 if (!Files
.exists(commonBnd
))
418 Properties commonProps
= new Properties();
419 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
420 commonProps
.load(in
);
423 String m2Version
= commonProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
424 if (m2Version
== null) {
425 logger
.log(WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
426 return;// ignore, this is probably an Eclipse archive
428 if (!m2Version
.startsWith(":")) {
429 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
431 m2Version
= m2Version
.substring(1);
433 DirectoryStream
<Path
> ds
= Files
.newDirectoryStream(duDir
,
434 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
435 && !p
.getFileName().toString().equals(MERGE_BND
));
437 Properties fileProps
= new Properties();
438 try (InputStream in
= Files
.newInputStream(p
)) {
441 String m2Coordinates
= fileProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
442 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
443 if (artifact
.getVersion() == null) {
444 artifact
.setVersion(m2Version
);
446 logger
.log(DEBUG
, p
.getFileName() + " : Using version " + artifact
.getVersion()
447 + " specified in descriptor rather than " + m2Version
+ " specified in " + COMMON_BND
);
450 // prepare manifest entries
451 Properties mergedProps
= new Properties();
452 mergedProps
.putAll(commonProps
);
454 fileEntries
: for (Object key
: fileProps
.keySet()) {
455 if (ARGEO_ORIGIN_M2
.toString().equals(key
))
456 continue fileEntries
;
457 String value
= fileProps
.getProperty(key
.toString());
458 Object previousValue
= mergedProps
.put(key
.toString(), value
);
459 if (previousValue
!= null) {
461 commonBnd
+ ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
464 mergedProps
.put(ARGEO_ORIGIN_M2
.toString(), artifact
.toM2Coordinates());
465 if (!mergedProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
466 // use file name as symbolic name
467 String symbolicName
= p
.getFileName().toString();
468 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
469 mergedProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
473 Path downloaded
= downloadMaven(mergedProps
, artifact
);
475 boolean doNotModify
= Boolean
.parseBoolean(
476 mergedProps
.getOrDefault(ARGEO_ORIGIN_DO_NOT_MODIFY
.toString(), "false").toString());
478 processNotModified(targetCategoryBase
, downloaded
, mergedProps
, artifact
);
480 A2Origin origin
= new A2Origin();
481 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, mergedProps
, artifact
, origin
);
482 downloadAndProcessM2Sources(mergedProps
, artifact
, targetBundleDir
, false, false);
483 createJar(targetBundleDir
, origin
);
486 } catch (IOException e
) {
487 throw new RuntimeException("Cannot process " + duDir
, e
);
491 /** Merge multiple Maven artifacts. */
492 void mergeM2Artifacts(Path mergeBnd
) throws IOException
{
493 Path duDir
= mergeBnd
.getParent();
494 String category
= duDir
.getParent().getFileName().toString();
495 Path targetCategoryBase
= a2Base
.resolve(category
);
497 Properties mergeProps
= new Properties();
498 // first, load common properties
499 Path commonBnd
= duDir
.resolve(COMMON_BND
);
500 if (Files
.exists(commonBnd
))
501 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
504 // then, the merge properties themselves
505 try (InputStream in
= Files
.newInputStream(mergeBnd
)) {
509 String m2Version
= mergeProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
510 if (m2Version
== null) {
511 logger
.log(WARNING
, "Ignoring merging in " + duDir
+ " as it is not an M2-based distribution unit");
512 return;// ignore, this is probably an Eclipse archive
514 if (!m2Version
.startsWith(":")) {
515 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
517 m2Version
= m2Version
.substring(1);
518 mergeProps
.put(BUNDLE_VERSION
.toString(), m2Version
);
520 String artifactsStr
= mergeProps
.getProperty(ARGEO_ORIGIN_M2_MERGE
.toString());
521 if (artifactsStr
== null)
522 throw new IllegalArgumentException(mergeBnd
+ ": " + ARGEO_ORIGIN_M2_MERGE
+ " must be set");
524 String bundleSymbolicName
= mergeProps
.getProperty(BUNDLE_SYMBOLICNAME
.toString());
525 if (bundleSymbolicName
== null)
526 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd
);
527 CategoryNameVersion nameVersion
= new M2Artifact(category
+ ":" + bundleSymbolicName
+ ":" + m2Version
);
529 A2Origin origin
= new A2Origin();
530 Path bundleDir
= targetCategoryBase
.resolve(bundleSymbolicName
+ "." + nameVersion
.getBranch());
532 StringJoiner originDesc
= new StringJoiner(",");
533 String
[] artifacts
= artifactsStr
.split(",");
534 artifacts
: for (String str
: artifacts
) {
535 String m2Coordinates
= str
.trim();
536 if ("".equals(m2Coordinates
))
538 M2Artifact artifact
= new M2Artifact(m2Coordinates
.trim());
539 if (artifact
.getVersion() == null)
540 artifact
.setVersion(m2Version
);
541 originDesc
.add(artifact
.toString());
542 Path downloaded
= downloadMaven(mergeProps
, artifact
);
544 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(downloaded
), false)) {
545 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
546 if (entry
.isDirectory())
548 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".DSA")
549 || entry
.getName().endsWith(".SF")) {
550 origin
.deleted
.add("cryptographic signatures from " + artifact
);
553 if (entry
.getName().endsWith("module-info.class")) { // skip Java 9 module info
554 origin
.deleted
.add("Java module information (module-info.class) from " + artifact
);
557 if (entry
.getName().startsWith("META-INF/versions/")) { // skip multi-version
558 origin
.deleted
.add("additional Java versions (META-INF/versions) from " + artifact
);
561 if (entry
.getName().startsWith("META-INF/maven/")) {
562 origin
.deleted
.add("Maven information (META-INF/maven) from " + artifact
);
565 if (entry
.getName().startsWith(".cache/")) { // Apache SSHD
566 origin
.deleted
.add("cache directory (.cache) from " + artifact
);
569 if (entry
.getName().equals("META-INF/DEPENDENCIES")) {
570 origin
.deleted
.add("Dependencies (META-INF/DEPENDENCIES) from " + artifact
);
573 if (entry
.getName().equals("META-INF/MANIFEST.MF")) {
574 Path originalManifest
= bundleDir
.resolve(ARGEO_ORIGIN
).resolve(artifact
.getGroupId())
575 .resolve(artifact
.getArtifactId()).resolve("MANIFEST.MF");
576 Files
.createDirectories(originalManifest
.getParent());
577 try (OutputStream out
= Files
.newOutputStream(originalManifest
)) {
578 Files
.copy(jarIn
, originalManifest
);
581 "original MANIFEST (" + bundleDir
.relativize(originalManifest
) + ") from " + artifact
);
585 if (entry
.getName().endsWith("NOTICE") || entry
.getName().endsWith("NOTICE.txt")
586 || entry
.getName().endsWith("NOTICE.md") || entry
.getName().endsWith("LICENSE")
587 || entry
.getName().endsWith("LICENSE.md") || entry
.getName().endsWith("LICENSE-notice.md")
588 || entry
.getName().endsWith("COPYING") || entry
.getName().endsWith("COPYING.LESSER")) {
589 Path artifactOriginDir
= bundleDir
.resolve(ARGEO_ORIGIN
).resolve(artifact
.getGroupId())
590 .resolve(artifact
.getArtifactId());
591 Path target
= artifactOriginDir
.resolve(entry
.getName());
592 Files
.createDirectories(target
.getParent());
593 Files
.copy(jarIn
, target
);
594 origin
.moved
.add(entry
.getName() + " in " + artifact
+ " to " + bundleDir
.relativize(target
));
597 Path target
= bundleDir
.resolve(entry
.getName());
598 Files
.createDirectories(target
.getParent());
599 if (!Files
.exists(target
)) {
600 Files
.copy(jarIn
, target
);
602 if (entry
.getName().startsWith("META-INF/services/")) {
603 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
604 out
.write("\n".getBytes());
605 jarIn
.transferTo(out
);
606 logger
.log(DEBUG
, artifact
.getArtifactId() + " - Appended " + entry
.getName());
608 origin
.modified
.add(entry
.getName() + ", merging from " + artifact
);
609 } else if (entry
.getName().startsWith("org/apache/batik/")) {
610 logger
.log(TRACE
, "Skip " + entry
.getName());
612 } else if (entry
.getName().startsWith("META-INF/NOTICE")) {
613 logger
.log(WARNING
, "Skip " + entry
.getName() + " from " + artifact
);
617 throw new IllegalStateException("File " + target
+ " from " + artifact
+ " already exists");
620 logger
.log(TRACE
, () -> "Copied " + target
);
623 origin
.added
.add("binary content of " + artifact
);
626 downloadAndProcessM2Sources(mergeProps
, artifact
, bundleDir
, true, false);
629 // additional service files
630 Path servicesDir
= duDir
.resolve("services");
631 if (Files
.exists(servicesDir
)) {
632 for (Path p
: Files
.newDirectoryStream(servicesDir
)) {
633 Path target
= bundleDir
.resolve("META-INF/services/").resolve(p
.getFileName());
634 try (InputStream in
= Files
.newInputStream(p
);
635 OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
);) {
636 out
.write("\n".getBytes());
638 logger
.log(DEBUG
, "Appended " + p
);
640 origin
.added
.add(bundleDir
.relativize(target
).toString());
645 Map
<String
, String
> entries
= new TreeMap
<>();
646 try (Analyzer bndAnalyzer
= new Analyzer()) {
647 bndAnalyzer
.setProperties(mergeProps
);
648 Jar jar
= new Jar(bundleDir
.toFile());
649 bndAnalyzer
.setJar(jar
);
650 Manifest manifest
= bndAnalyzer
.calcManifest();
652 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
653 Object value
= manifest
.getMainAttributes().get(key
);
655 switch (key
.toString()) {
657 case "Bnd-LastModified":
661 if ("Require-Capability".equals(key
.toString())
662 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\"")) {
663 origin
.deleted
.add("MANIFEST header " + key
);
664 continue keys
;// hack for very old classes
666 entries
.put(key
.toString(), value
.toString());
668 } catch (Exception e
) {
669 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
672 Manifest manifest
= new Manifest();
673 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
674 Files
.createDirectories(manifestPath
.getParent());
675 for (String key
: entries
.keySet()) {
676 String value
= entries
.get(key
);
677 manifest
.getMainAttributes().putValue(key
, value
);
679 manifest
.getMainAttributes().putValue(ARGEO_ORIGIN_M2
.toString(), originDesc
.toString());
681 processLicense(bundleDir
, manifest
);
684 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
687 createJar(bundleDir
, origin
);
690 /** Generates MANIFEST using BND. */
691 Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
, M2Artifact artifact
,
694 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
695 boolean doNotModifyManifest
= Boolean
.parseBoolean(
696 fileProps
.getOrDefault(ARGEO_ORIGIN_NO_METADATA_GENERATION
.toString(), "false").toString());
698 // Note: we always force the symbolic name
699 if (doNotModifyManifest
) {
700 for (Object key
: fileProps
.keySet()) {
701 String value
= fileProps
.getProperty(key
.toString());
702 additionalEntries
.put(key
.toString(), value
);
705 if (artifact
!= null) {
706 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
707 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
709 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
710 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
714 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
715 fileProps
.put(EXPORT_PACKAGE
.toString(),
716 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
720 try (Analyzer bndAnalyzer
= new Analyzer()) {
721 bndAnalyzer
.setProperties(fileProps
);
722 Jar jar
= new Jar(downloaded
.toFile());
723 bndAnalyzer
.setJar(jar
);
724 Manifest manifest
= bndAnalyzer
.calcManifest();
726 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
727 Object value
= manifest
.getMainAttributes().get(key
);
729 switch (key
.toString()) {
731 case "Bnd-LastModified":
735 if ("Require-Capability".equals(key
.toString())
736 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\"")) {
737 origin
.deleted
.add("MANIFEST header " + key
);
738 continue keys
;// !! hack for very old classes
740 additionalEntries
.put(key
.toString(), value
.toString());
744 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
, origin
);
745 logger
.log(DEBUG
, () -> "Processed " + downloaded
);
746 return targetBundleDir
;
747 } catch (Exception e
) {
748 throw new RuntimeException("Cannot BND process " + downloaded
, e
);
753 /** Process an artifact that should not be modified. */
754 void processNotModified(Path targetCategoryBase
, Path downloaded
, Properties fileProps
, M2Artifact artifact
)
756 // Some proprietary or signed artifacts do not allow any modification
757 // When releasing (with separate sources), we just copy it
758 Path unmodifiedTarget
= targetCategoryBase
759 .resolve(fileProps
.getProperty(BUNDLE_SYMBOLICNAME
.toString()) + "." + artifact
.getBranch() + ".jar");
760 Files
.createDirectories(unmodifiedTarget
.getParent());
761 Files
.copy(downloaded
, unmodifiedTarget
, StandardCopyOption
.REPLACE_EXISTING
);
762 Path bundleDir
= targetCategoryBase
763 .resolve(fileProps
.getProperty(BUNDLE_SYMBOLICNAME
.toString()) + "." + artifact
.getBranch());
764 downloadAndProcessM2Sources(fileProps
, artifact
, bundleDir
, false, true);
766 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(unmodifiedTarget
))) {
767 manifest
= jarIn
.getManifest();
769 createSourceJar(bundleDir
, manifest
, fileProps
);
772 /** Download and integrates sources for a single Maven artifact. */
773 void downloadAndProcessM2Sources(Properties props
, M2Artifact artifact
, Path targetBundleDir
, boolean merging
,
774 boolean unmodified
) throws IOException
{
776 String repoStr
= props
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
777 ? props
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
779 String alternateUri
= props
.getProperty(ARGEO_ORIGIN_SOURCES_URI
.toString());
780 M2Artifact sourcesArtifact
= new M2Artifact(artifact
.toM2Coordinates(), "sources");
781 URI sourcesUrl
= alternateUri
!= null ?
new URI(alternateUri
)
782 : M2ConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
783 Path sourcesDownloaded
= downloadMaven(sourcesUrl
, sourcesArtifact
);
784 processM2SourceJar(sourcesDownloaded
, targetBundleDir
, merging ? artifact
: null, unmodified
);
785 logger
.log(TRACE
, () -> "Processed source " + sourcesDownloaded
);
786 } catch (Exception e
) {
787 logger
.log(ERROR
, () -> "Cannot download source for " + artifact
);
792 /** Integrate sources from a downloaded jar file. */
793 void processM2SourceJar(Path file
, Path bundleDir
, M2Artifact mergingFrom
, boolean unmodified
) throws IOException
{
794 A2Origin origin
= new A2Origin();
795 Path sourceDir
= separateSources
|| unmodified ? bundleDir
.getParent().resolve(bundleDir
.toString() + ".src")
796 : bundleDir
.resolve("OSGI-OPT/src");
797 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
799 String mergingMsg
= "";
800 if (mergingFrom
!= null)
801 mergingMsg
= " of " + mergingFrom
;
803 Files
.createDirectories(sourceDir
);
805 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
806 String relPath
= entry
.getName();
807 if (entry
.isDirectory())
809 if (entry
.getName().equals("META-INF/MANIFEST.MF")) {// skip META-INF entries
810 origin
.deleted
.add("MANIFEST.MF from the sources" + mergingMsg
);
814 if (entry
.getName().startsWith("module-info.java")) {// skip Java module information
815 origin
.deleted
.add("Java module information from the sources (module-info.java)" + mergingMsg
);
818 if (entry
.getName().startsWith("/")) { // absolute paths
819 int metaInfIndex
= entry
.getName().indexOf("META-INF");
820 if (metaInfIndex
>= 0) {
821 relPath
= entry
.getName().substring(metaInfIndex
);
822 origin
.moved
.add(" to " + relPath
+ " entry with absolute path " + entry
.getName());
824 logger
.log(WARNING
, entry
.getName() + " has an absolute path");
825 origin
.deleted
.add(entry
.getName() + " from the sources" + mergingMsg
);
830 Path target
= sourceDir
.resolve(relPath
);
831 Files
.createDirectories(target
.getParent());
832 if (!Files
.exists(target
)) {
833 Files
.copy(jarIn
, target
);
834 logger
.log(TRACE
, () -> "Copied source " + target
);
836 logger
.log(TRACE
, () -> target
+ " already exists, skipping...");
841 if (separateSources
|| unmodified
) {
842 origin
.appendChanges(sourceDir
);
844 origin
.added
.add("source code under OSGI-OPT/src");
845 origin
.appendChanges(bundleDir
);
849 /** Download a Maven artifact. */
850 Path
downloadMaven(Properties props
, M2Artifact artifact
) throws IOException
{
851 String repoStr
= props
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
852 ? props
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
854 String alternateUri
= props
.getProperty(ARGEO_ORIGIN_URI
.toString());
856 URI uri
= alternateUri
!= null ?
new URI(alternateUri
) : M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
857 return downloadMaven(uri
, artifact
);
858 } catch (URISyntaxException e
) {
859 throw new IllegalArgumentException("Wrong aritfact URI", e
);
863 /** Download a Maven artifact. */
864 Path
downloadMaven(URI uri
, M2Artifact artifact
) throws IOException
{
865 return download(uri
, mavenBase
, M2ConventionsUtils
.artifactPath("", artifact
));
871 /** Process an archive in Eclipse format. */
872 void processEclipseArchive(Path duDir
) {
874 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
875 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
876 Files
.createDirectories(targetCategoryBase
);
877 // first delete all directories from previous builds
878 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)))
879 deleteDirectory(dir
);
881 Files
.createDirectories(originBase
);
883 Path commonBnd
= duDir
.resolve(COMMON_BND
);
884 Properties commonProps
= new Properties();
885 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
886 commonProps
.load(in
);
888 String url
= commonProps
.getProperty(ARGEO_ORIGIN_URI
.toString());
890 url
= uris
.getProperty(duDir
.getFileName().toString());
892 throw new IllegalStateException("No url available for " + duDir
);
893 commonProps
.put(ARGEO_ORIGIN_URI
.toString(), url
);
895 Path downloaded
= tryDownloadArchive(url
, originBase
);
897 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
900 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
901 Properties includes
= new Properties();
902 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
905 for (Object pattern
: includes
.keySet()) {
906 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
907 includeMatchers
.add(pathMatcher
);
910 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
911 Path excludeFile
= duDir
.resolve("excludes.properties");
912 if (Files
.exists(excludeFile
)) {
913 Properties excludes
= new Properties();
914 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
917 for (Object pattern
: excludes
.keySet()) {
918 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
919 excludeMatchers
.add(pathMatcher
);
923 // keys are the bundle directories
924 Map
<Path
, A2Origin
> origins
= new HashMap
<>();
925 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
928 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
929 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
930 if (includeMatcher
.matches(file
)) {
931 for (PathMatcher excludeMatcher
: excludeMatchers
) {
932 if (excludeMatcher
.matches(file
)) {
933 logger
.log(TRACE
, "Skipping excluded " + file
);
934 return FileVisitResult
.CONTINUE
;
937 if (file
.getFileName().toString().contains(".source_")) {
938 processEclipseSourceJar(file
, targetCategoryBase
);
939 logger
.log(DEBUG
, () -> "Processed source " + file
);
941 Map
<String
, String
> map
= new HashMap
<>();
942 for (Object key
: commonProps
.keySet())
943 map
.put(key
.toString(), commonProps
.getProperty(key
.toString()));
944 A2Origin origin
= new A2Origin();
945 Path bundleDir
= processBundleJar(file
, targetCategoryBase
, map
, origin
);
946 if (bundleDir
== null) {
947 logger
.log(WARNING
, "No bundle dir created for " + file
+ ", skipping...");
948 return FileVisitResult
.CONTINUE
;
950 origins
.put(bundleDir
, origin
);
951 logger
.log(DEBUG
, () -> "Processed " + file
);
953 break includeMatchers
;
956 return FileVisitResult
.CONTINUE
;
960 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)
961 && p
.getFileName().toString().indexOf('.') >= 0 && !p
.getFileName().toString().endsWith(".src"));
962 for (Path bundleDir
: dirs
) {
963 A2Origin origin
= origins
.get(bundleDir
);
964 Objects
.requireNonNull(origin
, "No A2 origin found for " + bundleDir
);
965 createJar(bundleDir
, origin
);
967 } catch (IOException e
) {
968 throw new RuntimeException("Cannot process " + duDir
, e
);
973 /** Process sources in Eclipse format. */
974 void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
976 A2Origin origin
= new A2Origin();
978 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
979 Manifest manifest
= jarIn
.getManifest();
981 String
[] relatedBundle
= manifest
.getMainAttributes().getValue(ECLIPSE_SOURCE_BUNDLE
.toString())
983 String version
= relatedBundle
[1].substring("version=\"".length());
984 version
= version
.substring(0, version
.length() - 1);
985 NameVersion nameVersion
= new NameVersion(relatedBundle
[0], version
);
986 bundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
988 Path sourceDir
= separateSources ? bundleDir
.getParent().resolve(bundleDir
.toString() + ".src")
989 : bundleDir
.resolve("OSGI-OPT/src");
991 Files
.createDirectories(sourceDir
);
993 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
994 if (entry
.isDirectory())
996 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
998 Path target
= sourceDir
.resolve(entry
.getName());
999 Files
.createDirectories(target
.getParent());
1000 Files
.copy(jarIn
, target
);
1001 logger
.log(TRACE
, () -> "Copied source " + target
);
1004 // write the changes
1005 if (separateSources
) {
1006 origin
.appendChanges(sourceDir
);
1008 origin
.added
.add("source code under OSGI-OPT/src");
1009 origin
.appendChanges(bundleDir
);
1012 } catch (IOException e
) {
1013 throw new IllegalStateException("Cannot process " + file
, e
);
1020 /** Normalise a single (that is, non-merged) bundle. */
1021 Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
, A2Origin origin
) throws IOException
{
1022 // boolean embed = Boolean.parseBoolean(entries.getOrDefault(ARGEO_ORIGIN_EMBED.toString(), "false").toString());
1023 boolean doNotModify
= Boolean
.parseBoolean(
1024 entries
.getOrDefault(ManifestHeader
.ARGEO_ORIGIN_DO_NOT_MODIFY
.toString(), "false").toString());
1025 boolean keepModuleInfo
= Boolean
.parseBoolean(
1026 entries
.getOrDefault(ManifestHeader
.ARGEO_ORIGIN_KEEP_MODULE_INFO
.toString(), "false").toString());
1027 NameVersion nameVersion
;
1030 boolean isSingleton
= false;
1032 Manifest sourceManifest
;
1033 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
1034 sourceManifest
= jarIn
.getManifest();
1035 if (sourceManifest
== null)
1036 logger
.log(WARNING
, file
+ " has no manifest");
1037 manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
1039 String rawSourceSymbolicName
= manifest
.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME
.toString());
1040 if (rawSourceSymbolicName
!= null) {
1041 // make sure there is no directive
1042 String
[] arr
= rawSourceSymbolicName
.split(";");
1043 for (int i
= 1; i
< arr
.length
; i
++) {
1044 if (arr
[i
].trim().equals("singleton:=true"))
1046 logger
.log(DEBUG
, file
.getFileName() + " is a singleton");
1049 // remove problematic entries in MANIFEST
1050 manifest
.getEntries().clear();
1052 String ourSymbolicName
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
1053 String ourVersion
= entries
.get(BUNDLE_VERSION
.toString());
1055 if (ourSymbolicName
!= null && ourVersion
!= null) {
1056 nameVersion
= new NameVersion(ourSymbolicName
, ourVersion
);
1058 nameVersion
= nameVersionFromManifest(manifest
);
1059 if (nameVersion
== null)
1060 throw new IllegalStateException("Could not compute name/version from Manifest");
1061 if (ourVersion
!= null && !nameVersion
.getVersion().equals(ourVersion
)) {
1063 "Original version is " + nameVersion
.getVersion() + " while new version is " + ourVersion
);
1064 entries
.put(BUNDLE_VERSION
.toString(), ourVersion
);
1066 if (ourSymbolicName
!= null) {
1067 // we always force our symbolic name
1068 nameVersion
.setName(ourSymbolicName
);
1072 bundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
1074 // copy original MANIFEST
1075 if (sourceManifest
!= null) {
1076 Path originalManifest
= bundleDir
.resolve(ARGEO_ORIGIN
).resolve("MANIFEST.MF");
1077 Files
.createDirectories(originalManifest
.getParent());
1078 try (OutputStream out
= Files
.newOutputStream(originalManifest
)) {
1079 sourceManifest
.write(out
);
1081 origin
.moved
.add("original MANIFEST to " + bundleDir
.relativize(originalManifest
));
1084 // force Java 9 module name
1085 if (!keepModuleInfo
)
1086 entries
.put(ManifestHeader
.AUTOMATIC_MODULE_NAME
.toString(), nameVersion
.getName());
1088 boolean isNative
= false;
1091 if (bundleDir
.startsWith(a2LibBase
)) {
1093 Path libRelativePath
= a2LibBase
.relativize(bundleDir
);
1094 os
= libRelativePath
.getName(0).toString();
1095 arch
= libRelativePath
.getName(1).toString();
1100 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
1101 if (entry
.isDirectory())
1104 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".DSA")
1105 || entry
.getName().endsWith(".SF")) {
1106 origin
.deleted
.add("cryptographic signatures");
1109 if (entry
.getName().endsWith("module-info.class") && !keepModuleInfo
) { // skip Java 9 module info
1110 origin
.deleted
.add("Java module information (module-info.class)");
1113 if (entry
.getName().startsWith("META-INF/versions/")) { // skip multi-version
1114 origin
.deleted
.add("additional Java versions (META-INF/versions)");
1117 if (entry
.getName().startsWith("META-INF/maven/")) {
1118 origin
.deleted
.add("Maven information (META-INF/maven)");
1121 // skip file system providers as they cause issues with native image
1122 if (entry
.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider")) {
1124 .add("file system providers (META-INF/services/java.nio.file.spi.FileSystemProvider)");
1128 if (entry
.getName().startsWith("OSGI-OPT/src/")) { // skip embedded sources
1129 origin
.deleted
.add("embedded sources");
1132 Path target
= bundleDir
.resolve(entry
.getName());
1133 Files
.createDirectories(target
.getParent());
1134 Files
.copy(jarIn
, target
);
1137 boolean removeDllFromJar
= true;
1138 if (isNative
&& (entry
.getName().endsWith(".so") || entry
.getName().endsWith(".dll")
1139 || entry
.getName().endsWith(".jnilib") || entry
.getName().endsWith(".a"))) {
1140 Path categoryDir
= bundleDir
.getParent();
1141 boolean copyDll
= false;
1142 Path targetDll
= categoryDir
.resolve(bundleDir
.relativize(target
));
1143 if (nameVersion
.getName().equals("com.sun.jna")) {
1144 if (arch
.equals("x86_64"))
1146 if (os
.equals("macosx"))
1148 if (target
.getParent().getFileName().toString().equals(os
+ "-" + arch
)) {
1151 targetDll
= categoryDir
.resolve(target
.getFileName());
1156 Files
.createDirectories(targetDll
.getParent());
1157 if (Files
.exists(targetDll
))
1158 Files
.delete(targetDll
);
1159 Files
.copy(target
, targetDll
);
1162 if (removeDllFromJar
) {
1163 Files
.delete(target
);
1164 origin
.deleted
.add(bundleDir
.relativize(target
).toString());
1167 logger
.log(TRACE
, () -> "Copied " + target
);
1172 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
1173 Files
.createDirectories(manifestPath
.getParent());
1175 if (isSingleton
&& entries
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
1176 entries
.put(BUNDLE_SYMBOLICNAME
.toString(),
1177 entries
.get(BUNDLE_SYMBOLICNAME
.toString()) + ";singleton:=true");
1180 // Final MANIFEST decisions
1181 // We also check the original OSGi metadata and compare with our changes
1182 for (String key
: entries
.keySet()) {
1183 String value
= entries
.get(key
);
1184 String previousValue
= manifest
.getMainAttributes().getValue(key
);
1185 boolean wasDifferent
= previousValue
!= null && !previousValue
.equals(value
);
1186 boolean keepPrevious
= false;
1188 if (SPDX_LICENSE_IDENTIFIER
.toString().equals(key
) && previousValue
!= null)
1189 keepPrevious
= true;
1190 else if (BUNDLE_VERSION
.toString().equals(key
) && wasDifferent
)
1191 if (previousValue
.equals(value
+ ".0")) // typically a Maven first release
1192 keepPrevious
= true;
1195 if (logger
.isLoggable(DEBUG
))
1196 logger
.log(DEBUG
, file
.getFileName() + ": " + key
+ " was NOT modified, value kept is "
1197 + previousValue
+ ", not overriden with " + value
);
1198 value
= previousValue
;
1202 manifest
.getMainAttributes().putValue(key
, value
);
1203 if (wasDifferent
&& !keepPrevious
) {
1204 if (IMPORT_PACKAGE
.toString().equals(key
) || EXPORT_PACKAGE
.toString().equals(key
))
1205 logger
.log(TRACE
, () -> file
.getFileName() + ": " + key
+ " was modified");
1206 else if (BUNDLE_SYMBOLICNAME
.toString().equals(key
) || AUTOMATIC_MODULE_NAME
.toString().equals(key
))
1208 file
.getFileName() + ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
1211 file
.getFileName() + ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
1212 origin
.modified
.add("MANIFEST header " + key
);
1215 // !! hack to remove unresolvable
1216 if (key
.equals("Provide-Capability") || key
.equals("Require-Capability"))
1217 if (nameVersion
.getName().equals("osgi.core") || nameVersion
.getName().equals("osgi.cmpn")) {
1218 manifest
.getMainAttributes().remove(key
);
1219 origin
.deleted
.add("MANIFEST header " + key
);
1223 // de-pollute MANIFEST
1224 for (Iterator
<Map
.Entry
<Object
, Object
>> manifestEntries
= manifest
.getMainAttributes().entrySet()
1225 .iterator(); manifestEntries
.hasNext();) {
1226 Map
.Entry
<Object
, Object
> manifestEntry
= manifestEntries
.next();
1227 String key
= manifestEntry
.getKey().toString();
1228 // TODO make it more generic
1229 // if (key.equals(REQUIRE_BUNDLE.toString()) && nameVersion.getName().equals("com.sun.jna.platform"))
1230 // manifestEntries.remove();
1232 case "Archiver-Version":
1235 case "Originally-Created-By":
1237 case "Bnd-LastModified":
1238 manifestEntries
.remove();
1239 origin
.deleted
.add("MANIFEST header " + manifestEntry
.getKey());
1242 if (sourceManifest
!= null && !sourceManifest
.getMainAttributes().containsKey(manifestEntry
.getKey()))
1243 origin
.added
.add("MANIFEST header " + manifestEntry
.getKey());
1247 processLicense(bundleDir
, manifest
);
1249 origin
.modified
.add("MANIFEST (META-INF/MANIFEST.MF)");
1250 // write the MANIFEST
1251 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
1252 manifest
.write(out
);
1257 /** Process SPDX license identifier. */
1258 void processLicense(Path bundleDir
, Manifest manifest
) {
1259 String spdxLicenceId
= manifest
.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER
.toString());
1260 String bundleLicense
= manifest
.getMainAttributes().getValue(BUNDLE_LICENSE
.toString());
1261 if (spdxLicenceId
== null) {
1262 logger
.log(ERROR
, bundleDir
.getFileName() + ": " + SPDX_LICENSE_IDENTIFIER
+ " not available, "
1263 + BUNDLE_LICENSE
+ " is " + bundleLicense
);
1265 // only use the first licensing option
1266 int orIndex
= spdxLicenceId
.indexOf(" OR ");
1268 spdxLicenceId
= spdxLicenceId
.substring(0, orIndex
).trim();
1270 String bundleDirName
= bundleDir
.getFileName().toString();
1271 // force licenses of some well-known components
1272 // even if we say otherwise (typically because from an Eclipse archive)
1273 if (bundleDirName
.startsWith("org.apache."))
1274 spdxLicenceId
= "Apache-2.0";
1275 if (bundleDirName
.startsWith("com.sun.jna."))
1276 spdxLicenceId
= "Apache-2.0";
1277 if (bundleDirName
.startsWith("com.ibm.icu."))
1278 spdxLicenceId
= "ICU";
1279 if (bundleDirName
.startsWith("javax.annotation."))
1280 spdxLicenceId
= "GPL-2.0-only WITH Classpath-exception-2.0";
1281 if (bundleDirName
.startsWith("javax.inject."))
1282 spdxLicenceId
= "Apache-2.0";
1283 if (bundleDirName
.startsWith("org.osgi."))
1284 spdxLicenceId
= "Apache-2.0";
1286 manifest
.getMainAttributes().putValue(SPDX_LICENSE_IDENTIFIER
.toString(), spdxLicenceId
);
1287 if (!licensesUsed
.containsKey(spdxLicenceId
))
1288 licensesUsed
.put(spdxLicenceId
, new TreeSet
<>());
1289 licensesUsed
.get(spdxLicenceId
).add(bundleDir
.getParent().getFileName() + "/" + bundleDir
.getFileName());
1296 /** Recursively deletes a directory. */
1297 static void deleteDirectory(Path path
) throws IOException
{
1298 if (!Files
.exists(path
))
1300 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
1302 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
1305 Files
.delete(directory
);
1310 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1317 /** Extract name/version from a MANIFEST. */
1318 NameVersion
nameVersionFromManifest(Manifest manifest
) {
1319 Attributes attrs
= manifest
.getMainAttributes();
1321 String symbolicName
= attrs
.getValue(ManifestHeader
.BUNDLE_SYMBOLICNAME
.toString());
1322 if (symbolicName
== null)
1324 // make sure there is no directive
1325 symbolicName
= symbolicName
.split(";")[0];
1327 String version
= attrs
.getValue(ManifestHeader
.BUNDLE_VERSION
.toString());
1328 return new NameVersion(symbolicName
, version
);
1331 /** Try to download from an URI. */
1332 Path
tryDownloadArchive(String uriStr
, Path dir
) throws IOException
{
1334 List
<String
> urlBases
= null;
1335 String uriPrefix
= null;
1336 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
1337 if (uriStr
.startsWith(uriPref
)) {
1338 if (mirrors
.get(uriPref
).size() > 0) {
1339 urlBases
= mirrors
.get(uriPref
);
1340 uriPrefix
= uriPref
;
1345 if (urlBases
== null)
1347 return downloadArchive(new URI(uriStr
), dir
);
1348 } catch (FileNotFoundException
| URISyntaxException e
) {
1349 throw new FileNotFoundException("Cannot find " + uriStr
);
1353 for (String urlBase
: urlBases
) {
1354 String relativePath
= uriStr
.substring(uriPrefix
.length());
1355 String uStr
= urlBase
+ relativePath
;
1357 return downloadArchive(new URI(uStr
), dir
);
1358 } catch (FileNotFoundException
| URISyntaxException e
) {
1359 logger
.log(WARNING
, "Cannot download " + uStr
+ ", trying another mirror");
1362 throw new FileNotFoundException("Cannot find " + uriStr
);
1366 * Effectively download an archive.
1368 Path
downloadArchive(URI uri
, Path dir
) throws IOException
{
1369 return download(uri
, dir
, (String
) null);
1373 * Effectively download. Synchronised in order to avoid downloading twice in
1376 synchronized Path
download(URI uri
, Path dir
, String name
) throws IOException
{
1380 // We use also use parent directory in case the archive itself has a fixed name
1381 String
[] segments
= uri
.getPath().split("/");
1382 name
= segments
.length
> 1 ? segments
[segments
.length
- 2] + '-' + segments
[segments
.length
- 1]
1383 : segments
[segments
.length
- 1];
1386 dest
= dir
.resolve(name
);
1387 if (Files
.exists(dest
)) {
1388 logger
.log(TRACE
, () -> "File " + dest
+ " already exists for " + uri
+ ", not downloading again");
1391 Files
.createDirectories(dest
.getParent());
1394 try (InputStream in
= uri
.toURL().openStream()) {
1395 Files
.copy(in
, dest
);
1396 logger
.log(DEBUG
, () -> "Downloaded " + dest
+ " from " + uri
);
1401 /** Create a JAR file from a directory. */
1402 Path
createJar(Path bundleDir
, A2Origin origin
) throws IOException
{
1403 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
1405 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
1406 manifest
= new Manifest(in
);
1408 // legal requirements
1409 origin
.appendChanges(bundleDir
);
1410 createReadMe(bundleDir
, manifest
);
1413 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
1414 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
1415 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
1416 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
1419 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1420 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1421 return super.visitFile(file
, attrs
);
1422 JarEntry entry
= new JarEntry(
1423 bundleDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1424 jarOut
.putNextEntry(entry
);
1425 Files
.copy(file
, jarOut
);
1426 return super.visitFile(file
, attrs
);
1431 deleteDirectory(bundleDir
);
1433 if (separateSources
)
1434 createSourceJar(bundleDir
, manifest
, null);
1439 /** Package sources separately, in the Eclipse-SourceBundle format. */
1440 void createSourceJar(Path bundleDir
, Manifest manifest
, Properties props
) throws IOException
{
1441 boolean unmodified
= props
!= null;
1442 Path bundleCategoryDir
= bundleDir
.getParent();
1443 Path sourceDir
= bundleCategoryDir
.resolve(bundleDir
.toString() + ".src");
1444 if (!Files
.exists(sourceDir
)) {
1445 logger
.log(WARNING
, sourceDir
+ " does not exist, skipping...");
1449 Path relPath
= a2Base
.relativize(bundleCategoryDir
);
1450 Path srcCategoryDir
= a2SrcBase
.resolve(relPath
);
1451 Path srcJarP
= srcCategoryDir
.resolve(sourceDir
.getFileName() + ".jar");
1452 Files
.createDirectories(srcJarP
.getParent());
1454 String bundleSymbolicName
= manifest
.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1455 // in case there are additional directives
1456 bundleSymbolicName
= bundleSymbolicName
.split(";")[0];
1457 Manifest srcManifest
= new Manifest();
1458 srcManifest
.getMainAttributes().put(MANIFEST_VERSION
, "1.0");
1459 BUNDLE_SYMBOLICNAME
.put(srcManifest
, bundleSymbolicName
+ ".src");
1460 BUNDLE_VERSION
.put(srcManifest
, BUNDLE_VERSION
.get(manifest
));
1461 ECLIPSE_SOURCE_BUNDLE
.put(srcManifest
,
1462 bundleSymbolicName
+ ";version=\"" + BUNDLE_VERSION
.get(manifest
) + "\"");
1465 createReadMe(sourceDir
, unmodified ? props
: manifest
);
1467 try (JarOutputStream srcJarOut
= new JarOutputStream(Files
.newOutputStream(srcJarP
), srcManifest
)) {
1468 // srcJarOut.setLevel(Deflater.BEST_COMPRESSION);
1469 Files
.walkFileTree(sourceDir
, new SimpleFileVisitor
<Path
>() {
1472 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1473 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1474 return super.visitFile(file
, attrs
);
1475 JarEntry entry
= new JarEntry(
1476 sourceDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1477 srcJarOut
.putNextEntry(entry
);
1478 Files
.copy(file
, srcJarOut
);
1479 return super.visitFile(file
, attrs
);
1484 deleteDirectory(sourceDir
);
1488 * Generate a readme clarifying and prominently notifying of the repackaging and
1491 void createReadMe(Path jarDir
, Object mapping
) throws IOException
{
1492 // write repackaged README
1493 try (BufferedWriter writer
= Files
.newBufferedWriter(jarDir
.resolve(README_REPACKAGED
))) {
1494 boolean merged
= ARGEO_ORIGIN_M2_MERGE
.get(mapping
) != null;
1496 writer
.append("This component is a merging of third party components"
1497 + " in order to comply with A2 packaging standards.\n");
1499 writer
.append("This component is a repackaging of a third party component"
1500 + " in order to comply with A2 packaging standards.\n");
1503 String spdxLicenseId
= SPDX_LICENSE_IDENTIFIER
.get(mapping
);
1504 if (spdxLicenseId
== null)
1505 throw new IllegalStateException("An SPDX license id must have beend defined at this stage.");
1506 writer
.append("\nIt is redistributed under the following license:\n\n");
1507 writer
.append("SPDX-Identifier: " + spdxLicenseId
+ "\n\n");
1509 if (!spdxLicenseId
.startsWith("LicenseRef")) {// standard
1510 int withIndex
= spdxLicenseId
.indexOf(" WITH ");
1511 if (withIndex
>= 0) {
1512 String simpleId
= spdxLicenseId
.substring(0, withIndex
).trim();
1513 String exception
= spdxLicenseId
.substring(withIndex
+ " WITH ".length());
1514 writer
.append("which are available here: https://spdx.org/licenses/" + simpleId
1515 + "\nand here: https://spdx.org/licenses/" + exception
+ "\n");
1517 writer
.append("which is available here: https://spdx.org/licenses/" + spdxLicenseId
+ "\n");
1520 String url
= BUNDLE_LICENSE
.get(mapping
);
1522 writer
.write("which is available here: " + url
+ "\n");
1524 logger
.log(ERROR
, "No licence URL for " + jarDir
);
1529 String originDesc
= ARGEO_ORIGIN_URI
.get(mapping
);
1530 if (originDesc
!= null)
1531 writer
.append("\nThe original component comes from " + originDesc
+ ".\n");
1533 String m2Repo
= ARGEO_ORIGIN_M2_REPO
.get(mapping
);
1534 originDesc
= ARGEO_ORIGIN_M2
.get(mapping
);
1535 if (originDesc
!= null)
1536 writer
.append("\nThe original component has M2 coordinates:\n" + originDesc
.replace(',', '\n')
1537 + "\n" + (m2Repo
!= null ?
"\nin M2 repository " + m2Repo
+ "\n" : ""));
1539 logger
.log(ERROR
, "Cannot find origin information in " + jarDir
);
1541 String originSources
= ARGEO_ORIGIN_SOURCES_URI
.get(mapping
);
1542 if (originSources
!= null)
1543 writer
.append("\nThe original sources come from " + originSources
+ ".\n");
1545 if (Files
.exists(jarDir
.resolve(CHANGES
)))
1546 writer
.append("\nA detailed list of changes is available under " + CHANGES
+ ".\n");
1548 if (!jarDir
.getFileName().toString().endsWith(".src")) {// binary archive
1549 if (separateSources
)
1550 writer
.append("Corresponding sources are available in the related archive named "
1551 + jarDir
.toString() + ".src.jar.\n");
1553 writer
.append("Corresponding sources are available under OSGI-OPT/src.\n");
1559 * Gathers modifications performed on the original binaries and sources,
1560 * especially in order to comply with their license requirements.
1567 Set
<String
> modified
= new TreeSet
<>();
1568 Set
<String
> deleted
= new TreeSet
<>();
1569 Set
<String
> added
= new TreeSet
<>();
1570 Set
<String
> moved
= new TreeSet
<>();
1572 /** Append changes to the A2-ORIGIN/changes file. */
1573 void appendChanges(Path baseDirectory
) throws IOException
{
1574 if (modified
.isEmpty() && deleted
.isEmpty() && added
.isEmpty() && moved
.isEmpty())
1575 return; // no changes
1576 Path changesFile
= baseDirectory
.resolve(CHANGES
);
1577 Files
.createDirectories(changesFile
.getParent());
1578 try (BufferedWriter writer
= Files
.newBufferedWriter(changesFile
, APPEND
, CREATE
)) {
1579 for (String msg
: added
)
1580 writer
.write("- Added " + msg
+ ".\n");
1581 for (String msg
: modified
)
1582 writer
.write("- Modified " + msg
+ ".\n");
1583 for (String msg
: moved
)
1584 writer
.write("- Moved " + msg
+ ".\n");
1585 for (String msg
: deleted
)
1586 writer
.write("- Deleted " + msg
+ ".\n");
1592 /** Simple representation of an M2 artifact. */
1593 class M2Artifact
extends CategoryNameVersion
{
1594 private String classifier
;
1596 M2Artifact(String m2coordinates
) {
1597 this(m2coordinates
, null);
1600 M2Artifact(String m2coordinates
, String classifier
) {
1601 String
[] parts
= m2coordinates
.split(":");
1602 setCategory(parts
[0]);
1604 if (parts
.length
> 2) {
1605 setVersion(parts
[2]);
1607 this.classifier
= classifier
;
1610 String
getGroupId() {
1611 return super.getCategory();
1614 String
getArtifactId() {
1615 return super.getName();
1618 String
toM2Coordinates() {
1619 return getCategory() + ":" + getName() + (getVersion() != null ?
":" + getVersion() : "");
1622 String
getClassifier() {
1623 return classifier
!= null ? classifier
: "";
1626 String
getExtension() {
1631 /** Utilities around Maven (conventions based). */
1632 class M2ConventionsUtils
{
1633 final static String MAVEN_CENTRAL_BASE_URL
= "https://repo1.maven.org/maven2/";
1635 /** The file name of this artifact when stored */
1636 static String
artifactFileName(M2Artifact artifact
) {
1637 return artifact
.getArtifactId() + '-' + artifact
.getVersion()
1638 + (artifact
.getClassifier().equals("") ?
"" : '-' + artifact
.getClassifier()) + '.'
1639 + artifact
.getExtension();
1642 /** Absolute path to the file */
1643 static String
artifactPath(String artifactBasePath
, M2Artifact artifact
) {
1644 return artifactParentPath(artifactBasePath
, artifact
) + '/' + artifactFileName(artifact
);
1647 /** Absolute path to the file */
1648 static String
artifactUrl(String repoUrl
, M2Artifact artifact
) {
1649 if (repoUrl
.endsWith("/"))
1650 return repoUrl
+ artifactPath("/", artifact
).substring(1);
1652 return repoUrl
+ artifactPath("/", artifact
);
1655 /** Absolute path to the file */
1656 static URI
mavenRepoUrl(String repoBase
, M2Artifact artifact
) throws URISyntaxException
{
1657 String uri
= artifactUrl(repoBase
== null ? MAVEN_CENTRAL_BASE_URL
: repoBase
, artifact
);
1658 return new URI(uri
);
1661 /** Absolute path to the directories where the files will be stored */
1662 static String
artifactParentPath(String artifactBasePath
, M2Artifact artifact
) {
1663 return artifactBasePath
+ (artifactBasePath
.endsWith("/") || artifactBasePath
.equals("") ?
"" : "/")
1664 + artifactParentPath(artifact
);
1667 /** Relative path to the directories where the files will be stored */
1668 static String
artifactParentPath(M2Artifact artifact
) {
1669 return artifact
.getGroupId().replace('.', '/') + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion();
1673 private M2ConventionsUtils() {
1677 /** Combination of a category, a name and a version. */
1678 class CategoryNameVersion
extends NameVersion
{
1679 private String category
;
1681 CategoryNameVersion() {
1684 CategoryNameVersion(String category
, String name
, String version
) {
1685 super(name
, version
);
1686 this.category
= category
;
1689 CategoryNameVersion(String category
, NameVersion nameVersion
) {
1691 this.category
= category
;
1694 String
getCategory() {
1698 void setCategory(String category
) {
1699 this.category
= category
;
1703 public String
toString() {
1704 return category
+ ":" + super.toString();
1709 /** Combination of a name and a version. */
1710 class NameVersion
implements Comparable
<NameVersion
> {
1711 private String name
;
1712 private String version
;
1717 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1718 NameVersion(String nameVersion
) {
1719 int index
= nameVersion
.indexOf(";version=");
1721 setName(nameVersion
);
1724 setName(nameVersion
.substring(0, index
));
1725 setVersion(nameVersion
.substring(index
+ ";version=".length()));
1729 NameVersion(String name
, String version
) {
1731 this.version
= version
;
1734 NameVersion(NameVersion nameVersion
) {
1735 this.name
= nameVersion
.getName();
1736 this.version
= nameVersion
.getVersion();
1743 void setName(String name
) {
1747 String
getVersion() {
1751 void setVersion(String version
) {
1752 this.version
= version
;
1755 String
getBranch() {
1756 String
[] parts
= getVersion().split("\\.");
1757 if (parts
.length
< 2)
1758 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1759 return parts
[0] + "." + parts
[1];
1763 public boolean equals(Object obj
) {
1764 if (obj
instanceof NameVersion
) {
1765 NameVersion nameVersion
= (NameVersion
) obj
;
1766 return name
.equals(nameVersion
.getName()) && version
.equals(nameVersion
.getVersion());
1772 public int hashCode() {
1773 return name
.hashCode();
1777 public String
toString() {
1778 return name
+ ":" + version
;
1781 public int compareTo(NameVersion o
) {
1782 if (o
.getName().equals(name
))
1783 return version
.compareTo(o
.getVersion());
1785 return name
.compareTo(o
.getName());