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_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
.SPDX_LICENSE_IDENTIFIER
;
28 import java
.io
.BufferedWriter
;
30 import java
.io
.FileNotFoundException
;
31 import java
.io
.IOException
;
32 import java
.io
.InputStream
;
33 import java
.io
.OutputStream
;
34 import java
.lang
.System
.Logger
;
35 import java
.net
.MalformedURLException
;
37 import java
.nio
.charset
.StandardCharsets
;
38 import java
.nio
.file
.DirectoryStream
;
39 import java
.nio
.file
.FileSystem
;
40 import java
.nio
.file
.FileSystems
;
41 import java
.nio
.file
.FileVisitResult
;
42 import java
.nio
.file
.Files
;
43 import java
.nio
.file
.Path
;
44 import java
.nio
.file
.PathMatcher
;
45 import java
.nio
.file
.Paths
;
46 import java
.nio
.file
.SimpleFileVisitor
;
47 import java
.nio
.file
.StandardCopyOption
;
48 import java
.nio
.file
.StandardOpenOption
;
49 import java
.nio
.file
.attribute
.BasicFileAttributes
;
50 import java
.util
.ArrayList
;
51 import java
.util
.HashMap
;
52 import java
.util
.Iterator
;
53 import java
.util
.List
;
55 import java
.util
.Objects
;
56 import java
.util
.Properties
;
58 import java
.util
.StringJoiner
;
59 import java
.util
.TreeMap
;
60 import java
.util
.TreeSet
;
61 import java
.util
.concurrent
.CompletableFuture
;
62 import java
.util
.jar
.Attributes
;
63 import java
.util
.jar
.JarEntry
;
64 import java
.util
.jar
.JarInputStream
;
65 import java
.util
.jar
.JarOutputStream
;
66 import java
.util
.jar
.Manifest
;
67 import java
.util
.zip
.Deflater
;
69 import aQute
.bnd
.osgi
.Analyzer
;
70 import aQute
.bnd
.osgi
.Jar
;
72 /** Repackages existing jar files into OSGi bundles in an A2 repository. */
73 public class Repackage
{
74 final static Logger logger
= System
.getLogger(Repackage
.class.getName());
77 * Environment variable on whether sources should be packaged separately or
78 * integrated in the bundles.
80 final static String ENV_SOURCE_BUNDLES
= "SOURCE_BUNDLES";
81 /** Environment variable on whether operations should be parallelised. */
82 final static String ENV_ARGEO_BUILD_SEQUENTIAL
= "ARGEO_BUILD_SEQUENTIAL";
84 /** Whether repackaging should run in parallel (default) or sequentially. */
85 final static boolean sequential
= Boolean
.parseBoolean(System
.getenv(ENV_ARGEO_BUILD_SEQUENTIAL
));
87 /** Main entry point. */
88 public static void main(String
[] args
) {
90 logger
.log(INFO
, "Build will be sequential");
91 if (args
.length
< 2) {
92 System
.err
.println("Usage: <path to a2 output dir> <category1> <category2> ...");
95 Path a2Base
= Paths
.get(args
[0]).toAbsolutePath().normalize();
96 Path descriptorsBase
= Paths
.get(".").toAbsolutePath().normalize();
97 Repackage factory
= new Repackage(a2Base
, descriptorsBase
);
99 List
<CompletableFuture
<Void
>> toDos
= new ArrayList
<>();
100 for (int i
= 1; i
< args
.length
; i
++) {
101 Path p
= Paths
.get(args
[i
]);
103 factory
.processCategory(p
);
105 toDos
.add(CompletableFuture
.runAsync(() -> factory
.processCategory(p
)));
108 CompletableFuture
.allOf(toDos
.toArray(new CompletableFuture
[toDos
.size()])).join();
111 StringBuilder sb
= new StringBuilder();
112 for (String licenseId
: licensesUsed
.keySet())
113 for (String name
: licensesUsed
.get(licenseId
))
114 sb
.append((licenseId
.equals("") ?
"Proprietary" : licenseId
) + "\t\t" + name
+ "\n");
115 logger
.log(INFO
, "# License summary:\n" + sb
);
118 /** MANIFEST headers. */
119 enum ManifestHeader
{
121 /** OSGi bundle symbolic name. */
122 BUNDLE_SYMBOLICNAME("Bundle-SymbolicName"), //
123 /** OSGi bundle version. */
124 BUNDLE_VERSION("Bundle-Version"), //
125 /** OSGi bundle license. */
126 BUNDLE_LICENSE("Bundle-License"), //
127 /** OSGi exported packages list. */
128 EXPORT_PACKAGE("Export-Package"), //
129 /** OSGi imported packages list. */
130 IMPORT_PACKAGE("Import-Package"), //
131 /** OSGi path to embedded jar. */
132 BUNDLE_CLASSPATH("Bundle-Classpath"), //
134 /** Java module name. */
135 AUTOMATIC_MODULE_NAME("Automatic-Module-Name"), //
137 /** Eclipse source bundle. */
138 ECLIPSE_SOURCE_BUNDLE("Eclipse-SourceBundle"), //
141 * SPDX license identifier.
143 * @see https://spdx.org/licenses/
145 SPDX_LICENSE_IDENTIFIER("SPDX-License-Identifier"), //
148 * Maven coordinates of the origin, possibly partial when using common.bnd or
151 ARGEO_ORIGIN_M2("Argeo-Origin-M2"), //
152 /** List of Maven coordinates to merge. */
153 ARGEO_ORIGIN_M2_MERGE("Argeo-Origin-M2-Merge"), //
154 /** Maven repository, if not the default one. */
155 ARGEO_ORIGIN_M2_REPO("Argeo-Origin-M2-Repo"), //
157 * Do not perform BND analysis of the origin component. Typically Import_package
158 * and Export-Package will be kept untouched.
160 ARGEO_ORIGIN_NO_METADATA_GENERATION("Argeo-Origin-NoMetadataGeneration"), //
162 // * Embed the original jar without modifying it (may be required by some
163 // * proprietary licenses, such as JCR Day License).
165 // ARGEO_ORIGIN_EMBED("Argeo-Origin-Embed"), //
167 * Do not modify original jar (may be required by some proprietary licenses,
168 * such as JCR Day License).
170 ARGEO_DO_NOT_MODIFY("Argeo-Origin-Do-Not-Modify"), //
172 * Origin (non-Maven) URI of the component. It may be anything (jar, archive,
175 ARGEO_ORIGIN_URI("Argeo-Origin-URI"), //
177 * Origin (non-Maven) URI of the source of the component. It may be anything
178 * (jar, archive, code repository, etc.).
180 ARGEO_ORIGIN_SOURCES_URI("Argeo-Origin-Sources-URI"), //
185 private ManifestHeader(String value
) {
190 public String
toString() {
195 /** Name of the file centralising information for multiple M2 artifacts. */
196 final static String COMMON_BND
= "common.bnd";
197 /** Name of the file centralising information for mergin M2 artifacts. */
198 final static String MERGE_BND
= "merge.bnd";
200 * Subdirectory of the jar file where origin informations (changes, legal
201 * notices etc. are stored)
203 final static String ARGEO_ORIGIN
= "ARGEO-ORIGIN";
204 /** File detailing modifications to the original component. */
205 final static String CHANGES
= ARGEO_ORIGIN
+ "/changes";
207 * Name of the file at the root of the repackaged jar, which prominently
208 * notifies that the component has be repackaged.
210 final static String README_REPACKAGED
= "README.repackaged";
213 /** Summary of all license seen during the repackaging. */
214 final static Map
<String
, Set
<String
>> licensesUsed
= new TreeMap
<>();
216 /** Directory where to download archives */
217 final Path originBase
;
218 /** Directory where to download Maven artifacts */
219 final Path mavenBase
;
221 /** A2 repository base for binary bundles */
223 /** A2 repository base for source bundles */
224 final Path a2SrcBase
;
225 /** A2 base for native components */
226 final Path a2LibBase
;
227 /** Location of the descriptors driving the packaging */
228 final Path descriptorsBase
;
229 /** URIs of archives to download */
230 final Properties uris
= new Properties();
231 /** Mirrors for archive download. Key is URI prefix, value list of base URLs */
232 final Map
<String
, List
<String
>> mirrors
= new HashMap
<String
, List
<String
>>();
234 /** Whether sources should be packaged separately */
235 final boolean sourceBundles
;
237 /** Constructor initialises the various variables */
238 public Repackage(Path a2Base
, Path descriptorsBase
) {
239 sourceBundles
= Boolean
.parseBoolean(System
.getenv(ENV_SOURCE_BUNDLES
));
241 logger
.log(INFO
, "Sources will be packaged separately");
243 Objects
.requireNonNull(a2Base
);
244 Objects
.requireNonNull(descriptorsBase
);
245 this.originBase
= Paths
.get(System
.getProperty("user.home"), ".cache", "argeo/build/origin");
246 this.mavenBase
= Paths
.get(System
.getProperty("user.home"), ".m2", "repository");
248 // TODO define and use a build base
249 this.a2Base
= a2Base
;
250 this.a2SrcBase
= a2Base
.getParent().resolve(a2Base
.getFileName() + ".src");
251 this.a2LibBase
= a2Base
.resolve("lib");
252 this.descriptorsBase
= descriptorsBase
;
253 if (!Files
.exists(this.descriptorsBase
))
254 throw new IllegalArgumentException(this.descriptorsBase
+ " does not exist");
257 Path urisPath
= this.descriptorsBase
.resolve("uris.properties");
258 if (Files
.exists(urisPath
)) {
259 try (InputStream in
= Files
.newInputStream(urisPath
)) {
261 } catch (IOException e
) {
262 throw new IllegalStateException("Cannot load " + urisPath
, e
);
267 Path eclipseMirrorsPath
= this.descriptorsBase
.resolve("eclipse.mirrors.txt");
268 List
<String
> eclipseMirrors
= new ArrayList
<>();
269 if (Files
.exists(eclipseMirrorsPath
)) {
271 eclipseMirrors
= Files
.readAllLines(eclipseMirrorsPath
, StandardCharsets
.UTF_8
);
272 } catch (IOException e
) {
273 throw new IllegalStateException("Cannot load " + eclipseMirrorsPath
, e
);
275 for (Iterator
<String
> it
= eclipseMirrors
.iterator(); it
.hasNext();) {
276 String value
= it
.next();
277 if (value
.strip().equals(""))
281 mirrors
.put("http://www.eclipse.org/downloads", eclipseMirrors
);
287 /** Process a whole category/group id. */
288 void processCategory(Path categoryRelativePath
) {
290 Path targetCategoryBase
= descriptorsBase
.resolve(categoryRelativePath
);
291 DirectoryStream
<Path
> bnds
= Files
.newDirectoryStream(targetCategoryBase
,
292 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
293 && !p
.getFileName().toString().equals(MERGE_BND
));
294 for (Path p
: bnds
) {
295 processSingleM2ArtifactDistributionUnit(p
);
298 DirectoryStream
<Path
> dus
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
299 for (Path duDir
: dus
) {
300 if (duDir
.getFileName().toString().startsWith("eclipse-")) {
301 processEclipseArchive(duDir
);
303 processM2BasedDistributionUnit(duDir
);
306 } catch (IOException e
) {
307 throw new RuntimeException("Cannot process category " + categoryRelativePath
, e
);
311 /** Process a standalone Maven artifact. */
312 void processSingleM2ArtifactDistributionUnit(Path bndFile
) {
314 Path categoryRelativePath
= descriptorsBase
.relativize(bndFile
.getParent());
315 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
317 Properties fileProps
= new Properties();
318 try (InputStream in
= Files
.newInputStream(bndFile
)) {
321 // use file name as symbolic name
322 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
323 String symbolicName
= bndFile
.getFileName().toString();
324 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
325 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
328 String m2Coordinates
= fileProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
329 if (m2Coordinates
== null)
330 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile
);
331 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
333 Path downloaded
= downloadMaven(fileProps
, artifact
);
335 boolean doNotModify
= Boolean
336 .parseBoolean(fileProps
.getOrDefault(ARGEO_DO_NOT_MODIFY
.toString(), "false").toString());
337 if (doNotModify
&& sourceBundles
) {
338 processNotModified(targetCategoryBase
, downloaded
, fileProps
, artifact
);
342 // regular processing
343 A2Origin origin
= new A2Origin();
344 Path bundleDir
= processBndJar(downloaded
, targetCategoryBase
, fileProps
, artifact
, origin
);
345 downloadAndProcessM2Sources(fileProps
, artifact
, bundleDir
, false);
346 createJar(bundleDir
, origin
);
347 } catch (Exception e
) {
348 throw new RuntimeException("Cannot process " + bndFile
, e
);
353 * Process multiple Maven artifacts coming from a same project and therefore
354 * with information in common (typically the version), generating single bundles
355 * or merging them if necessary.
360 void processM2BasedDistributionUnit(Path duDir
) {
362 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
363 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
365 Path mergeBnd
= duDir
.resolve(MERGE_BND
);
366 if (Files
.exists(mergeBnd
)) // merge
367 mergeM2Artifacts(mergeBnd
);
369 Path commonBnd
= duDir
.resolve(COMMON_BND
);
370 if (!Files
.exists(commonBnd
))
373 Properties commonProps
= new Properties();
374 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
375 commonProps
.load(in
);
378 String m2Version
= commonProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
379 if (m2Version
== null) {
380 logger
.log(WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
381 return;// ignore, this is probably an Eclipse archive
383 if (!m2Version
.startsWith(":")) {
384 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
386 m2Version
= m2Version
.substring(1);
388 DirectoryStream
<Path
> ds
= Files
.newDirectoryStream(duDir
,
389 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
390 && !p
.getFileName().toString().equals(MERGE_BND
));
392 Properties fileProps
= new Properties();
393 try (InputStream in
= Files
.newInputStream(p
)) {
396 String m2Coordinates
= fileProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
397 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
398 if (artifact
.getVersion() == null) {
399 artifact
.setVersion(m2Version
);
401 logger
.log(WARNING
, p
.getFileName() + " : Using version " + artifact
.getVersion()
402 + " specified in descriptor rather than " + m2Version
+ " specified in " + COMMON_BND
);
405 // prepare manifest entries
406 Properties mergedProps
= new Properties();
407 mergedProps
.putAll(commonProps
);
409 fileEntries
: for (Object key
: fileProps
.keySet()) {
410 if (ARGEO_ORIGIN_M2
.toString().equals(key
))
411 continue fileEntries
;
412 String value
= fileProps
.getProperty(key
.toString());
413 Object previousValue
= mergedProps
.put(key
.toString(), value
);
414 if (previousValue
!= null) {
416 commonBnd
+ ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
419 mergedProps
.put(ARGEO_ORIGIN_M2
.toString(), artifact
.toM2Coordinates());
420 if (!mergedProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
421 // use file name as symbolic name
422 String symbolicName
= p
.getFileName().toString();
423 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
424 mergedProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
428 Path downloaded
= downloadMaven(mergedProps
, artifact
);
430 boolean doNotModify
= Boolean
431 .parseBoolean(mergedProps
.getOrDefault(ARGEO_DO_NOT_MODIFY
.toString(), "false").toString());
432 if (doNotModify
&& sourceBundles
) {
433 processNotModified(targetCategoryBase
, downloaded
, mergedProps
, artifact
);
435 A2Origin origin
= new A2Origin();
436 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, mergedProps
, artifact
, origin
);
437 downloadAndProcessM2Sources(mergedProps
, artifact
, targetBundleDir
, false);
438 createJar(targetBundleDir
, origin
);
441 } catch (IOException e
) {
442 throw new RuntimeException("Cannot process " + duDir
, e
);
446 /** Merge multiple Maven artifacts. */
447 void mergeM2Artifacts(Path mergeBnd
) throws IOException
{
448 Path duDir
= mergeBnd
.getParent();
449 String category
= duDir
.getParent().getFileName().toString();
450 Path targetCategoryBase
= a2Base
.resolve(category
);
452 Properties mergeProps
= new Properties();
453 // first, load common properties
454 Path commonBnd
= duDir
.resolve(COMMON_BND
);
455 if (Files
.exists(commonBnd
))
456 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
459 // then, the merge properties themselves
460 try (InputStream in
= Files
.newInputStream(mergeBnd
)) {
464 String m2Version
= mergeProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
465 if (m2Version
== null) {
466 logger
.log(WARNING
, "Ignoring merging in " + duDir
+ " as it is not an M2-based distribution unit");
467 return;// ignore, this is probably an Eclipse archive
469 if (!m2Version
.startsWith(":")) {
470 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
472 m2Version
= m2Version
.substring(1);
473 mergeProps
.put(BUNDLE_VERSION
.toString(), m2Version
);
475 String artifactsStr
= mergeProps
.getProperty(ARGEO_ORIGIN_M2_MERGE
.toString());
476 if (artifactsStr
== null)
477 throw new IllegalArgumentException(mergeBnd
+ ": " + ARGEO_ORIGIN_M2_MERGE
+ " must be set");
479 String bundleSymbolicName
= mergeProps
.getProperty(BUNDLE_SYMBOLICNAME
.toString());
480 if (bundleSymbolicName
== null)
481 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd
);
482 CategoryNameVersion nameVersion
= new M2Artifact(category
+ ":" + bundleSymbolicName
+ ":" + m2Version
);
484 A2Origin origin
= new A2Origin();
485 Path bundleDir
= targetCategoryBase
.resolve(bundleSymbolicName
+ "." + nameVersion
.getBranch());
487 StringJoiner originDesc
= new StringJoiner(",");
488 String
[] artifacts
= artifactsStr
.split(",");
489 artifacts
: for (String str
: artifacts
) {
490 String m2Coordinates
= str
.trim();
491 if ("".equals(m2Coordinates
))
493 M2Artifact artifact
= new M2Artifact(m2Coordinates
.trim());
494 if (artifact
.getVersion() == null)
495 artifact
.setVersion(m2Version
);
496 originDesc
.add(artifact
.toString());
497 Path downloaded
= downloadMaven(mergeProps
, artifact
);
499 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(downloaded
), false)) {
500 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
501 if (entry
.isDirectory())
503 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".DSA")
504 || entry
.getName().endsWith(".SF")) {
505 origin
.deleted
.add("cryptographic signatures from " + artifact
);
508 if (entry
.getName().endsWith("module-info.class")) { // skip Java 9 module info
509 origin
.deleted
.add("Java module information (module-info.class) from " + artifact
);
512 if (entry
.getName().startsWith("META-INF/versions/")) { // skip multi-version
513 origin
.deleted
.add("additional Java versions (META-INF/versions) from " + artifact
);
516 if (entry
.getName().startsWith("META-INF/maven/")) {
517 origin
.deleted
.add("Maven information (META-INF/maven) from " + artifact
);
520 if (entry
.getName().startsWith(".cache/")) { // Apache SSHD
521 origin
.deleted
.add("cache directory (.cache) from " + artifact
);
524 if (entry
.getName().equals("META-INF/DEPENDENCIES")) {
525 origin
.deleted
.add("Dependencies (META-INF/DEPENDENCIES) from " + artifact
);
528 if (entry
.getName().equals("META-INF/MANIFEST.MF")) {
529 Path originalManifest
= bundleDir
.resolve(ARGEO_ORIGIN
).resolve(artifact
.getGroupId())
530 .resolve(artifact
.getArtifactId()).resolve("MANIFEST.MF");
531 Files
.createDirectories(originalManifest
.getParent());
532 try (OutputStream out
= Files
.newOutputStream(originalManifest
)) {
533 Files
.copy(jarIn
, originalManifest
);
536 "original MANIFEST (" + bundleDir
.relativize(originalManifest
) + ") from " + artifact
);
540 if (entry
.getName().endsWith("NOTICE") || entry
.getName().endsWith("NOTICE.txt")
541 || entry
.getName().endsWith("LICENSE") || entry
.getName().endsWith("LICENSE.md")
542 || entry
.getName().endsWith("LICENSE-notice.md") || entry
.getName().endsWith("COPYING")
543 || entry
.getName().endsWith("COPYING.LESSER")) {
544 Path artifactOriginDir
= bundleDir
.resolve(ARGEO_ORIGIN
).resolve(artifact
.getGroupId())
545 .resolve(artifact
.getArtifactId());
546 Path target
= artifactOriginDir
.resolve(entry
.getName());
547 Files
.createDirectories(target
.getParent());
548 Files
.copy(jarIn
, target
);
549 origin
.moved
.add(entry
.getName() + " in " + artifact
+ " to " + bundleDir
.relativize(target
));
552 Path target
= bundleDir
.resolve(entry
.getName());
553 Files
.createDirectories(target
.getParent());
554 if (!Files
.exists(target
)) {
555 Files
.copy(jarIn
, target
);
557 if (entry
.getName().startsWith("META-INF/services/")) {
558 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
559 out
.write("\n".getBytes());
560 jarIn
.transferTo(out
);
561 logger
.log(DEBUG
, artifact
.getArtifactId() + " - Appended " + entry
.getName());
563 origin
.modified
.add(entry
.getName() + ", merging from " + artifact
);
564 } else if (entry
.getName().startsWith("org/apache/batik/")) {
565 logger
.log(TRACE
, "Skip " + entry
.getName());
568 throw new IllegalStateException("File " + target
+ " from " + artifact
+ " already exists");
571 logger
.log(TRACE
, () -> "Copied " + target
);
574 origin
.added
.add("binary content of " + artifact
);
577 downloadAndProcessM2Sources(mergeProps
, artifact
, bundleDir
, true);
580 // additional service files
581 Path servicesDir
= duDir
.resolve("services");
582 if (Files
.exists(servicesDir
)) {
583 for (Path p
: Files
.newDirectoryStream(servicesDir
)) {
584 Path target
= bundleDir
.resolve("META-INF/services/").resolve(p
.getFileName());
585 try (InputStream in
= Files
.newInputStream(p
);
586 OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
);) {
587 out
.write("\n".getBytes());
589 logger
.log(DEBUG
, "Appended " + p
);
591 origin
.added
.add(bundleDir
.relativize(target
).toString());
596 Map
<String
, String
> entries
= new TreeMap
<>();
597 try (Analyzer bndAnalyzer
= new Analyzer()) {
598 bndAnalyzer
.setProperties(mergeProps
);
599 Jar jar
= new Jar(bundleDir
.toFile());
600 bndAnalyzer
.setJar(jar
);
601 Manifest manifest
= bndAnalyzer
.calcManifest();
603 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
604 Object value
= manifest
.getMainAttributes().get(key
);
606 switch (key
.toString()) {
608 case "Bnd-LastModified":
612 if ("Require-Capability".equals(key
.toString())
613 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\"")) {
614 origin
.deleted
.add("MANIFEST header " + key
);
615 continue keys
;// hack for very old classes
617 entries
.put(key
.toString(), value
.toString());
619 } catch (Exception e
) {
620 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
623 Manifest manifest
= new Manifest();
624 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
625 Files
.createDirectories(manifestPath
.getParent());
626 for (String key
: entries
.keySet()) {
627 String value
= entries
.get(key
);
628 manifest
.getMainAttributes().putValue(key
, value
);
630 manifest
.getMainAttributes().putValue(ARGEO_ORIGIN_M2
.toString(), originDesc
.toString());
632 processLicense(bundleDir
, manifest
);
635 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
638 createJar(bundleDir
, origin
);
641 /** Generates MANIFEST using BND. */
642 Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
, M2Artifact artifact
,
645 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
646 boolean doNotModifyManifest
= Boolean
.parseBoolean(
647 fileProps
.getOrDefault(ARGEO_ORIGIN_NO_METADATA_GENERATION
.toString(), "false").toString());
649 // Note: we always force the symbolic name
650 if (doNotModifyManifest
) {
651 for (Object key
: fileProps
.keySet()) {
652 String value
= fileProps
.getProperty(key
.toString());
653 additionalEntries
.put(key
.toString(), value
);
656 if (artifact
!= null) {
657 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
658 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
660 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
661 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
665 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
666 fileProps
.put(EXPORT_PACKAGE
.toString(),
667 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
671 try (Analyzer bndAnalyzer
= new Analyzer()) {
672 bndAnalyzer
.setProperties(fileProps
);
673 Jar jar
= new Jar(downloaded
.toFile());
674 bndAnalyzer
.setJar(jar
);
675 Manifest manifest
= bndAnalyzer
.calcManifest();
677 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
678 Object value
= manifest
.getMainAttributes().get(key
);
680 switch (key
.toString()) {
682 case "Bnd-LastModified":
686 if ("Require-Capability".equals(key
.toString())
687 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\"")) {
688 origin
.deleted
.add("MANIFEST header " + key
);
689 continue keys
;// !! hack for very old classes
691 additionalEntries
.put(key
.toString(), value
.toString());
695 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
, origin
);
696 logger
.log(DEBUG
, () -> "Processed " + downloaded
);
697 return targetBundleDir
;
698 } catch (Exception e
) {
699 throw new RuntimeException("Cannot BND process " + downloaded
, e
);
704 /** Process an artifact that should not be modified. */
705 void processNotModified(Path targetCategoryBase
, Path downloaded
, Properties fileProps
, M2Artifact artifact
)
707 // Some proprietary or signed artifacts do not allow any modification
708 // When releasing (with separate sources), we just copy it
709 Path unmodifiedTarget
= targetCategoryBase
710 .resolve(fileProps
.getProperty(BUNDLE_SYMBOLICNAME
.toString()) + "." + artifact
.getBranch() + ".jar");
711 Files
.copy(downloaded
, unmodifiedTarget
, StandardCopyOption
.REPLACE_EXISTING
);
712 Path bundleDir
= targetCategoryBase
713 .resolve(fileProps
.getProperty(BUNDLE_SYMBOLICNAME
.toString()) + "." + artifact
.getBranch());
714 downloadAndProcessM2Sources(fileProps
, artifact
, bundleDir
, false);
716 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(unmodifiedTarget
))) {
717 manifest
= jarIn
.getManifest();
719 createSourceJar(bundleDir
, manifest
, true);
722 /** Download and integrates sources for a single Maven artifact. */
723 void downloadAndProcessM2Sources(Properties props
, M2Artifact artifact
, Path targetBundleDir
, boolean merging
)
726 String repoStr
= props
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
727 ? props
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
729 String alternateUri
= props
.getProperty(ARGEO_ORIGIN_SOURCES_URI
.toString());
730 M2Artifact sourcesArtifact
= new M2Artifact(artifact
.toM2Coordinates(), "sources");
731 URL sourcesUrl
= alternateUri
!= null ?
new URL(alternateUri
)
732 : M2ConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
733 Path sourcesDownloaded
= downloadMaven(sourcesUrl
, sourcesArtifact
);
734 processM2SourceJar(sourcesDownloaded
, targetBundleDir
, merging ? artifact
: null);
735 logger
.log(TRACE
, () -> "Processed source " + sourcesDownloaded
);
736 } catch (Exception e
) {
737 logger
.log(ERROR
, () -> "Cannot download source for " + artifact
);
742 /** Integrate sources from a downloaded jar file. */
743 void processM2SourceJar(Path file
, Path bundleDir
, M2Artifact mergingFrom
) throws IOException
{
744 A2Origin origin
= new A2Origin();
745 Path sourceDir
= sourceBundles ? bundleDir
.getParent().resolve(bundleDir
.toString() + ".src")
746 : bundleDir
.resolve("OSGI-OPT/src");
747 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
749 String mergingMsg
= "";
750 if (mergingFrom
!= null)
751 mergingMsg
= " of " + mergingFrom
;
753 Files
.createDirectories(sourceDir
);
755 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
756 String relPath
= entry
.getName();
757 if (entry
.isDirectory())
759 if (entry
.getName().startsWith("META-INF")) {// skip META-INF entries
760 origin
.deleted
.add("META-INF directory from the sources" + mergingMsg
);
763 if (entry
.getName().startsWith("module-info.java")) {// skip Java module information
764 origin
.deleted
.add("Java module information from the sources (module-info.java)" + mergingMsg
);
767 if (entry
.getName().startsWith("/")) { // absolute paths
768 int metaInfIndex
= entry
.getName().indexOf("META-INF");
769 if (metaInfIndex
>= 0) {
770 relPath
= entry
.getName().substring(metaInfIndex
);
771 origin
.moved
.add(" to " + relPath
+ " entry with absolute path " + entry
.getName());
773 logger
.log(WARNING
, entry
.getName() + " has an absolute path");
774 origin
.deleted
.add(entry
.getName() + " from the sources" + mergingMsg
);
778 Path target
= sourceDir
.resolve(relPath
);
779 Files
.createDirectories(target
.getParent());
780 if (!Files
.exists(target
)) {
781 Files
.copy(jarIn
, target
);
782 logger
.log(TRACE
, () -> "Copied source " + target
);
784 logger
.log(TRACE
, () -> target
+ " already exists, skipping...");
790 origin
.appendChanges(sourceDir
);
792 origin
.added
.add("source code under OSGI-OPT/src");
793 origin
.appendChanges(bundleDir
);
797 /** Download a Maven artifact. */
798 Path
downloadMaven(Properties props
, M2Artifact artifact
) throws IOException
{
799 String repoStr
= props
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
800 ? props
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
802 String alternateUri
= props
.getProperty(ARGEO_ORIGIN_URI
.toString());
803 URL url
= alternateUri
!= null ?
new URL(alternateUri
) : M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
804 return downloadMaven(url
, artifact
);
807 /** Download a Maven artifact. */
808 Path
downloadMaven(URL url
, M2Artifact artifact
) throws IOException
{
809 return download(url
, mavenBase
, M2ConventionsUtils
.artifactPath("", artifact
));
815 /** Process an archive in Eclipse format. */
816 void processEclipseArchive(Path duDir
) {
818 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
819 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
820 Files
.createDirectories(targetCategoryBase
);
821 // first delete all directories from previous builds
822 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)))
823 deleteDirectory(dir
);
825 Files
.createDirectories(originBase
);
827 Path commonBnd
= duDir
.resolve(COMMON_BND
);
828 Properties commonProps
= new Properties();
829 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
830 commonProps
.load(in
);
832 String url
= commonProps
.getProperty(ARGEO_ORIGIN_URI
.toString());
834 url
= uris
.getProperty(duDir
.getFileName().toString());
836 throw new IllegalStateException("No url available for " + duDir
);
837 commonProps
.put(ARGEO_ORIGIN_URI
.toString(), url
);
839 Path downloaded
= tryDownloadArchive(url
, originBase
);
841 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
844 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
845 Properties includes
= new Properties();
846 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
849 for (Object pattern
: includes
.keySet()) {
850 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
851 includeMatchers
.add(pathMatcher
);
854 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
855 Path excludeFile
= duDir
.resolve("excludes.properties");
856 if (Files
.exists(excludeFile
)) {
857 Properties excludes
= new Properties();
858 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
861 for (Object pattern
: excludes
.keySet()) {
862 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
863 excludeMatchers
.add(pathMatcher
);
867 // keys are the bundle directories
868 Map
<Path
, A2Origin
> origins
= new HashMap
<>();
869 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
872 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
873 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
874 if (includeMatcher
.matches(file
)) {
875 for (PathMatcher excludeMatcher
: excludeMatchers
) {
876 if (excludeMatcher
.matches(file
)) {
877 logger
.log(TRACE
, "Skipping excluded " + file
);
878 return FileVisitResult
.CONTINUE
;
881 if (file
.getFileName().toString().contains(".source_")) {
882 processEclipseSourceJar(file
, targetCategoryBase
);
883 logger
.log(DEBUG
, () -> "Processed source " + file
);
885 Map
<String
, String
> map
= new HashMap
<>();
886 for (Object key
: commonProps
.keySet())
887 map
.put(key
.toString(), commonProps
.getProperty(key
.toString()));
888 A2Origin origin
= new A2Origin();
889 Path bundleDir
= processBundleJar(file
, targetCategoryBase
, map
, origin
);
890 origins
.put(bundleDir
, origin
);
891 logger
.log(DEBUG
, () -> "Processed " + file
);
893 break includeMatchers
;
896 return FileVisitResult
.CONTINUE
;
900 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)
901 && p
.getFileName().toString().indexOf('.') >= 0 && !p
.getFileName().toString().endsWith(".src"));
902 for (Path bundleDir
: dirs
) {
903 A2Origin origin
= origins
.get(bundleDir
);
904 Objects
.requireNonNull(origin
, "No A2 origin found for " + bundleDir
);
905 createJar(bundleDir
, origin
);
907 } catch (IOException e
) {
908 throw new RuntimeException("Cannot process " + duDir
, e
);
913 /** Process sources in Eclipse format. */
914 void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
916 A2Origin origin
= new A2Origin();
918 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
919 Manifest manifest
= jarIn
.getManifest();
921 String
[] relatedBundle
= manifest
.getMainAttributes().getValue(ECLIPSE_SOURCE_BUNDLE
.toString())
923 String version
= relatedBundle
[1].substring("version=\"".length());
924 version
= version
.substring(0, version
.length() - 1);
925 NameVersion nameVersion
= new NameVersion(relatedBundle
[0], version
);
926 bundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
928 Path sourceDir
= sourceBundles ? bundleDir
.getParent().resolve(bundleDir
.toString() + ".src")
929 : bundleDir
.resolve("OSGI-OPT/src");
931 Files
.createDirectories(sourceDir
);
933 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
934 if (entry
.isDirectory())
936 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
938 Path target
= sourceDir
.resolve(entry
.getName());
939 Files
.createDirectories(target
.getParent());
940 Files
.copy(jarIn
, target
);
941 logger
.log(TRACE
, () -> "Copied source " + target
);
946 origin
.appendChanges(sourceDir
);
948 origin
.added
.add("source code under OSGI-OPT/src");
949 origin
.appendChanges(bundleDir
);
952 } catch (IOException e
) {
953 throw new IllegalStateException("Cannot process " + file
, e
);
960 /** Normalise a single (that is, non-merged) bundle. */
961 Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
, A2Origin origin
) throws IOException
{
962 // boolean embed = Boolean.parseBoolean(entries.getOrDefault(ARGEO_ORIGIN_EMBED.toString(), "false").toString());
963 boolean doNotModify
= Boolean
964 .parseBoolean(entries
.getOrDefault(ManifestHeader
.ARGEO_DO_NOT_MODIFY
.toString(), "false").toString());
965 NameVersion nameVersion
;
968 boolean isSingleton
= false;
970 Manifest sourceManifest
;
971 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
972 sourceManifest
= jarIn
.getManifest();
973 manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
975 String rawSourceSymbolicName
= manifest
.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME
.toString());
976 if (rawSourceSymbolicName
!= null) {
977 // make sure there is no directive
978 String
[] arr
= rawSourceSymbolicName
.split(";");
979 for (int i
= 1; i
< arr
.length
; i
++) {
980 if (arr
[i
].trim().equals("singleton:=true"))
982 logger
.log(DEBUG
, file
.getFileName() + " is a singleton");
985 // remove problematic entries in MANIFEST
986 manifest
.getEntries().clear();
988 String ourSymbolicName
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
989 String ourVersion
= entries
.get(BUNDLE_VERSION
.toString());
991 if (ourSymbolicName
!= null && ourVersion
!= null) {
992 nameVersion
= new NameVersion(ourSymbolicName
, ourVersion
);
994 nameVersion
= nameVersionFromManifest(manifest
);
995 if (ourVersion
!= null && !nameVersion
.getVersion().equals(ourVersion
)) {
997 "Original version is " + nameVersion
.getVersion() + " while new version is " + ourVersion
);
998 entries
.put(BUNDLE_VERSION
.toString(), ourVersion
);
1000 if (ourSymbolicName
!= null) {
1001 // we always force our symbolic name
1002 nameVersion
.setName(ourSymbolicName
);
1005 bundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
1007 // copy original MANIFEST
1008 if (sourceManifest
!= null) {
1009 Path originalManifest
= bundleDir
.resolve(ARGEO_ORIGIN
).resolve("MANIFEST.MF");
1010 Files
.createDirectories(originalManifest
.getParent());
1011 try (OutputStream out
= Files
.newOutputStream(originalManifest
)) {
1012 sourceManifest
.write(out
);
1014 origin
.moved
.add("original MANIFEST to " + bundleDir
.relativize(originalManifest
));
1017 // force Java 9 module name
1018 entries
.put(ManifestHeader
.AUTOMATIC_MODULE_NAME
.toString(), nameVersion
.getName());
1020 boolean isNative
= false;
1023 if (bundleDir
.startsWith(a2LibBase
)) {
1025 Path libRelativePath
= a2LibBase
.relativize(bundleDir
);
1026 os
= libRelativePath
.getName(0).toString();
1027 arch
= libRelativePath
.getName(1).toString();
1033 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
1034 if (entry
.isDirectory())
1037 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".DSA")
1038 || entry
.getName().endsWith(".SF")) {
1039 origin
.deleted
.add("cryptographic signatures");
1042 if (entry
.getName().endsWith("module-info.class")) { // skip Java 9 module info
1043 origin
.deleted
.add("Java module information (module-info.class)");
1046 if (entry
.getName().startsWith("META-INF/versions/")) { // skip multi-version
1047 origin
.deleted
.add("additional Java versions (META-INF/versions)");
1050 if (entry
.getName().startsWith("META-INF/maven/")) {
1051 origin
.deleted
.add("Maven information (META-INF/maven)");
1054 // skip file system providers as they cause issues with native image
1055 if (entry
.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider")) {
1057 .add("file system providers (META-INF/services/java.nio.file.spi.FileSystemProvider)");
1061 if (entry
.getName().startsWith("OSGI-OPT/src/")) { // skip embedded sources
1062 origin
.deleted
.add("embedded sources");
1065 Path target
= bundleDir
.resolve(entry
.getName());
1066 Files
.createDirectories(target
.getParent());
1067 Files
.copy(jarIn
, target
);
1070 if (isNative
&& (entry
.getName().endsWith(".so") || entry
.getName().endsWith(".dll")
1071 || entry
.getName().endsWith(".jnilib"))) {
1072 Path categoryDir
= bundleDir
.getParent();
1073 boolean copyDll
= false;
1074 Path targetDll
= categoryDir
.resolve(bundleDir
.relativize(target
));
1075 if (nameVersion
.getName().equals("com.sun.jna")) {
1076 if (arch
.equals("x86_64"))
1078 if (os
.equals("macosx"))
1080 if (target
.getParent().getFileName().toString().equals(os
+ "-" + arch
)) {
1083 targetDll
= categoryDir
.resolve(target
.getFileName());
1088 Files
.createDirectories(targetDll
.getParent());
1089 if (Files
.exists(targetDll
))
1090 Files
.delete(targetDll
);
1091 Files
.copy(target
, targetDll
);
1093 Files
.delete(target
);
1094 origin
.deleted
.add(bundleDir
.relativize(target
).toString());
1096 logger
.log(TRACE
, () -> "Copied " + target
);
1102 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
1103 Files
.createDirectories(manifestPath
.getParent());
1105 if (isSingleton
&& entries
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
1106 entries
.put(BUNDLE_SYMBOLICNAME
.toString(),
1107 entries
.get(BUNDLE_SYMBOLICNAME
.toString()) + ";singleton:=true");
1110 // if (embed) {// copy embedded jar
1111 // Files.copy(file, bundleDir.resolve(file.getFileName()));
1112 // entries.put(ManifestHeader.BUNDLE_CLASSPATH.toString(), file.getFileName().toString());
1115 // Final MANIFEST decisions
1116 // We also check the original OSGi metadata and compare with our changes
1117 for (String key
: entries
.keySet()) {
1118 String value
= entries
.get(key
);
1119 String previousValue
= manifest
.getMainAttributes().getValue(key
);
1120 boolean wasDifferent
= previousValue
!= null && !previousValue
.equals(value
);
1121 boolean keepPrevious
= false;
1123 if (SPDX_LICENSE_IDENTIFIER
.toString().equals(key
) && previousValue
!= null)
1124 keepPrevious
= true;
1125 else if (BUNDLE_VERSION
.toString().equals(key
) && wasDifferent
)
1126 if (previousValue
.equals(value
+ ".0")) // typically a Maven first release
1127 keepPrevious
= true;
1130 if (logger
.isLoggable(DEBUG
))
1131 logger
.log(DEBUG
, file
.getFileName() + ": " + key
+ " was NOT modified, value kept is "
1132 + previousValue
+ ", not overriden with " + value
);
1133 value
= previousValue
;
1137 manifest
.getMainAttributes().putValue(key
, value
);
1138 if (wasDifferent
&& !keepPrevious
) {
1139 if (IMPORT_PACKAGE
.toString().equals(key
) || EXPORT_PACKAGE
.toString().equals(key
))
1140 logger
.log(TRACE
, () -> file
.getFileName() + ": " + key
+ " was modified");
1141 else if (BUNDLE_SYMBOLICNAME
.toString().equals(key
) || AUTOMATIC_MODULE_NAME
.toString().equals(key
))
1143 file
.getFileName() + ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
1146 file
.getFileName() + ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
1147 origin
.modified
.add("MANIFEST header " + key
);
1150 // !! hack to remove unresolvable
1151 if (key
.equals("Provide-Capability") || key
.equals("Require-Capability"))
1152 if (nameVersion
.getName().equals("osgi.core") || nameVersion
.getName().equals("osgi.cmpn")) {
1153 manifest
.getMainAttributes().remove(key
);
1154 origin
.deleted
.add("MANIFEST header " + key
);
1158 // de-pollute MANIFEST
1159 for (Iterator
<Map
.Entry
<Object
, Object
>> manifestEntries
= manifest
.getMainAttributes().entrySet()
1160 .iterator(); manifestEntries
.hasNext();) {
1161 Map
.Entry
<Object
, Object
> manifestEntry
= manifestEntries
.next();
1162 switch (manifestEntry
.getKey().toString()) {
1163 case "Archiver-Version":
1166 case "Originally-Created-By":
1168 case "Bnd-LastModified":
1169 manifestEntries
.remove();
1170 origin
.deleted
.add("MANIFEST header " + manifestEntry
.getKey());
1173 if (sourceManifest
!= null && !sourceManifest
.getMainAttributes().containsKey(manifestEntry
.getKey()))
1174 origin
.added
.add("MANIFEST header " + manifestEntry
.getKey());
1178 processLicense(bundleDir
, manifest
);
1180 origin
.modified
.add("MANIFEST (META-INF/MANIFEST.MF)");
1181 // write the MANIFEST
1182 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
1183 manifest
.write(out
);
1188 /** Process SPDX license identifier. */
1189 void processLicense(Path bundleDir
, Manifest manifest
) {
1190 String spdxLicenceId
= manifest
.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER
.toString());
1191 String bundleLicense
= manifest
.getMainAttributes().getValue(BUNDLE_LICENSE
.toString());
1192 if (spdxLicenceId
== null) {
1193 logger
.log(ERROR
, bundleDir
.getFileName() + ": " + SPDX_LICENSE_IDENTIFIER
+ " not available, "
1194 + BUNDLE_LICENSE
+ " is " + bundleLicense
);
1196 // only use the first licensing option
1197 int orIndex
= spdxLicenceId
.indexOf(" OR ");
1199 spdxLicenceId
= spdxLicenceId
.substring(0, orIndex
).trim();
1201 String bundleDirName
= bundleDir
.getFileName().toString();
1202 // force licenses of some well-known components
1203 // even if we say otherwise (typically because from an Eclipse archive)
1204 if (bundleDirName
.startsWith("org.apache."))
1205 spdxLicenceId
= "Apache-2.0";
1206 if (bundleDirName
.startsWith("com.sun.jna."))
1207 spdxLicenceId
= "Apache-2.0";
1208 if (bundleDirName
.startsWith("com.ibm.icu."))
1209 spdxLicenceId
= "ICU";
1210 if (bundleDirName
.startsWith("javax.annotation."))
1211 spdxLicenceId
= "GPL-2.0-only WITH Classpath-exception-2.0";
1212 if (bundleDirName
.startsWith("javax.inject."))
1213 spdxLicenceId
= "Apache-2.0";
1214 if (bundleDirName
.startsWith("org.osgi."))
1215 spdxLicenceId
= "Apache-2.0";
1217 manifest
.getMainAttributes().putValue(SPDX_LICENSE_IDENTIFIER
.toString(), spdxLicenceId
);
1218 if (!licensesUsed
.containsKey(spdxLicenceId
))
1219 licensesUsed
.put(spdxLicenceId
, new TreeSet
<>());
1220 licensesUsed
.get(spdxLicenceId
).add(bundleDir
.getParent().getFileName() + "/" + bundleDir
.getFileName());
1227 /** Recursively deletes a directory. */
1228 static void deleteDirectory(Path path
) throws IOException
{
1229 if (!Files
.exists(path
))
1231 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
1233 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
1236 Files
.delete(directory
);
1241 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1248 /** Extract name/version from a MANIFEST. */
1249 NameVersion
nameVersionFromManifest(Manifest manifest
) {
1250 Attributes attrs
= manifest
.getMainAttributes();
1252 String symbolicName
= attrs
.getValue(ManifestHeader
.BUNDLE_SYMBOLICNAME
.toString());
1253 if (symbolicName
== null)
1255 // make sure there is no directive
1256 symbolicName
= symbolicName
.split(";")[0];
1258 String version
= attrs
.getValue(ManifestHeader
.BUNDLE_VERSION
.toString());
1259 return new NameVersion(symbolicName
, version
);
1262 /** Try to download from an URI. */
1263 Path
tryDownloadArchive(String uri
, Path dir
) throws IOException
{
1265 List
<String
> urlBases
= null;
1266 String uriPrefix
= null;
1267 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
1268 if (uri
.startsWith(uriPref
)) {
1269 if (mirrors
.get(uriPref
).size() > 0) {
1270 urlBases
= mirrors
.get(uriPref
);
1271 uriPrefix
= uriPref
;
1276 if (urlBases
== null)
1278 return downloadArchive(new URL(uri
), dir
);
1279 } catch (FileNotFoundException e
) {
1280 throw new FileNotFoundException("Cannot find " + uri
);
1284 for (String urlBase
: urlBases
) {
1285 String relativePath
= uri
.substring(uriPrefix
.length());
1286 URL url
= new URL(urlBase
+ relativePath
);
1288 return downloadArchive(url
, dir
);
1289 } catch (FileNotFoundException e
) {
1290 logger
.log(WARNING
, "Cannot download " + url
+ ", trying another mirror");
1293 throw new FileNotFoundException("Cannot find " + uri
);
1297 * Effectively download. Synchronised in order to avoid downloading twice in
1300 synchronized Path
downloadArchive(URL url
, Path dir
) throws IOException
{
1301 return download(url
, dir
, (String
) null);
1304 /** Effectively download. */
1305 Path
download(URL url
, Path dir
, String name
) throws IOException
{
1309 // We use also use parent directory in case the archive itself has a fixed name
1310 String
[] segments
= url
.getPath().split("/");
1311 name
= segments
.length
> 1 ? segments
[segments
.length
- 2] + '-' + segments
[segments
.length
- 1]
1312 : segments
[segments
.length
- 1];
1315 dest
= dir
.resolve(name
);
1316 if (Files
.exists(dest
)) {
1317 logger
.log(TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
1320 Files
.createDirectories(dest
.getParent());
1323 try (InputStream in
= url
.openStream()) {
1324 Files
.copy(in
, dest
);
1325 logger
.log(DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
1330 /** Create a JAR file from a directory. */
1331 Path
createJar(Path bundleDir
, A2Origin origin
) throws IOException
{
1332 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
1334 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
1335 manifest
= new Manifest(in
);
1337 // legal requirements
1338 origin
.appendChanges(bundleDir
);
1339 createReadMe(bundleDir
, manifest
);
1342 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
1343 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
1344 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
1345 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
1348 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1349 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1350 return super.visitFile(file
, attrs
);
1351 JarEntry entry
= new JarEntry(
1352 bundleDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1353 jarOut
.putNextEntry(entry
);
1354 Files
.copy(file
, jarOut
);
1355 return super.visitFile(file
, attrs
);
1360 deleteDirectory(bundleDir
);
1363 createSourceJar(bundleDir
, manifest
, false);
1368 /** Package sources separately, in the Eclipse-SourceBundle format. */
1369 void createSourceJar(Path bundleDir
, Manifest manifest
, boolean notModified
) throws IOException
{
1370 Path bundleCategoryDir
= bundleDir
.getParent();
1371 Path sourceDir
= bundleCategoryDir
.resolve(bundleDir
.toString() + ".src");
1372 if (!Files
.exists(sourceDir
)) {
1373 logger
.log(WARNING
, sourceDir
+ " does not exist, skipping...");
1378 createReadMe(sourceDir
, manifest
);
1380 Path relPath
= a2Base
.relativize(bundleCategoryDir
);
1381 Path srcCategoryDir
= a2SrcBase
.resolve(relPath
);
1382 Path srcJarP
= srcCategoryDir
.resolve(sourceDir
.getFileName() + ".jar");
1383 Files
.createDirectories(srcJarP
.getParent());
1385 String bundleSymbolicName
= manifest
.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1386 // in case there are additional directives
1387 bundleSymbolicName
= bundleSymbolicName
.split(";")[0];
1388 Manifest srcManifest
= new Manifest();
1389 srcManifest
.getMainAttributes().put(MANIFEST_VERSION
, "1.0");
1390 srcManifest
.getMainAttributes().putValue(BUNDLE_SYMBOLICNAME
.toString(), bundleSymbolicName
+ ".src");
1391 srcManifest
.getMainAttributes().putValue(BUNDLE_VERSION
.toString(),
1392 manifest
.getMainAttributes().getValue(BUNDLE_VERSION
.toString()).toString());
1393 srcManifest
.getMainAttributes().putValue(ECLIPSE_SOURCE_BUNDLE
.toString(), bundleSymbolicName
+ ";version=\""
1394 + manifest
.getMainAttributes().getValue(BUNDLE_VERSION
.toString()) + "\"");
1396 try (JarOutputStream srcJarOut
= new JarOutputStream(Files
.newOutputStream(srcJarP
), srcManifest
)) {
1397 srcJarOut
.setLevel(Deflater
.BEST_COMPRESSION
);
1398 Files
.walkFileTree(sourceDir
, new SimpleFileVisitor
<Path
>() {
1401 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1402 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1403 return super.visitFile(file
, attrs
);
1404 JarEntry entry
= new JarEntry(
1405 sourceDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1406 srcJarOut
.putNextEntry(entry
);
1407 Files
.copy(file
, srcJarOut
);
1408 return super.visitFile(file
, attrs
);
1413 deleteDirectory(sourceDir
);
1417 * Generate a readme clarifying and prominently notifying of the repackaging and
1420 void createReadMe(Path jarDir
, Manifest manifest
) throws IOException
{
1421 // write repackaged README
1422 try (BufferedWriter writer
= Files
.newBufferedWriter(jarDir
.resolve(README_REPACKAGED
))) {
1423 boolean merged
= manifest
.getMainAttributes().getValue(ARGEO_ORIGIN_M2_MERGE
.toString()) != null;
1425 writer
.append("This component is a merging of third party components"
1426 + " in order to comply with A2 packaging standards.\n");
1428 writer
.append("This component is a repackaging of a third party component"
1429 + " in order to comply with A2 packaging standards.\n");
1432 String spdxLicenseId
= manifest
.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER
.toString());
1433 if (spdxLicenseId
== null)
1434 throw new IllegalStateException("An SPDX license id must have beend defined at this stage.");
1435 writer
.append("\nIt is redistributed under the following license:\n\n");
1436 writer
.append("SPDX-Identifier: " + spdxLicenseId
+ "\n\n");
1438 if (!spdxLicenseId
.startsWith("LicenseRef")) {// standard
1439 int withIndex
= spdxLicenseId
.indexOf(" WITH ");
1440 if (withIndex
>= 0) {
1441 String simpleId
= spdxLicenseId
.substring(0, withIndex
).trim();
1442 String exception
= spdxLicenseId
.substring(withIndex
+ " WITH ".length());
1443 writer
.append("which are available here: https://spdx.org/licenses/" + simpleId
1444 + "\nand here: https://spdx.org/licenses/" + exception
+ "\n");
1446 writer
.append("which is available here: https://spdx.org/licenses/" + spdxLicenseId
+ "\n");
1449 String url
= manifest
.getMainAttributes().getValue(BUNDLE_LICENSE
.toString());
1451 writer
.write("which is available here: " + url
+ "\n");
1453 logger
.log(ERROR
, "No licne URL for " + jarDir
);
1459 String m2Repo
= manifest
.getMainAttributes().getValue(ARGEO_ORIGIN_M2_REPO
.toString());
1460 String originDesc
= manifest
.getMainAttributes().getValue(ARGEO_ORIGIN_M2
.toString());
1461 if (originDesc
!= null)
1462 writer
.append("The original component has M2 coordinates:\n" + originDesc
.replace(',', '\n') + "\n"
1463 + (m2Repo
!= null ?
"\nin M2 repository " + m2Repo
+ "\n" : ""));
1465 originDesc
= manifest
.getMainAttributes().getValue(ARGEO_ORIGIN_URI
.toString());
1466 if (originDesc
!= null)
1467 writer
.append("The original component comes from " + originDesc
+ ".\n");
1469 logger
.log(ERROR
, "Cannot find origin information in " + jarDir
);
1472 writer
.append("\nA detailed list of changes is available under " + CHANGES
+ ".\n");
1473 if (!jarDir
.getFileName().endsWith(".src")) {// binary archive
1475 writer
.append("Corresponding sources are available in the related archive named "
1476 + jarDir
.toString() + ".src.jar.\n");
1478 writer
.append("Corresponding sources are available under OSGI-OPT/src.\n");
1485 * Gathers modifications performed on the original binaries and sources,
1486 * especially in order to comply with their license requirements.
1493 Set
<String
> modified
= new TreeSet
<>();
1494 Set
<String
> deleted
= new TreeSet
<>();
1495 Set
<String
> added
= new TreeSet
<>();
1496 Set
<String
> moved
= new TreeSet
<>();
1498 /** Append changes to the A2-ORIGIN/changes file. */
1499 void appendChanges(Path baseDirectory
) throws IOException
{
1500 Path changesFile
= baseDirectory
.resolve(CHANGES
);
1501 Files
.createDirectories(changesFile
.getParent());
1502 try (BufferedWriter writer
= Files
.newBufferedWriter(changesFile
, APPEND
, CREATE
)) {
1503 for (String msg
: added
)
1504 writer
.write("- Added " + msg
+ ".\n");
1505 for (String msg
: modified
)
1506 writer
.write("- Modified " + msg
+ ".\n");
1507 for (String msg
: moved
)
1508 writer
.write("- Moved " + msg
+ ".\n");
1509 for (String msg
: deleted
)
1510 writer
.write("- Deleted " + msg
+ ".\n");
1516 /** Simple representation of an M2 artifact. */
1517 class M2Artifact
extends CategoryNameVersion
{
1518 private String classifier
;
1520 M2Artifact(String m2coordinates
) {
1521 this(m2coordinates
, null);
1524 M2Artifact(String m2coordinates
, String classifier
) {
1525 String
[] parts
= m2coordinates
.split(":");
1526 setCategory(parts
[0]);
1528 if (parts
.length
> 2) {
1529 setVersion(parts
[2]);
1531 this.classifier
= classifier
;
1534 String
getGroupId() {
1535 return super.getCategory();
1538 String
getArtifactId() {
1539 return super.getName();
1542 String
toM2Coordinates() {
1543 return getCategory() + ":" + getName() + (getVersion() != null ?
":" + getVersion() : "");
1546 String
getClassifier() {
1547 return classifier
!= null ? classifier
: "";
1550 String
getExtension() {
1555 /** Utilities around Maven (conventions based). */
1556 class M2ConventionsUtils
{
1557 final static String MAVEN_CENTRAL_BASE_URL
= "https://repo1.maven.org/maven2/";
1559 /** The file name of this artifact when stored */
1560 static String
artifactFileName(M2Artifact artifact
) {
1561 return artifact
.getArtifactId() + '-' + artifact
.getVersion()
1562 + (artifact
.getClassifier().equals("") ?
"" : '-' + artifact
.getClassifier()) + '.'
1563 + artifact
.getExtension();
1566 /** Absolute path to the file */
1567 static String
artifactPath(String artifactBasePath
, M2Artifact artifact
) {
1568 return artifactParentPath(artifactBasePath
, artifact
) + '/' + artifactFileName(artifact
);
1571 /** Absolute path to the file */
1572 static String
artifactUrl(String repoUrl
, M2Artifact artifact
) {
1573 if (repoUrl
.endsWith("/"))
1574 return repoUrl
+ artifactPath("/", artifact
).substring(1);
1576 return repoUrl
+ artifactPath("/", artifact
);
1579 /** Absolute path to the file */
1580 static URL
mavenRepoUrl(String repoBase
, M2Artifact artifact
) {
1581 String url
= artifactUrl(repoBase
== null ? MAVEN_CENTRAL_BASE_URL
: repoBase
, artifact
);
1583 return new URL(url
);
1584 } catch (MalformedURLException e
) {
1585 // it should not happen
1586 throw new IllegalStateException(e
);
1590 /** Absolute path to the directories where the files will be stored */
1591 static String
artifactParentPath(String artifactBasePath
, M2Artifact artifact
) {
1592 return artifactBasePath
+ (artifactBasePath
.endsWith("/") || artifactBasePath
.equals("") ?
"" : "/")
1593 + artifactParentPath(artifact
);
1596 /** Relative path to the directories where the files will be stored */
1597 static String
artifactParentPath(M2Artifact artifact
) {
1598 return artifact
.getGroupId().replace('.', '/') + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion();
1602 private M2ConventionsUtils() {
1606 /** Combination of a category, a name and a version. */
1607 class CategoryNameVersion
extends NameVersion
{
1608 private String category
;
1610 CategoryNameVersion() {
1613 CategoryNameVersion(String category
, String name
, String version
) {
1614 super(name
, version
);
1615 this.category
= category
;
1618 CategoryNameVersion(String category
, NameVersion nameVersion
) {
1620 this.category
= category
;
1623 String
getCategory() {
1627 void setCategory(String category
) {
1628 this.category
= category
;
1632 public String
toString() {
1633 return category
+ ":" + super.toString();
1638 /** Combination of a name and a version. */
1639 class NameVersion
implements Comparable
<NameVersion
> {
1640 private String name
;
1641 private String version
;
1646 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1647 NameVersion(String nameVersion
) {
1648 int index
= nameVersion
.indexOf(";version=");
1650 setName(nameVersion
);
1653 setName(nameVersion
.substring(0, index
));
1654 setVersion(nameVersion
.substring(index
+ ";version=".length()));
1658 NameVersion(String name
, String version
) {
1660 this.version
= version
;
1663 NameVersion(NameVersion nameVersion
) {
1664 this.name
= nameVersion
.getName();
1665 this.version
= nameVersion
.getVersion();
1672 void setName(String name
) {
1676 String
getVersion() {
1680 void setVersion(String version
) {
1681 this.version
= version
;
1684 String
getBranch() {
1685 String
[] parts
= getVersion().split("\\.");
1686 if (parts
.length
< 2)
1687 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1688 return parts
[0] + "." + parts
[1];
1692 public boolean equals(Object obj
) {
1693 if (obj
instanceof NameVersion
) {
1694 NameVersion nameVersion
= (NameVersion
) obj
;
1695 return name
.equals(nameVersion
.getName()) && version
.equals(nameVersion
.getVersion());
1701 public int hashCode() {
1702 return name
.hashCode();
1706 public String
toString() {
1707 return name
+ ":" + version
;
1710 public int compareTo(NameVersion o
) {
1711 if (o
.getName().equals(name
))
1712 return version
.compareTo(o
.getVersion());
1714 return name
.compareTo(o
.getName());