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"), //
183 final String headerName
;
185 private ManifestHeader(String headerName
) {
186 this.headerName
= headerName
;
190 public String
toString() {
194 /** Get the value from either a {@link Manifest} or a {@link Properties}. */
195 String
get(Object map
) {
196 if (map
instanceof Manifest manifest
)
197 return manifest
.getMainAttributes().getValue(headerName
);
198 else if (map
instanceof Properties props
)
199 return props
.getProperty(headerName
);
201 throw new IllegalArgumentException("Unsupported mapping " + map
.getClass());
204 /** Put the value into either a {@link Manifest} or a {@link Properties}. */
205 void put(Object map
, String value
) {
206 if (map
instanceof Manifest manifest
)
207 manifest
.getMainAttributes().putValue(headerName
, value
);
208 else if (map
instanceof Properties props
)
209 props
.setProperty(headerName
, value
);
211 throw new IllegalArgumentException("Unsupported mapping " + map
.getClass());
215 /** Name of the file centralising information for multiple M2 artifacts. */
216 final static String COMMON_BND
= "common.bnd";
217 /** Name of the file centralising information for mergin M2 artifacts. */
218 final static String MERGE_BND
= "merge.bnd";
220 * Subdirectory of the jar file where origin informations (changes, legal
221 * notices etc. are stored)
223 final static String ARGEO_ORIGIN
= "ARGEO-ORIGIN";
224 /** File detailing modifications to the original component. */
225 final static String CHANGES
= ARGEO_ORIGIN
+ "/changes";
227 * Name of the file at the root of the repackaged jar, which prominently
228 * notifies that the component has be repackaged.
230 final static String README_REPACKAGED
= "README.repackaged";
233 /** Summary of all license seen during the repackaging. */
234 final static Map
<String
, Set
<String
>> licensesUsed
= new TreeMap
<>();
236 /** Directory where to download archives */
237 final Path originBase
;
238 /** Directory where to download Maven artifacts */
239 final Path mavenBase
;
241 /** A2 repository base for binary bundles */
243 /** A2 repository base for source bundles */
244 final Path a2SrcBase
;
245 /** A2 base for native components */
246 final Path a2LibBase
;
247 /** Location of the descriptors driving the packaging */
248 final Path descriptorsBase
;
249 /** URIs of archives to download */
250 final Properties uris
= new Properties();
251 /** Mirrors for archive download. Key is URI prefix, value list of base URLs */
252 final Map
<String
, List
<String
>> mirrors
= new HashMap
<String
, List
<String
>>();
254 /** Whether sources should be packaged separately */
255 final boolean separateSources
;
257 /** Constructor initialises the various variables */
258 public Repackage(Path a2Base
, Path descriptorsBase
) {
259 separateSources
= Boolean
.parseBoolean(System
.getenv(ENV_SOURCE_BUNDLES
));
261 logger
.log(INFO
, "Sources will be packaged separately");
263 Objects
.requireNonNull(a2Base
);
264 Objects
.requireNonNull(descriptorsBase
);
265 this.originBase
= Paths
.get(System
.getProperty("user.home"), ".cache", "argeo/build/origin");
266 this.mavenBase
= Paths
.get(System
.getProperty("user.home"), ".m2", "repository");
268 // TODO define and use a build base
269 this.a2Base
= a2Base
;
270 this.a2SrcBase
= separateSources ? a2Base
.getParent().resolve(a2Base
.getFileName() + ".src") : a2Base
;
271 this.a2LibBase
= a2Base
.resolve("lib");
272 this.descriptorsBase
= descriptorsBase
;
273 if (!Files
.exists(this.descriptorsBase
))
274 throw new IllegalArgumentException(this.descriptorsBase
+ " does not exist");
277 Path urisPath
= this.descriptorsBase
.resolve("uris.properties");
278 if (Files
.exists(urisPath
)) {
279 try (InputStream in
= Files
.newInputStream(urisPath
)) {
281 } catch (IOException e
) {
282 throw new IllegalStateException("Cannot load " + urisPath
, e
);
287 Path eclipseMirrorsPath
= this.descriptorsBase
.resolve("eclipse.mirrors.txt");
288 List
<String
> eclipseMirrors
= new ArrayList
<>();
289 if (Files
.exists(eclipseMirrorsPath
)) {
291 eclipseMirrors
= Files
.readAllLines(eclipseMirrorsPath
, StandardCharsets
.UTF_8
);
292 } catch (IOException e
) {
293 throw new IllegalStateException("Cannot load " + eclipseMirrorsPath
, e
);
295 for (Iterator
<String
> it
= eclipseMirrors
.iterator(); it
.hasNext();) {
296 String value
= it
.next();
297 if (value
.strip().equals(""))
301 mirrors
.put("http://www.eclipse.org/downloads", eclipseMirrors
);
307 /** Process a whole category/group id. */
308 void processCategory(Path categoryRelativePath
) {
310 Path targetCategoryBase
= descriptorsBase
.resolve(categoryRelativePath
);
311 DirectoryStream
<Path
> bnds
= Files
.newDirectoryStream(targetCategoryBase
,
312 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
313 && !p
.getFileName().toString().equals(MERGE_BND
));
314 for (Path p
: bnds
) {
315 processSingleM2ArtifactDistributionUnit(p
);
318 DirectoryStream
<Path
> dus
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
319 for (Path duDir
: dus
) {
320 if (duDir
.getFileName().toString().startsWith("eclipse-")) {
321 processEclipseArchive(duDir
);
323 processM2BasedDistributionUnit(duDir
);
326 } catch (IOException e
) {
327 throw new RuntimeException("Cannot process category " + categoryRelativePath
, e
);
331 /** Process a standalone Maven artifact. */
332 void processSingleM2ArtifactDistributionUnit(Path bndFile
) {
334 Path categoryRelativePath
= descriptorsBase
.relativize(bndFile
.getParent());
335 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
337 Properties fileProps
= new Properties();
338 try (InputStream in
= Files
.newInputStream(bndFile
)) {
341 // use file name as symbolic name
342 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
343 String symbolicName
= bndFile
.getFileName().toString();
344 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
345 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
348 String m2Coordinates
= fileProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
349 if (m2Coordinates
== null)
350 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile
);
351 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
353 Path downloaded
= downloadMaven(fileProps
, artifact
);
355 boolean doNotModify
= Boolean
356 .parseBoolean(fileProps
.getOrDefault(ARGEO_DO_NOT_MODIFY
.toString(), "false").toString());
358 processNotModified(targetCategoryBase
, downloaded
, fileProps
, artifact
);
362 // regular processing
363 A2Origin origin
= new A2Origin();
364 Path bundleDir
= processBndJar(downloaded
, targetCategoryBase
, fileProps
, artifact
, origin
);
365 downloadAndProcessM2Sources(fileProps
, artifact
, bundleDir
, false, false);
366 createJar(bundleDir
, origin
);
367 } catch (Exception e
) {
368 throw new RuntimeException("Cannot process " + bndFile
, e
);
373 * Process multiple Maven artifacts coming from a same project and therefore
374 * with information in common (typically the version), generating single bundles
375 * or merging them if necessary.
380 void processM2BasedDistributionUnit(Path duDir
) {
382 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
383 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
385 Path mergeBnd
= duDir
.resolve(MERGE_BND
);
386 if (Files
.exists(mergeBnd
)) // merge
387 mergeM2Artifacts(mergeBnd
);
389 Path commonBnd
= duDir
.resolve(COMMON_BND
);
390 if (!Files
.exists(commonBnd
))
393 Properties commonProps
= new Properties();
394 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
395 commonProps
.load(in
);
398 String m2Version
= commonProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
399 if (m2Version
== null) {
400 logger
.log(WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
401 return;// ignore, this is probably an Eclipse archive
403 if (!m2Version
.startsWith(":")) {
404 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
406 m2Version
= m2Version
.substring(1);
408 DirectoryStream
<Path
> ds
= Files
.newDirectoryStream(duDir
,
409 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
410 && !p
.getFileName().toString().equals(MERGE_BND
));
412 Properties fileProps
= new Properties();
413 try (InputStream in
= Files
.newInputStream(p
)) {
416 String m2Coordinates
= fileProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
417 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
418 if (artifact
.getVersion() == null) {
419 artifact
.setVersion(m2Version
);
421 logger
.log(WARNING
, p
.getFileName() + " : Using version " + artifact
.getVersion()
422 + " specified in descriptor rather than " + m2Version
+ " specified in " + COMMON_BND
);
425 // prepare manifest entries
426 Properties mergedProps
= new Properties();
427 mergedProps
.putAll(commonProps
);
429 fileEntries
: for (Object key
: fileProps
.keySet()) {
430 if (ARGEO_ORIGIN_M2
.toString().equals(key
))
431 continue fileEntries
;
432 String value
= fileProps
.getProperty(key
.toString());
433 Object previousValue
= mergedProps
.put(key
.toString(), value
);
434 if (previousValue
!= null) {
436 commonBnd
+ ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
439 mergedProps
.put(ARGEO_ORIGIN_M2
.toString(), artifact
.toM2Coordinates());
440 if (!mergedProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
441 // use file name as symbolic name
442 String symbolicName
= p
.getFileName().toString();
443 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
444 mergedProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
448 Path downloaded
= downloadMaven(mergedProps
, artifact
);
450 boolean doNotModify
= Boolean
451 .parseBoolean(mergedProps
.getOrDefault(ARGEO_DO_NOT_MODIFY
.toString(), "false").toString());
453 processNotModified(targetCategoryBase
, downloaded
, mergedProps
, artifact
);
455 A2Origin origin
= new A2Origin();
456 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, mergedProps
, artifact
, origin
);
457 downloadAndProcessM2Sources(mergedProps
, artifact
, targetBundleDir
, false, false);
458 createJar(targetBundleDir
, origin
);
461 } catch (IOException e
) {
462 throw new RuntimeException("Cannot process " + duDir
, e
);
466 /** Merge multiple Maven artifacts. */
467 void mergeM2Artifacts(Path mergeBnd
) throws IOException
{
468 Path duDir
= mergeBnd
.getParent();
469 String category
= duDir
.getParent().getFileName().toString();
470 Path targetCategoryBase
= a2Base
.resolve(category
);
472 Properties mergeProps
= new Properties();
473 // first, load common properties
474 Path commonBnd
= duDir
.resolve(COMMON_BND
);
475 if (Files
.exists(commonBnd
))
476 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
479 // then, the merge properties themselves
480 try (InputStream in
= Files
.newInputStream(mergeBnd
)) {
484 String m2Version
= mergeProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
485 if (m2Version
== null) {
486 logger
.log(WARNING
, "Ignoring merging in " + duDir
+ " as it is not an M2-based distribution unit");
487 return;// ignore, this is probably an Eclipse archive
489 if (!m2Version
.startsWith(":")) {
490 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
492 m2Version
= m2Version
.substring(1);
493 mergeProps
.put(BUNDLE_VERSION
.toString(), m2Version
);
495 String artifactsStr
= mergeProps
.getProperty(ARGEO_ORIGIN_M2_MERGE
.toString());
496 if (artifactsStr
== null)
497 throw new IllegalArgumentException(mergeBnd
+ ": " + ARGEO_ORIGIN_M2_MERGE
+ " must be set");
499 String bundleSymbolicName
= mergeProps
.getProperty(BUNDLE_SYMBOLICNAME
.toString());
500 if (bundleSymbolicName
== null)
501 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd
);
502 CategoryNameVersion nameVersion
= new M2Artifact(category
+ ":" + bundleSymbolicName
+ ":" + m2Version
);
504 A2Origin origin
= new A2Origin();
505 Path bundleDir
= targetCategoryBase
.resolve(bundleSymbolicName
+ "." + nameVersion
.getBranch());
507 StringJoiner originDesc
= new StringJoiner(",");
508 String
[] artifacts
= artifactsStr
.split(",");
509 artifacts
: for (String str
: artifacts
) {
510 String m2Coordinates
= str
.trim();
511 if ("".equals(m2Coordinates
))
513 M2Artifact artifact
= new M2Artifact(m2Coordinates
.trim());
514 if (artifact
.getVersion() == null)
515 artifact
.setVersion(m2Version
);
516 originDesc
.add(artifact
.toString());
517 Path downloaded
= downloadMaven(mergeProps
, artifact
);
519 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(downloaded
), false)) {
520 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
521 if (entry
.isDirectory())
523 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".DSA")
524 || entry
.getName().endsWith(".SF")) {
525 origin
.deleted
.add("cryptographic signatures from " + artifact
);
528 if (entry
.getName().endsWith("module-info.class")) { // skip Java 9 module info
529 origin
.deleted
.add("Java module information (module-info.class) from " + artifact
);
532 if (entry
.getName().startsWith("META-INF/versions/")) { // skip multi-version
533 origin
.deleted
.add("additional Java versions (META-INF/versions) from " + artifact
);
536 if (entry
.getName().startsWith("META-INF/maven/")) {
537 origin
.deleted
.add("Maven information (META-INF/maven) from " + artifact
);
540 if (entry
.getName().startsWith(".cache/")) { // Apache SSHD
541 origin
.deleted
.add("cache directory (.cache) from " + artifact
);
544 if (entry
.getName().equals("META-INF/DEPENDENCIES")) {
545 origin
.deleted
.add("Dependencies (META-INF/DEPENDENCIES) from " + artifact
);
548 if (entry
.getName().equals("META-INF/MANIFEST.MF")) {
549 Path originalManifest
= bundleDir
.resolve(ARGEO_ORIGIN
).resolve(artifact
.getGroupId())
550 .resolve(artifact
.getArtifactId()).resolve("MANIFEST.MF");
551 Files
.createDirectories(originalManifest
.getParent());
552 try (OutputStream out
= Files
.newOutputStream(originalManifest
)) {
553 Files
.copy(jarIn
, originalManifest
);
556 "original MANIFEST (" + bundleDir
.relativize(originalManifest
) + ") from " + artifact
);
560 if (entry
.getName().endsWith("NOTICE") || entry
.getName().endsWith("NOTICE.txt")
561 || entry
.getName().endsWith("LICENSE") || entry
.getName().endsWith("LICENSE.md")
562 || entry
.getName().endsWith("LICENSE-notice.md") || entry
.getName().endsWith("COPYING")
563 || entry
.getName().endsWith("COPYING.LESSER")) {
564 Path artifactOriginDir
= bundleDir
.resolve(ARGEO_ORIGIN
).resolve(artifact
.getGroupId())
565 .resolve(artifact
.getArtifactId());
566 Path target
= artifactOriginDir
.resolve(entry
.getName());
567 Files
.createDirectories(target
.getParent());
568 Files
.copy(jarIn
, target
);
569 origin
.moved
.add(entry
.getName() + " in " + artifact
+ " to " + bundleDir
.relativize(target
));
572 Path target
= bundleDir
.resolve(entry
.getName());
573 Files
.createDirectories(target
.getParent());
574 if (!Files
.exists(target
)) {
575 Files
.copy(jarIn
, target
);
577 if (entry
.getName().startsWith("META-INF/services/")) {
578 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
579 out
.write("\n".getBytes());
580 jarIn
.transferTo(out
);
581 logger
.log(DEBUG
, artifact
.getArtifactId() + " - Appended " + entry
.getName());
583 origin
.modified
.add(entry
.getName() + ", merging from " + artifact
);
584 } else if (entry
.getName().startsWith("org/apache/batik/")) {
585 logger
.log(TRACE
, "Skip " + entry
.getName());
588 throw new IllegalStateException("File " + target
+ " from " + artifact
+ " already exists");
591 logger
.log(TRACE
, () -> "Copied " + target
);
594 origin
.added
.add("binary content of " + artifact
);
597 downloadAndProcessM2Sources(mergeProps
, artifact
, bundleDir
, true, false);
600 // additional service files
601 Path servicesDir
= duDir
.resolve("services");
602 if (Files
.exists(servicesDir
)) {
603 for (Path p
: Files
.newDirectoryStream(servicesDir
)) {
604 Path target
= bundleDir
.resolve("META-INF/services/").resolve(p
.getFileName());
605 try (InputStream in
= Files
.newInputStream(p
);
606 OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
);) {
607 out
.write("\n".getBytes());
609 logger
.log(DEBUG
, "Appended " + p
);
611 origin
.added
.add(bundleDir
.relativize(target
).toString());
616 Map
<String
, String
> entries
= new TreeMap
<>();
617 try (Analyzer bndAnalyzer
= new Analyzer()) {
618 bndAnalyzer
.setProperties(mergeProps
);
619 Jar jar
= new Jar(bundleDir
.toFile());
620 bndAnalyzer
.setJar(jar
);
621 Manifest manifest
= bndAnalyzer
.calcManifest();
623 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
624 Object value
= manifest
.getMainAttributes().get(key
);
626 switch (key
.toString()) {
628 case "Bnd-LastModified":
632 if ("Require-Capability".equals(key
.toString())
633 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\"")) {
634 origin
.deleted
.add("MANIFEST header " + key
);
635 continue keys
;// hack for very old classes
637 entries
.put(key
.toString(), value
.toString());
639 } catch (Exception e
) {
640 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
643 Manifest manifest
= new Manifest();
644 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
645 Files
.createDirectories(manifestPath
.getParent());
646 for (String key
: entries
.keySet()) {
647 String value
= entries
.get(key
);
648 manifest
.getMainAttributes().putValue(key
, value
);
650 manifest
.getMainAttributes().putValue(ARGEO_ORIGIN_M2
.toString(), originDesc
.toString());
652 processLicense(bundleDir
, manifest
);
655 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
658 createJar(bundleDir
, origin
);
661 /** Generates MANIFEST using BND. */
662 Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
, M2Artifact artifact
,
665 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
666 boolean doNotModifyManifest
= Boolean
.parseBoolean(
667 fileProps
.getOrDefault(ARGEO_ORIGIN_NO_METADATA_GENERATION
.toString(), "false").toString());
669 // Note: we always force the symbolic name
670 if (doNotModifyManifest
) {
671 for (Object key
: fileProps
.keySet()) {
672 String value
= fileProps
.getProperty(key
.toString());
673 additionalEntries
.put(key
.toString(), value
);
676 if (artifact
!= null) {
677 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
678 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
680 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
681 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
685 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
686 fileProps
.put(EXPORT_PACKAGE
.toString(),
687 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
691 try (Analyzer bndAnalyzer
= new Analyzer()) {
692 bndAnalyzer
.setProperties(fileProps
);
693 Jar jar
= new Jar(downloaded
.toFile());
694 bndAnalyzer
.setJar(jar
);
695 Manifest manifest
= bndAnalyzer
.calcManifest();
697 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
698 Object value
= manifest
.getMainAttributes().get(key
);
700 switch (key
.toString()) {
702 case "Bnd-LastModified":
706 if ("Require-Capability".equals(key
.toString())
707 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\"")) {
708 origin
.deleted
.add("MANIFEST header " + key
);
709 continue keys
;// !! hack for very old classes
711 additionalEntries
.put(key
.toString(), value
.toString());
715 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
, origin
);
716 logger
.log(DEBUG
, () -> "Processed " + downloaded
);
717 return targetBundleDir
;
718 } catch (Exception e
) {
719 throw new RuntimeException("Cannot BND process " + downloaded
, e
);
724 /** Process an artifact that should not be modified. */
725 void processNotModified(Path targetCategoryBase
, Path downloaded
, Properties fileProps
, M2Artifact artifact
)
727 // Some proprietary or signed artifacts do not allow any modification
728 // When releasing (with separate sources), we just copy it
729 Path unmodifiedTarget
= targetCategoryBase
730 .resolve(fileProps
.getProperty(BUNDLE_SYMBOLICNAME
.toString()) + "." + artifact
.getBranch() + ".jar");
731 Files
.createDirectories(unmodifiedTarget
.getParent());
732 Files
.copy(downloaded
, unmodifiedTarget
, StandardCopyOption
.REPLACE_EXISTING
);
733 Path bundleDir
= targetCategoryBase
734 .resolve(fileProps
.getProperty(BUNDLE_SYMBOLICNAME
.toString()) + "." + artifact
.getBranch());
735 downloadAndProcessM2Sources(fileProps
, artifact
, bundleDir
, false, true);
737 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(unmodifiedTarget
))) {
738 manifest
= jarIn
.getManifest();
740 createSourceJar(bundleDir
, manifest
, fileProps
);
743 /** Download and integrates sources for a single Maven artifact. */
744 void downloadAndProcessM2Sources(Properties props
, M2Artifact artifact
, Path targetBundleDir
, boolean merging
,
745 boolean unmodified
) throws IOException
{
747 String repoStr
= props
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
748 ? props
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
750 String alternateUri
= props
.getProperty(ARGEO_ORIGIN_SOURCES_URI
.toString());
751 M2Artifact sourcesArtifact
= new M2Artifact(artifact
.toM2Coordinates(), "sources");
752 URL sourcesUrl
= alternateUri
!= null ?
new URL(alternateUri
)
753 : M2ConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
754 Path sourcesDownloaded
= downloadMaven(sourcesUrl
, sourcesArtifact
);
755 processM2SourceJar(sourcesDownloaded
, targetBundleDir
, merging ? artifact
: null, unmodified
);
756 logger
.log(TRACE
, () -> "Processed source " + sourcesDownloaded
);
757 } catch (Exception e
) {
758 logger
.log(ERROR
, () -> "Cannot download source for " + artifact
);
763 /** Integrate sources from a downloaded jar file. */
764 void processM2SourceJar(Path file
, Path bundleDir
, M2Artifact mergingFrom
, boolean unmodified
) throws IOException
{
765 A2Origin origin
= new A2Origin();
766 Path sourceDir
= separateSources
|| unmodified ? bundleDir
.getParent().resolve(bundleDir
.toString() + ".src")
767 : bundleDir
.resolve("OSGI-OPT/src");
768 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
770 String mergingMsg
= "";
771 if (mergingFrom
!= null)
772 mergingMsg
= " of " + mergingFrom
;
774 Files
.createDirectories(sourceDir
);
776 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
777 String relPath
= entry
.getName();
778 if (entry
.isDirectory())
780 if (entry
.getName().equals("META-INF/MANIFEST.MF")) {// skip META-INF entries
781 origin
.deleted
.add("MANIFEST.MF from the sources" + mergingMsg
);
785 if (entry
.getName().startsWith("module-info.java")) {// skip Java module information
786 origin
.deleted
.add("Java module information from the sources (module-info.java)" + mergingMsg
);
789 if (entry
.getName().startsWith("/")) { // absolute paths
790 int metaInfIndex
= entry
.getName().indexOf("META-INF");
791 if (metaInfIndex
>= 0) {
792 relPath
= entry
.getName().substring(metaInfIndex
);
793 origin
.moved
.add(" to " + relPath
+ " entry with absolute path " + entry
.getName());
795 logger
.log(WARNING
, entry
.getName() + " has an absolute path");
796 origin
.deleted
.add(entry
.getName() + " from the sources" + mergingMsg
);
801 Path target
= sourceDir
.resolve(relPath
);
802 Files
.createDirectories(target
.getParent());
803 if (!Files
.exists(target
)) {
804 Files
.copy(jarIn
, target
);
805 logger
.log(TRACE
, () -> "Copied source " + target
);
807 logger
.log(TRACE
, () -> target
+ " already exists, skipping...");
812 if (separateSources
|| unmodified
) {
813 origin
.appendChanges(sourceDir
);
815 origin
.added
.add("source code under OSGI-OPT/src");
816 origin
.appendChanges(bundleDir
);
820 /** Download a Maven artifact. */
821 Path
downloadMaven(Properties props
, M2Artifact artifact
) throws IOException
{
822 String repoStr
= props
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
823 ? props
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
825 String alternateUri
= props
.getProperty(ARGEO_ORIGIN_URI
.toString());
826 URL url
= alternateUri
!= null ?
new URL(alternateUri
) : M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
827 return downloadMaven(url
, artifact
);
830 /** Download a Maven artifact. */
831 Path
downloadMaven(URL url
, M2Artifact artifact
) throws IOException
{
832 return download(url
, mavenBase
, M2ConventionsUtils
.artifactPath("", artifact
));
838 /** Process an archive in Eclipse format. */
839 void processEclipseArchive(Path duDir
) {
841 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
842 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
843 Files
.createDirectories(targetCategoryBase
);
844 // first delete all directories from previous builds
845 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)))
846 deleteDirectory(dir
);
848 Files
.createDirectories(originBase
);
850 Path commonBnd
= duDir
.resolve(COMMON_BND
);
851 Properties commonProps
= new Properties();
852 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
853 commonProps
.load(in
);
855 String url
= commonProps
.getProperty(ARGEO_ORIGIN_URI
.toString());
857 url
= uris
.getProperty(duDir
.getFileName().toString());
859 throw new IllegalStateException("No url available for " + duDir
);
860 commonProps
.put(ARGEO_ORIGIN_URI
.toString(), url
);
862 Path downloaded
= tryDownloadArchive(url
, originBase
);
864 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
867 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
868 Properties includes
= new Properties();
869 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
872 for (Object pattern
: includes
.keySet()) {
873 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
874 includeMatchers
.add(pathMatcher
);
877 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
878 Path excludeFile
= duDir
.resolve("excludes.properties");
879 if (Files
.exists(excludeFile
)) {
880 Properties excludes
= new Properties();
881 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
884 for (Object pattern
: excludes
.keySet()) {
885 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
886 excludeMatchers
.add(pathMatcher
);
890 // keys are the bundle directories
891 Map
<Path
, A2Origin
> origins
= new HashMap
<>();
892 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
895 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
896 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
897 if (includeMatcher
.matches(file
)) {
898 for (PathMatcher excludeMatcher
: excludeMatchers
) {
899 if (excludeMatcher
.matches(file
)) {
900 logger
.log(TRACE
, "Skipping excluded " + file
);
901 return FileVisitResult
.CONTINUE
;
904 if (file
.getFileName().toString().contains(".source_")) {
905 processEclipseSourceJar(file
, targetCategoryBase
);
906 logger
.log(DEBUG
, () -> "Processed source " + file
);
908 Map
<String
, String
> map
= new HashMap
<>();
909 for (Object key
: commonProps
.keySet())
910 map
.put(key
.toString(), commonProps
.getProperty(key
.toString()));
911 A2Origin origin
= new A2Origin();
912 Path bundleDir
= processBundleJar(file
, targetCategoryBase
, map
, origin
);
913 origins
.put(bundleDir
, origin
);
914 logger
.log(DEBUG
, () -> "Processed " + file
);
916 break includeMatchers
;
919 return FileVisitResult
.CONTINUE
;
923 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)
924 && p
.getFileName().toString().indexOf('.') >= 0 && !p
.getFileName().toString().endsWith(".src"));
925 for (Path bundleDir
: dirs
) {
926 A2Origin origin
= origins
.get(bundleDir
);
927 Objects
.requireNonNull(origin
, "No A2 origin found for " + bundleDir
);
928 createJar(bundleDir
, origin
);
930 } catch (IOException e
) {
931 throw new RuntimeException("Cannot process " + duDir
, e
);
936 /** Process sources in Eclipse format. */
937 void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
939 A2Origin origin
= new A2Origin();
941 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
942 Manifest manifest
= jarIn
.getManifest();
944 String
[] relatedBundle
= manifest
.getMainAttributes().getValue(ECLIPSE_SOURCE_BUNDLE
.toString())
946 String version
= relatedBundle
[1].substring("version=\"".length());
947 version
= version
.substring(0, version
.length() - 1);
948 NameVersion nameVersion
= new NameVersion(relatedBundle
[0], version
);
949 bundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
951 Path sourceDir
= separateSources ? bundleDir
.getParent().resolve(bundleDir
.toString() + ".src")
952 : bundleDir
.resolve("OSGI-OPT/src");
954 Files
.createDirectories(sourceDir
);
956 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
957 if (entry
.isDirectory())
959 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
961 Path target
= sourceDir
.resolve(entry
.getName());
962 Files
.createDirectories(target
.getParent());
963 Files
.copy(jarIn
, target
);
964 logger
.log(TRACE
, () -> "Copied source " + target
);
968 if (separateSources
) {
969 origin
.appendChanges(sourceDir
);
971 origin
.added
.add("source code under OSGI-OPT/src");
972 origin
.appendChanges(bundleDir
);
975 } catch (IOException e
) {
976 throw new IllegalStateException("Cannot process " + file
, e
);
983 /** Normalise a single (that is, non-merged) bundle. */
984 Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
, A2Origin origin
) throws IOException
{
985 // boolean embed = Boolean.parseBoolean(entries.getOrDefault(ARGEO_ORIGIN_EMBED.toString(), "false").toString());
986 boolean doNotModify
= Boolean
987 .parseBoolean(entries
.getOrDefault(ManifestHeader
.ARGEO_DO_NOT_MODIFY
.toString(), "false").toString());
988 NameVersion nameVersion
;
991 boolean isSingleton
= false;
993 Manifest sourceManifest
;
994 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
995 sourceManifest
= jarIn
.getManifest();
996 manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
998 String rawSourceSymbolicName
= manifest
.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME
.toString());
999 if (rawSourceSymbolicName
!= null) {
1000 // make sure there is no directive
1001 String
[] arr
= rawSourceSymbolicName
.split(";");
1002 for (int i
= 1; i
< arr
.length
; i
++) {
1003 if (arr
[i
].trim().equals("singleton:=true"))
1005 logger
.log(DEBUG
, file
.getFileName() + " is a singleton");
1008 // remove problematic entries in MANIFEST
1009 manifest
.getEntries().clear();
1011 String ourSymbolicName
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
1012 String ourVersion
= entries
.get(BUNDLE_VERSION
.toString());
1014 if (ourSymbolicName
!= null && ourVersion
!= null) {
1015 nameVersion
= new NameVersion(ourSymbolicName
, ourVersion
);
1017 nameVersion
= nameVersionFromManifest(manifest
);
1018 if (ourVersion
!= null && !nameVersion
.getVersion().equals(ourVersion
)) {
1020 "Original version is " + nameVersion
.getVersion() + " while new version is " + ourVersion
);
1021 entries
.put(BUNDLE_VERSION
.toString(), ourVersion
);
1023 if (ourSymbolicName
!= null) {
1024 // we always force our symbolic name
1025 nameVersion
.setName(ourSymbolicName
);
1028 bundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
1030 // copy original MANIFEST
1031 if (sourceManifest
!= null) {
1032 Path originalManifest
= bundleDir
.resolve(ARGEO_ORIGIN
).resolve("MANIFEST.MF");
1033 Files
.createDirectories(originalManifest
.getParent());
1034 try (OutputStream out
= Files
.newOutputStream(originalManifest
)) {
1035 sourceManifest
.write(out
);
1037 origin
.moved
.add("original MANIFEST to " + bundleDir
.relativize(originalManifest
));
1040 // force Java 9 module name
1041 entries
.put(ManifestHeader
.AUTOMATIC_MODULE_NAME
.toString(), nameVersion
.getName());
1043 boolean isNative
= false;
1046 if (bundleDir
.startsWith(a2LibBase
)) {
1048 Path libRelativePath
= a2LibBase
.relativize(bundleDir
);
1049 os
= libRelativePath
.getName(0).toString();
1050 arch
= libRelativePath
.getName(1).toString();
1056 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
1057 if (entry
.isDirectory())
1060 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".DSA")
1061 || entry
.getName().endsWith(".SF")) {
1062 origin
.deleted
.add("cryptographic signatures");
1065 if (entry
.getName().endsWith("module-info.class")) { // skip Java 9 module info
1066 origin
.deleted
.add("Java module information (module-info.class)");
1069 if (entry
.getName().startsWith("META-INF/versions/")) { // skip multi-version
1070 origin
.deleted
.add("additional Java versions (META-INF/versions)");
1073 if (entry
.getName().startsWith("META-INF/maven/")) {
1074 origin
.deleted
.add("Maven information (META-INF/maven)");
1077 // skip file system providers as they cause issues with native image
1078 if (entry
.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider")) {
1080 .add("file system providers (META-INF/services/java.nio.file.spi.FileSystemProvider)");
1084 if (entry
.getName().startsWith("OSGI-OPT/src/")) { // skip embedded sources
1085 origin
.deleted
.add("embedded sources");
1088 Path target
= bundleDir
.resolve(entry
.getName());
1089 Files
.createDirectories(target
.getParent());
1090 Files
.copy(jarIn
, target
);
1093 if (isNative
&& (entry
.getName().endsWith(".so") || entry
.getName().endsWith(".dll")
1094 || entry
.getName().endsWith(".jnilib"))) {
1095 Path categoryDir
= bundleDir
.getParent();
1096 boolean copyDll
= false;
1097 Path targetDll
= categoryDir
.resolve(bundleDir
.relativize(target
));
1098 if (nameVersion
.getName().equals("com.sun.jna")) {
1099 if (arch
.equals("x86_64"))
1101 if (os
.equals("macosx"))
1103 if (target
.getParent().getFileName().toString().equals(os
+ "-" + arch
)) {
1106 targetDll
= categoryDir
.resolve(target
.getFileName());
1111 Files
.createDirectories(targetDll
.getParent());
1112 if (Files
.exists(targetDll
))
1113 Files
.delete(targetDll
);
1114 Files
.copy(target
, targetDll
);
1116 Files
.delete(target
);
1117 origin
.deleted
.add(bundleDir
.relativize(target
).toString());
1119 logger
.log(TRACE
, () -> "Copied " + target
);
1125 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
1126 Files
.createDirectories(manifestPath
.getParent());
1128 if (isSingleton
&& entries
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
1129 entries
.put(BUNDLE_SYMBOLICNAME
.toString(),
1130 entries
.get(BUNDLE_SYMBOLICNAME
.toString()) + ";singleton:=true");
1133 // if (embed) {// copy embedded jar
1134 // Files.copy(file, bundleDir.resolve(file.getFileName()));
1135 // entries.put(ManifestHeader.BUNDLE_CLASSPATH.toString(), file.getFileName().toString());
1138 // Final MANIFEST decisions
1139 // We also check the original OSGi metadata and compare with our changes
1140 for (String key
: entries
.keySet()) {
1141 String value
= entries
.get(key
);
1142 String previousValue
= manifest
.getMainAttributes().getValue(key
);
1143 boolean wasDifferent
= previousValue
!= null && !previousValue
.equals(value
);
1144 boolean keepPrevious
= false;
1146 if (SPDX_LICENSE_IDENTIFIER
.toString().equals(key
) && previousValue
!= null)
1147 keepPrevious
= true;
1148 else if (BUNDLE_VERSION
.toString().equals(key
) && wasDifferent
)
1149 if (previousValue
.equals(value
+ ".0")) // typically a Maven first release
1150 keepPrevious
= true;
1153 if (logger
.isLoggable(DEBUG
))
1154 logger
.log(DEBUG
, file
.getFileName() + ": " + key
+ " was NOT modified, value kept is "
1155 + previousValue
+ ", not overriden with " + value
);
1156 value
= previousValue
;
1160 manifest
.getMainAttributes().putValue(key
, value
);
1161 if (wasDifferent
&& !keepPrevious
) {
1162 if (IMPORT_PACKAGE
.toString().equals(key
) || EXPORT_PACKAGE
.toString().equals(key
))
1163 logger
.log(TRACE
, () -> file
.getFileName() + ": " + key
+ " was modified");
1164 else if (BUNDLE_SYMBOLICNAME
.toString().equals(key
) || AUTOMATIC_MODULE_NAME
.toString().equals(key
))
1166 file
.getFileName() + ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
1169 file
.getFileName() + ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
1170 origin
.modified
.add("MANIFEST header " + key
);
1173 // !! hack to remove unresolvable
1174 if (key
.equals("Provide-Capability") || key
.equals("Require-Capability"))
1175 if (nameVersion
.getName().equals("osgi.core") || nameVersion
.getName().equals("osgi.cmpn")) {
1176 manifest
.getMainAttributes().remove(key
);
1177 origin
.deleted
.add("MANIFEST header " + key
);
1181 // de-pollute MANIFEST
1182 for (Iterator
<Map
.Entry
<Object
, Object
>> manifestEntries
= manifest
.getMainAttributes().entrySet()
1183 .iterator(); manifestEntries
.hasNext();) {
1184 Map
.Entry
<Object
, Object
> manifestEntry
= manifestEntries
.next();
1185 switch (manifestEntry
.getKey().toString()) {
1186 case "Archiver-Version":
1189 case "Originally-Created-By":
1191 case "Bnd-LastModified":
1192 manifestEntries
.remove();
1193 origin
.deleted
.add("MANIFEST header " + manifestEntry
.getKey());
1196 if (sourceManifest
!= null && !sourceManifest
.getMainAttributes().containsKey(manifestEntry
.getKey()))
1197 origin
.added
.add("MANIFEST header " + manifestEntry
.getKey());
1201 processLicense(bundleDir
, manifest
);
1203 origin
.modified
.add("MANIFEST (META-INF/MANIFEST.MF)");
1204 // write the MANIFEST
1205 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
1206 manifest
.write(out
);
1211 /** Process SPDX license identifier. */
1212 void processLicense(Path bundleDir
, Manifest manifest
) {
1213 String spdxLicenceId
= manifest
.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER
.toString());
1214 String bundleLicense
= manifest
.getMainAttributes().getValue(BUNDLE_LICENSE
.toString());
1215 if (spdxLicenceId
== null) {
1216 logger
.log(ERROR
, bundleDir
.getFileName() + ": " + SPDX_LICENSE_IDENTIFIER
+ " not available, "
1217 + BUNDLE_LICENSE
+ " is " + bundleLicense
);
1219 // only use the first licensing option
1220 int orIndex
= spdxLicenceId
.indexOf(" OR ");
1222 spdxLicenceId
= spdxLicenceId
.substring(0, orIndex
).trim();
1224 String bundleDirName
= bundleDir
.getFileName().toString();
1225 // force licenses of some well-known components
1226 // even if we say otherwise (typically because from an Eclipse archive)
1227 if (bundleDirName
.startsWith("org.apache."))
1228 spdxLicenceId
= "Apache-2.0";
1229 if (bundleDirName
.startsWith("com.sun.jna."))
1230 spdxLicenceId
= "Apache-2.0";
1231 if (bundleDirName
.startsWith("com.ibm.icu."))
1232 spdxLicenceId
= "ICU";
1233 if (bundleDirName
.startsWith("javax.annotation."))
1234 spdxLicenceId
= "GPL-2.0-only WITH Classpath-exception-2.0";
1235 if (bundleDirName
.startsWith("javax.inject."))
1236 spdxLicenceId
= "Apache-2.0";
1237 if (bundleDirName
.startsWith("org.osgi."))
1238 spdxLicenceId
= "Apache-2.0";
1240 manifest
.getMainAttributes().putValue(SPDX_LICENSE_IDENTIFIER
.toString(), spdxLicenceId
);
1241 if (!licensesUsed
.containsKey(spdxLicenceId
))
1242 licensesUsed
.put(spdxLicenceId
, new TreeSet
<>());
1243 licensesUsed
.get(spdxLicenceId
).add(bundleDir
.getParent().getFileName() + "/" + bundleDir
.getFileName());
1250 /** Recursively deletes a directory. */
1251 static void deleteDirectory(Path path
) throws IOException
{
1252 if (!Files
.exists(path
))
1254 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
1256 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
1259 Files
.delete(directory
);
1264 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1271 /** Extract name/version from a MANIFEST. */
1272 NameVersion
nameVersionFromManifest(Manifest manifest
) {
1273 Attributes attrs
= manifest
.getMainAttributes();
1275 String symbolicName
= attrs
.getValue(ManifestHeader
.BUNDLE_SYMBOLICNAME
.toString());
1276 if (symbolicName
== null)
1278 // make sure there is no directive
1279 symbolicName
= symbolicName
.split(";")[0];
1281 String version
= attrs
.getValue(ManifestHeader
.BUNDLE_VERSION
.toString());
1282 return new NameVersion(symbolicName
, version
);
1285 /** Try to download from an URI. */
1286 Path
tryDownloadArchive(String uri
, Path dir
) throws IOException
{
1288 List
<String
> urlBases
= null;
1289 String uriPrefix
= null;
1290 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
1291 if (uri
.startsWith(uriPref
)) {
1292 if (mirrors
.get(uriPref
).size() > 0) {
1293 urlBases
= mirrors
.get(uriPref
);
1294 uriPrefix
= uriPref
;
1299 if (urlBases
== null)
1301 return downloadArchive(new URL(uri
), dir
);
1302 } catch (FileNotFoundException e
) {
1303 throw new FileNotFoundException("Cannot find " + uri
);
1307 for (String urlBase
: urlBases
) {
1308 String relativePath
= uri
.substring(uriPrefix
.length());
1309 URL url
= new URL(urlBase
+ relativePath
);
1311 return downloadArchive(url
, dir
);
1312 } catch (FileNotFoundException e
) {
1313 logger
.log(WARNING
, "Cannot download " + url
+ ", trying another mirror");
1316 throw new FileNotFoundException("Cannot find " + uri
);
1320 * Effectively download. Synchronised in order to avoid downloading twice in
1323 synchronized Path
downloadArchive(URL url
, Path dir
) throws IOException
{
1324 return download(url
, dir
, (String
) null);
1327 /** Effectively download. */
1328 Path
download(URL url
, Path dir
, String name
) throws IOException
{
1332 // We use also use parent directory in case the archive itself has a fixed name
1333 String
[] segments
= url
.getPath().split("/");
1334 name
= segments
.length
> 1 ? segments
[segments
.length
- 2] + '-' + segments
[segments
.length
- 1]
1335 : segments
[segments
.length
- 1];
1338 dest
= dir
.resolve(name
);
1339 if (Files
.exists(dest
)) {
1340 logger
.log(TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
1343 Files
.createDirectories(dest
.getParent());
1346 try (InputStream in
= url
.openStream()) {
1347 Files
.copy(in
, dest
);
1348 logger
.log(DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
1353 /** Create a JAR file from a directory. */
1354 Path
createJar(Path bundleDir
, A2Origin origin
) throws IOException
{
1355 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
1357 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
1358 manifest
= new Manifest(in
);
1360 // legal requirements
1361 origin
.appendChanges(bundleDir
);
1362 createReadMe(bundleDir
, manifest
);
1365 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
1366 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
1367 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
1368 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
1371 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1372 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1373 return super.visitFile(file
, attrs
);
1374 JarEntry entry
= new JarEntry(
1375 bundleDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1376 jarOut
.putNextEntry(entry
);
1377 Files
.copy(file
, jarOut
);
1378 return super.visitFile(file
, attrs
);
1383 deleteDirectory(bundleDir
);
1385 if (separateSources
)
1386 createSourceJar(bundleDir
, manifest
, null);
1391 /** Package sources separately, in the Eclipse-SourceBundle format. */
1392 void createSourceJar(Path bundleDir
, Manifest manifest
, Properties props
) throws IOException
{
1393 boolean unmodified
= props
!= null;
1394 Path bundleCategoryDir
= bundleDir
.getParent();
1395 Path sourceDir
= bundleCategoryDir
.resolve(bundleDir
.toString() + ".src");
1396 if (!Files
.exists(sourceDir
)) {
1397 logger
.log(WARNING
, sourceDir
+ " does not exist, skipping...");
1401 Path relPath
= a2Base
.relativize(bundleCategoryDir
);
1402 Path srcCategoryDir
= a2SrcBase
.resolve(relPath
);
1403 Path srcJarP
= srcCategoryDir
.resolve(sourceDir
.getFileName() + ".jar");
1404 Files
.createDirectories(srcJarP
.getParent());
1406 String bundleSymbolicName
= manifest
.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1407 // in case there are additional directives
1408 bundleSymbolicName
= bundleSymbolicName
.split(";")[0];
1409 Manifest srcManifest
= new Manifest();
1410 srcManifest
.getMainAttributes().put(MANIFEST_VERSION
, "1.0");
1411 BUNDLE_SYMBOLICNAME
.put(srcManifest
, bundleSymbolicName
+ ".src");
1412 BUNDLE_VERSION
.put(srcManifest
, BUNDLE_VERSION
.get(manifest
));
1413 ECLIPSE_SOURCE_BUNDLE
.put(srcManifest
,
1414 bundleSymbolicName
+ ";version=\"" + BUNDLE_VERSION
.get(manifest
) + "\"");
1417 createReadMe(sourceDir
, unmodified ? props
: manifest
);
1419 try (JarOutputStream srcJarOut
= new JarOutputStream(Files
.newOutputStream(srcJarP
), srcManifest
)) {
1420 // srcJarOut.setLevel(Deflater.BEST_COMPRESSION);
1421 Files
.walkFileTree(sourceDir
, new SimpleFileVisitor
<Path
>() {
1424 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1425 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1426 return super.visitFile(file
, attrs
);
1427 JarEntry entry
= new JarEntry(
1428 sourceDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1429 srcJarOut
.putNextEntry(entry
);
1430 Files
.copy(file
, srcJarOut
);
1431 return super.visitFile(file
, attrs
);
1436 deleteDirectory(sourceDir
);
1440 * Generate a readme clarifying and prominently notifying of the repackaging and
1443 void createReadMe(Path jarDir
, Object mapping
) throws IOException
{
1444 // write repackaged README
1445 try (BufferedWriter writer
= Files
.newBufferedWriter(jarDir
.resolve(README_REPACKAGED
))) {
1446 boolean merged
= ARGEO_ORIGIN_M2_MERGE
.get(mapping
) != null;
1448 writer
.append("This component is a merging of third party components"
1449 + " in order to comply with A2 packaging standards.\n");
1451 writer
.append("This component is a repackaging of a third party component"
1452 + " in order to comply with A2 packaging standards.\n");
1455 String spdxLicenseId
= SPDX_LICENSE_IDENTIFIER
.get(mapping
);
1456 if (spdxLicenseId
== null)
1457 throw new IllegalStateException("An SPDX license id must have beend defined at this stage.");
1458 writer
.append("\nIt is redistributed under the following license:\n\n");
1459 writer
.append("SPDX-Identifier: " + spdxLicenseId
+ "\n\n");
1461 if (!spdxLicenseId
.startsWith("LicenseRef")) {// standard
1462 int withIndex
= spdxLicenseId
.indexOf(" WITH ");
1463 if (withIndex
>= 0) {
1464 String simpleId
= spdxLicenseId
.substring(0, withIndex
).trim();
1465 String exception
= spdxLicenseId
.substring(withIndex
+ " WITH ".length());
1466 writer
.append("which are available here: https://spdx.org/licenses/" + simpleId
1467 + "\nand here: https://spdx.org/licenses/" + exception
+ "\n");
1469 writer
.append("which is available here: https://spdx.org/licenses/" + spdxLicenseId
+ "\n");
1472 String url
= BUNDLE_LICENSE
.get(mapping
);
1474 writer
.write("which is available here: " + url
+ "\n");
1476 logger
.log(ERROR
, "No licence URL for " + jarDir
);
1481 String originDesc
= ARGEO_ORIGIN_URI
.get(mapping
);
1482 if (originDesc
!= null)
1483 writer
.append("\nThe original component comes from " + originDesc
+ ".\n");
1485 String m2Repo
= ARGEO_ORIGIN_M2_REPO
.get(mapping
);
1486 originDesc
= ARGEO_ORIGIN_M2
.get(mapping
);
1487 if (originDesc
!= null)
1488 writer
.append("\nThe original component has M2 coordinates:\n" + originDesc
.replace(',', '\n')
1489 + "\n" + (m2Repo
!= null ?
"\nin M2 repository " + m2Repo
+ "\n" : ""));
1491 logger
.log(ERROR
, "Cannot find origin information in " + jarDir
);
1493 String originSources
= ARGEO_ORIGIN_SOURCES_URI
.get(mapping
);
1494 if (originSources
!= null)
1495 writer
.append("\nThe original sources come from " + originSources
+ ".\n");
1497 if (Files
.exists(jarDir
.resolve(CHANGES
)))
1498 writer
.append("\nA detailed list of changes is available under " + CHANGES
+ ".\n");
1500 if (!jarDir
.getFileName().toString().endsWith(".src")) {// binary archive
1501 if (separateSources
)
1502 writer
.append("Corresponding sources are available in the related archive named "
1503 + jarDir
.toString() + ".src.jar.\n");
1505 writer
.append("Corresponding sources are available under OSGI-OPT/src.\n");
1511 * Gathers modifications performed on the original binaries and sources,
1512 * especially in order to comply with their license requirements.
1519 Set
<String
> modified
= new TreeSet
<>();
1520 Set
<String
> deleted
= new TreeSet
<>();
1521 Set
<String
> added
= new TreeSet
<>();
1522 Set
<String
> moved
= new TreeSet
<>();
1524 /** Append changes to the A2-ORIGIN/changes file. */
1525 void appendChanges(Path baseDirectory
) throws IOException
{
1526 if (modified
.isEmpty() && deleted
.isEmpty() && added
.isEmpty() && moved
.isEmpty())
1527 return; // no changes
1528 Path changesFile
= baseDirectory
.resolve(CHANGES
);
1529 Files
.createDirectories(changesFile
.getParent());
1530 try (BufferedWriter writer
= Files
.newBufferedWriter(changesFile
, APPEND
, CREATE
)) {
1531 for (String msg
: added
)
1532 writer
.write("- Added " + msg
+ ".\n");
1533 for (String msg
: modified
)
1534 writer
.write("- Modified " + msg
+ ".\n");
1535 for (String msg
: moved
)
1536 writer
.write("- Moved " + msg
+ ".\n");
1537 for (String msg
: deleted
)
1538 writer
.write("- Deleted " + msg
+ ".\n");
1544 /** Simple representation of an M2 artifact. */
1545 class M2Artifact
extends CategoryNameVersion
{
1546 private String classifier
;
1548 M2Artifact(String m2coordinates
) {
1549 this(m2coordinates
, null);
1552 M2Artifact(String m2coordinates
, String classifier
) {
1553 String
[] parts
= m2coordinates
.split(":");
1554 setCategory(parts
[0]);
1556 if (parts
.length
> 2) {
1557 setVersion(parts
[2]);
1559 this.classifier
= classifier
;
1562 String
getGroupId() {
1563 return super.getCategory();
1566 String
getArtifactId() {
1567 return super.getName();
1570 String
toM2Coordinates() {
1571 return getCategory() + ":" + getName() + (getVersion() != null ?
":" + getVersion() : "");
1574 String
getClassifier() {
1575 return classifier
!= null ? classifier
: "";
1578 String
getExtension() {
1583 /** Utilities around Maven (conventions based). */
1584 class M2ConventionsUtils
{
1585 final static String MAVEN_CENTRAL_BASE_URL
= "https://repo1.maven.org/maven2/";
1587 /** The file name of this artifact when stored */
1588 static String
artifactFileName(M2Artifact artifact
) {
1589 return artifact
.getArtifactId() + '-' + artifact
.getVersion()
1590 + (artifact
.getClassifier().equals("") ?
"" : '-' + artifact
.getClassifier()) + '.'
1591 + artifact
.getExtension();
1594 /** Absolute path to the file */
1595 static String
artifactPath(String artifactBasePath
, M2Artifact artifact
) {
1596 return artifactParentPath(artifactBasePath
, artifact
) + '/' + artifactFileName(artifact
);
1599 /** Absolute path to the file */
1600 static String
artifactUrl(String repoUrl
, M2Artifact artifact
) {
1601 if (repoUrl
.endsWith("/"))
1602 return repoUrl
+ artifactPath("/", artifact
).substring(1);
1604 return repoUrl
+ artifactPath("/", artifact
);
1607 /** Absolute path to the file */
1608 static URL
mavenRepoUrl(String repoBase
, M2Artifact artifact
) {
1609 String url
= artifactUrl(repoBase
== null ? MAVEN_CENTRAL_BASE_URL
: repoBase
, artifact
);
1611 return new URL(url
);
1612 } catch (MalformedURLException e
) {
1613 // it should not happen
1614 throw new IllegalStateException(e
);
1618 /** Absolute path to the directories where the files will be stored */
1619 static String
artifactParentPath(String artifactBasePath
, M2Artifact artifact
) {
1620 return artifactBasePath
+ (artifactBasePath
.endsWith("/") || artifactBasePath
.equals("") ?
"" : "/")
1621 + artifactParentPath(artifact
);
1624 /** Relative path to the directories where the files will be stored */
1625 static String
artifactParentPath(M2Artifact artifact
) {
1626 return artifact
.getGroupId().replace('.', '/') + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion();
1630 private M2ConventionsUtils() {
1634 /** Combination of a category, a name and a version. */
1635 class CategoryNameVersion
extends NameVersion
{
1636 private String category
;
1638 CategoryNameVersion() {
1641 CategoryNameVersion(String category
, String name
, String version
) {
1642 super(name
, version
);
1643 this.category
= category
;
1646 CategoryNameVersion(String category
, NameVersion nameVersion
) {
1648 this.category
= category
;
1651 String
getCategory() {
1655 void setCategory(String category
) {
1656 this.category
= category
;
1660 public String
toString() {
1661 return category
+ ":" + super.toString();
1666 /** Combination of a name and a version. */
1667 class NameVersion
implements Comparable
<NameVersion
> {
1668 private String name
;
1669 private String version
;
1674 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1675 NameVersion(String nameVersion
) {
1676 int index
= nameVersion
.indexOf(";version=");
1678 setName(nameVersion
);
1681 setName(nameVersion
.substring(0, index
));
1682 setVersion(nameVersion
.substring(index
+ ";version=".length()));
1686 NameVersion(String name
, String version
) {
1688 this.version
= version
;
1691 NameVersion(NameVersion nameVersion
) {
1692 this.name
= nameVersion
.getName();
1693 this.version
= nameVersion
.getVersion();
1700 void setName(String name
) {
1704 String
getVersion() {
1708 void setVersion(String version
) {
1709 this.version
= version
;
1712 String
getBranch() {
1713 String
[] parts
= getVersion().split("\\.");
1714 if (parts
.length
< 2)
1715 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1716 return parts
[0] + "." + parts
[1];
1720 public boolean equals(Object obj
) {
1721 if (obj
instanceof NameVersion
) {
1722 NameVersion nameVersion
= (NameVersion
) obj
;
1723 return name
.equals(nameVersion
.getName()) && version
.equals(nameVersion
.getVersion());
1729 public int hashCode() {
1730 return name
.hashCode();
1734 public String
toString() {
1735 return name
+ ":" + version
;
1738 public int compareTo(NameVersion o
) {
1739 if (o
.getName().equals(name
))
1740 return version
.compareTo(o
.getVersion());
1742 return name
.compareTo(o
.getName());