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 if (!props
.containsKey(ARGEO_ORIGIN_SOURCES_URI
.toString()))
756 ARGEO_ORIGIN_SOURCES_URI
.put(props
, sourcesUrl
.toString());
757 processM2SourceJar(sourcesDownloaded
, targetBundleDir
, merging ? artifact
: null, unmodified
);
758 logger
.log(TRACE
, () -> "Processed source " + sourcesDownloaded
);
759 } catch (Exception e
) {
760 logger
.log(ERROR
, () -> "Cannot download source for " + artifact
);
765 /** Integrate sources from a downloaded jar file. */
766 void processM2SourceJar(Path file
, Path bundleDir
, M2Artifact mergingFrom
, boolean unmodified
) throws IOException
{
767 A2Origin origin
= new A2Origin();
768 Path sourceDir
= separateSources
|| unmodified ? bundleDir
.getParent().resolve(bundleDir
.toString() + ".src")
769 : bundleDir
.resolve("OSGI-OPT/src");
770 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
772 String mergingMsg
= "";
773 if (mergingFrom
!= null)
774 mergingMsg
= " of " + mergingFrom
;
776 Files
.createDirectories(sourceDir
);
778 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
779 String relPath
= entry
.getName();
780 if (entry
.isDirectory())
782 if (entry
.getName().equals("META-INF/MANIFEST.MF")) {// skip META-INF entries
783 origin
.deleted
.add("MANIFEST.MF from the sources" + mergingMsg
);
787 if (entry
.getName().startsWith("module-info.java")) {// skip Java module information
788 origin
.deleted
.add("Java module information from the sources (module-info.java)" + mergingMsg
);
791 if (entry
.getName().startsWith("/")) { // absolute paths
792 int metaInfIndex
= entry
.getName().indexOf("META-INF");
793 if (metaInfIndex
>= 0) {
794 relPath
= entry
.getName().substring(metaInfIndex
);
795 origin
.moved
.add(" to " + relPath
+ " entry with absolute path " + entry
.getName());
797 logger
.log(WARNING
, entry
.getName() + " has an absolute path");
798 origin
.deleted
.add(entry
.getName() + " from the sources" + mergingMsg
);
803 Path target
= sourceDir
.resolve(relPath
);
804 Files
.createDirectories(target
.getParent());
805 if (!Files
.exists(target
)) {
806 Files
.copy(jarIn
, target
);
807 logger
.log(TRACE
, () -> "Copied source " + target
);
809 logger
.log(TRACE
, () -> target
+ " already exists, skipping...");
814 if (separateSources
|| unmodified
) {
815 origin
.appendChanges(sourceDir
);
817 origin
.added
.add("source code under OSGI-OPT/src");
818 origin
.appendChanges(bundleDir
);
822 /** Download a Maven artifact. */
823 Path
downloadMaven(Properties props
, M2Artifact artifact
) throws IOException
{
824 String repoStr
= props
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
825 ? props
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
827 String alternateUri
= props
.getProperty(ARGEO_ORIGIN_URI
.toString());
828 URL url
= alternateUri
!= null ?
new URL(alternateUri
) : M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
829 return downloadMaven(url
, artifact
);
832 /** Download a Maven artifact. */
833 Path
downloadMaven(URL url
, M2Artifact artifact
) throws IOException
{
834 return download(url
, mavenBase
, M2ConventionsUtils
.artifactPath("", artifact
));
840 /** Process an archive in Eclipse format. */
841 void processEclipseArchive(Path duDir
) {
843 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
844 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
845 Files
.createDirectories(targetCategoryBase
);
846 // first delete all directories from previous builds
847 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)))
848 deleteDirectory(dir
);
850 Files
.createDirectories(originBase
);
852 Path commonBnd
= duDir
.resolve(COMMON_BND
);
853 Properties commonProps
= new Properties();
854 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
855 commonProps
.load(in
);
857 String url
= commonProps
.getProperty(ARGEO_ORIGIN_URI
.toString());
859 url
= uris
.getProperty(duDir
.getFileName().toString());
861 throw new IllegalStateException("No url available for " + duDir
);
862 commonProps
.put(ARGEO_ORIGIN_URI
.toString(), url
);
864 Path downloaded
= tryDownloadArchive(url
, originBase
);
866 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
869 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
870 Properties includes
= new Properties();
871 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
874 for (Object pattern
: includes
.keySet()) {
875 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
876 includeMatchers
.add(pathMatcher
);
879 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
880 Path excludeFile
= duDir
.resolve("excludes.properties");
881 if (Files
.exists(excludeFile
)) {
882 Properties excludes
= new Properties();
883 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
886 for (Object pattern
: excludes
.keySet()) {
887 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
888 excludeMatchers
.add(pathMatcher
);
892 // keys are the bundle directories
893 Map
<Path
, A2Origin
> origins
= new HashMap
<>();
894 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
897 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
898 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
899 if (includeMatcher
.matches(file
)) {
900 for (PathMatcher excludeMatcher
: excludeMatchers
) {
901 if (excludeMatcher
.matches(file
)) {
902 logger
.log(TRACE
, "Skipping excluded " + file
);
903 return FileVisitResult
.CONTINUE
;
906 if (file
.getFileName().toString().contains(".source_")) {
907 processEclipseSourceJar(file
, targetCategoryBase
);
908 logger
.log(DEBUG
, () -> "Processed source " + file
);
910 Map
<String
, String
> map
= new HashMap
<>();
911 for (Object key
: commonProps
.keySet())
912 map
.put(key
.toString(), commonProps
.getProperty(key
.toString()));
913 A2Origin origin
= new A2Origin();
914 Path bundleDir
= processBundleJar(file
, targetCategoryBase
, map
, origin
);
915 origins
.put(bundleDir
, origin
);
916 logger
.log(DEBUG
, () -> "Processed " + file
);
918 break includeMatchers
;
921 return FileVisitResult
.CONTINUE
;
925 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)
926 && p
.getFileName().toString().indexOf('.') >= 0 && !p
.getFileName().toString().endsWith(".src"));
927 for (Path bundleDir
: dirs
) {
928 A2Origin origin
= origins
.get(bundleDir
);
929 Objects
.requireNonNull(origin
, "No A2 origin found for " + bundleDir
);
930 createJar(bundleDir
, origin
);
932 } catch (IOException e
) {
933 throw new RuntimeException("Cannot process " + duDir
, e
);
938 /** Process sources in Eclipse format. */
939 void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
941 A2Origin origin
= new A2Origin();
943 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
944 Manifest manifest
= jarIn
.getManifest();
946 String
[] relatedBundle
= manifest
.getMainAttributes().getValue(ECLIPSE_SOURCE_BUNDLE
.toString())
948 String version
= relatedBundle
[1].substring("version=\"".length());
949 version
= version
.substring(0, version
.length() - 1);
950 NameVersion nameVersion
= new NameVersion(relatedBundle
[0], version
);
951 bundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
953 Path sourceDir
= separateSources ? bundleDir
.getParent().resolve(bundleDir
.toString() + ".src")
954 : bundleDir
.resolve("OSGI-OPT/src");
956 Files
.createDirectories(sourceDir
);
958 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
959 if (entry
.isDirectory())
961 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
963 Path target
= sourceDir
.resolve(entry
.getName());
964 Files
.createDirectories(target
.getParent());
965 Files
.copy(jarIn
, target
);
966 logger
.log(TRACE
, () -> "Copied source " + target
);
970 if (separateSources
) {
971 origin
.appendChanges(sourceDir
);
973 origin
.added
.add("source code under OSGI-OPT/src");
974 origin
.appendChanges(bundleDir
);
977 } catch (IOException e
) {
978 throw new IllegalStateException("Cannot process " + file
, e
);
985 /** Normalise a single (that is, non-merged) bundle. */
986 Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
, A2Origin origin
) throws IOException
{
987 // boolean embed = Boolean.parseBoolean(entries.getOrDefault(ARGEO_ORIGIN_EMBED.toString(), "false").toString());
988 boolean doNotModify
= Boolean
989 .parseBoolean(entries
.getOrDefault(ManifestHeader
.ARGEO_DO_NOT_MODIFY
.toString(), "false").toString());
990 NameVersion nameVersion
;
993 boolean isSingleton
= false;
995 Manifest sourceManifest
;
996 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
997 sourceManifest
= jarIn
.getManifest();
998 manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
1000 String rawSourceSymbolicName
= manifest
.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME
.toString());
1001 if (rawSourceSymbolicName
!= null) {
1002 // make sure there is no directive
1003 String
[] arr
= rawSourceSymbolicName
.split(";");
1004 for (int i
= 1; i
< arr
.length
; i
++) {
1005 if (arr
[i
].trim().equals("singleton:=true"))
1007 logger
.log(DEBUG
, file
.getFileName() + " is a singleton");
1010 // remove problematic entries in MANIFEST
1011 manifest
.getEntries().clear();
1013 String ourSymbolicName
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
1014 String ourVersion
= entries
.get(BUNDLE_VERSION
.toString());
1016 if (ourSymbolicName
!= null && ourVersion
!= null) {
1017 nameVersion
= new NameVersion(ourSymbolicName
, ourVersion
);
1019 nameVersion
= nameVersionFromManifest(manifest
);
1020 if (ourVersion
!= null && !nameVersion
.getVersion().equals(ourVersion
)) {
1022 "Original version is " + nameVersion
.getVersion() + " while new version is " + ourVersion
);
1023 entries
.put(BUNDLE_VERSION
.toString(), ourVersion
);
1025 if (ourSymbolicName
!= null) {
1026 // we always force our symbolic name
1027 nameVersion
.setName(ourSymbolicName
);
1030 bundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
1032 // copy original MANIFEST
1033 if (sourceManifest
!= null) {
1034 Path originalManifest
= bundleDir
.resolve(ARGEO_ORIGIN
).resolve("MANIFEST.MF");
1035 Files
.createDirectories(originalManifest
.getParent());
1036 try (OutputStream out
= Files
.newOutputStream(originalManifest
)) {
1037 sourceManifest
.write(out
);
1039 origin
.moved
.add("original MANIFEST to " + bundleDir
.relativize(originalManifest
));
1042 // force Java 9 module name
1043 entries
.put(ManifestHeader
.AUTOMATIC_MODULE_NAME
.toString(), nameVersion
.getName());
1045 boolean isNative
= false;
1048 if (bundleDir
.startsWith(a2LibBase
)) {
1050 Path libRelativePath
= a2LibBase
.relativize(bundleDir
);
1051 os
= libRelativePath
.getName(0).toString();
1052 arch
= libRelativePath
.getName(1).toString();
1058 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
1059 if (entry
.isDirectory())
1062 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".DSA")
1063 || entry
.getName().endsWith(".SF")) {
1064 origin
.deleted
.add("cryptographic signatures");
1067 if (entry
.getName().endsWith("module-info.class")) { // skip Java 9 module info
1068 origin
.deleted
.add("Java module information (module-info.class)");
1071 if (entry
.getName().startsWith("META-INF/versions/")) { // skip multi-version
1072 origin
.deleted
.add("additional Java versions (META-INF/versions)");
1075 if (entry
.getName().startsWith("META-INF/maven/")) {
1076 origin
.deleted
.add("Maven information (META-INF/maven)");
1079 // skip file system providers as they cause issues with native image
1080 if (entry
.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider")) {
1082 .add("file system providers (META-INF/services/java.nio.file.spi.FileSystemProvider)");
1086 if (entry
.getName().startsWith("OSGI-OPT/src/")) { // skip embedded sources
1087 origin
.deleted
.add("embedded sources");
1090 Path target
= bundleDir
.resolve(entry
.getName());
1091 Files
.createDirectories(target
.getParent());
1092 Files
.copy(jarIn
, target
);
1095 if (isNative
&& (entry
.getName().endsWith(".so") || entry
.getName().endsWith(".dll")
1096 || entry
.getName().endsWith(".jnilib"))) {
1097 Path categoryDir
= bundleDir
.getParent();
1098 boolean copyDll
= false;
1099 Path targetDll
= categoryDir
.resolve(bundleDir
.relativize(target
));
1100 if (nameVersion
.getName().equals("com.sun.jna")) {
1101 if (arch
.equals("x86_64"))
1103 if (os
.equals("macosx"))
1105 if (target
.getParent().getFileName().toString().equals(os
+ "-" + arch
)) {
1108 targetDll
= categoryDir
.resolve(target
.getFileName());
1113 Files
.createDirectories(targetDll
.getParent());
1114 if (Files
.exists(targetDll
))
1115 Files
.delete(targetDll
);
1116 Files
.copy(target
, targetDll
);
1118 Files
.delete(target
);
1119 origin
.deleted
.add(bundleDir
.relativize(target
).toString());
1121 logger
.log(TRACE
, () -> "Copied " + target
);
1127 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
1128 Files
.createDirectories(manifestPath
.getParent());
1130 if (isSingleton
&& entries
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
1131 entries
.put(BUNDLE_SYMBOLICNAME
.toString(),
1132 entries
.get(BUNDLE_SYMBOLICNAME
.toString()) + ";singleton:=true");
1135 // if (embed) {// copy embedded jar
1136 // Files.copy(file, bundleDir.resolve(file.getFileName()));
1137 // entries.put(ManifestHeader.BUNDLE_CLASSPATH.toString(), file.getFileName().toString());
1140 // Final MANIFEST decisions
1141 // We also check the original OSGi metadata and compare with our changes
1142 for (String key
: entries
.keySet()) {
1143 String value
= entries
.get(key
);
1144 String previousValue
= manifest
.getMainAttributes().getValue(key
);
1145 boolean wasDifferent
= previousValue
!= null && !previousValue
.equals(value
);
1146 boolean keepPrevious
= false;
1148 if (SPDX_LICENSE_IDENTIFIER
.toString().equals(key
) && previousValue
!= null)
1149 keepPrevious
= true;
1150 else if (BUNDLE_VERSION
.toString().equals(key
) && wasDifferent
)
1151 if (previousValue
.equals(value
+ ".0")) // typically a Maven first release
1152 keepPrevious
= true;
1155 if (logger
.isLoggable(DEBUG
))
1156 logger
.log(DEBUG
, file
.getFileName() + ": " + key
+ " was NOT modified, value kept is "
1157 + previousValue
+ ", not overriden with " + value
);
1158 value
= previousValue
;
1162 manifest
.getMainAttributes().putValue(key
, value
);
1163 if (wasDifferent
&& !keepPrevious
) {
1164 if (IMPORT_PACKAGE
.toString().equals(key
) || EXPORT_PACKAGE
.toString().equals(key
))
1165 logger
.log(TRACE
, () -> file
.getFileName() + ": " + key
+ " was modified");
1166 else if (BUNDLE_SYMBOLICNAME
.toString().equals(key
) || AUTOMATIC_MODULE_NAME
.toString().equals(key
))
1168 file
.getFileName() + ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
1171 file
.getFileName() + ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
1172 origin
.modified
.add("MANIFEST header " + key
);
1175 // !! hack to remove unresolvable
1176 if (key
.equals("Provide-Capability") || key
.equals("Require-Capability"))
1177 if (nameVersion
.getName().equals("osgi.core") || nameVersion
.getName().equals("osgi.cmpn")) {
1178 manifest
.getMainAttributes().remove(key
);
1179 origin
.deleted
.add("MANIFEST header " + key
);
1183 // de-pollute MANIFEST
1184 for (Iterator
<Map
.Entry
<Object
, Object
>> manifestEntries
= manifest
.getMainAttributes().entrySet()
1185 .iterator(); manifestEntries
.hasNext();) {
1186 Map
.Entry
<Object
, Object
> manifestEntry
= manifestEntries
.next();
1187 switch (manifestEntry
.getKey().toString()) {
1188 case "Archiver-Version":
1191 case "Originally-Created-By":
1193 case "Bnd-LastModified":
1194 manifestEntries
.remove();
1195 origin
.deleted
.add("MANIFEST header " + manifestEntry
.getKey());
1198 if (sourceManifest
!= null && !sourceManifest
.getMainAttributes().containsKey(manifestEntry
.getKey()))
1199 origin
.added
.add("MANIFEST header " + manifestEntry
.getKey());
1203 processLicense(bundleDir
, manifest
);
1205 origin
.modified
.add("MANIFEST (META-INF/MANIFEST.MF)");
1206 // write the MANIFEST
1207 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
1208 manifest
.write(out
);
1213 /** Process SPDX license identifier. */
1214 void processLicense(Path bundleDir
, Manifest manifest
) {
1215 String spdxLicenceId
= manifest
.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER
.toString());
1216 String bundleLicense
= manifest
.getMainAttributes().getValue(BUNDLE_LICENSE
.toString());
1217 if (spdxLicenceId
== null) {
1218 logger
.log(ERROR
, bundleDir
.getFileName() + ": " + SPDX_LICENSE_IDENTIFIER
+ " not available, "
1219 + BUNDLE_LICENSE
+ " is " + bundleLicense
);
1221 // only use the first licensing option
1222 int orIndex
= spdxLicenceId
.indexOf(" OR ");
1224 spdxLicenceId
= spdxLicenceId
.substring(0, orIndex
).trim();
1226 String bundleDirName
= bundleDir
.getFileName().toString();
1227 // force licenses of some well-known components
1228 // even if we say otherwise (typically because from an Eclipse archive)
1229 if (bundleDirName
.startsWith("org.apache."))
1230 spdxLicenceId
= "Apache-2.0";
1231 if (bundleDirName
.startsWith("com.sun.jna."))
1232 spdxLicenceId
= "Apache-2.0";
1233 if (bundleDirName
.startsWith("com.ibm.icu."))
1234 spdxLicenceId
= "ICU";
1235 if (bundleDirName
.startsWith("javax.annotation."))
1236 spdxLicenceId
= "GPL-2.0-only WITH Classpath-exception-2.0";
1237 if (bundleDirName
.startsWith("javax.inject."))
1238 spdxLicenceId
= "Apache-2.0";
1239 if (bundleDirName
.startsWith("org.osgi."))
1240 spdxLicenceId
= "Apache-2.0";
1242 manifest
.getMainAttributes().putValue(SPDX_LICENSE_IDENTIFIER
.toString(), spdxLicenceId
);
1243 if (!licensesUsed
.containsKey(spdxLicenceId
))
1244 licensesUsed
.put(spdxLicenceId
, new TreeSet
<>());
1245 licensesUsed
.get(spdxLicenceId
).add(bundleDir
.getParent().getFileName() + "/" + bundleDir
.getFileName());
1252 /** Recursively deletes a directory. */
1253 static void deleteDirectory(Path path
) throws IOException
{
1254 if (!Files
.exists(path
))
1256 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
1258 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
1261 Files
.delete(directory
);
1266 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1273 /** Extract name/version from a MANIFEST. */
1274 NameVersion
nameVersionFromManifest(Manifest manifest
) {
1275 Attributes attrs
= manifest
.getMainAttributes();
1277 String symbolicName
= attrs
.getValue(ManifestHeader
.BUNDLE_SYMBOLICNAME
.toString());
1278 if (symbolicName
== null)
1280 // make sure there is no directive
1281 symbolicName
= symbolicName
.split(";")[0];
1283 String version
= attrs
.getValue(ManifestHeader
.BUNDLE_VERSION
.toString());
1284 return new NameVersion(symbolicName
, version
);
1287 /** Try to download from an URI. */
1288 Path
tryDownloadArchive(String uri
, Path dir
) throws IOException
{
1290 List
<String
> urlBases
= null;
1291 String uriPrefix
= null;
1292 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
1293 if (uri
.startsWith(uriPref
)) {
1294 if (mirrors
.get(uriPref
).size() > 0) {
1295 urlBases
= mirrors
.get(uriPref
);
1296 uriPrefix
= uriPref
;
1301 if (urlBases
== null)
1303 return downloadArchive(new URL(uri
), dir
);
1304 } catch (FileNotFoundException e
) {
1305 throw new FileNotFoundException("Cannot find " + uri
);
1309 for (String urlBase
: urlBases
) {
1310 String relativePath
= uri
.substring(uriPrefix
.length());
1311 URL url
= new URL(urlBase
+ relativePath
);
1313 return downloadArchive(url
, dir
);
1314 } catch (FileNotFoundException e
) {
1315 logger
.log(WARNING
, "Cannot download " + url
+ ", trying another mirror");
1318 throw new FileNotFoundException("Cannot find " + uri
);
1322 * Effectively download. Synchronised in order to avoid downloading twice in
1325 synchronized Path
downloadArchive(URL url
, Path dir
) throws IOException
{
1326 return download(url
, dir
, (String
) null);
1329 /** Effectively download. */
1330 Path
download(URL url
, Path dir
, String name
) throws IOException
{
1334 // We use also use parent directory in case the archive itself has a fixed name
1335 String
[] segments
= url
.getPath().split("/");
1336 name
= segments
.length
> 1 ? segments
[segments
.length
- 2] + '-' + segments
[segments
.length
- 1]
1337 : segments
[segments
.length
- 1];
1340 dest
= dir
.resolve(name
);
1341 if (Files
.exists(dest
)) {
1342 logger
.log(TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
1345 Files
.createDirectories(dest
.getParent());
1348 try (InputStream in
= url
.openStream()) {
1349 Files
.copy(in
, dest
);
1350 logger
.log(DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
1355 /** Create a JAR file from a directory. */
1356 Path
createJar(Path bundleDir
, A2Origin origin
) throws IOException
{
1357 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
1359 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
1360 manifest
= new Manifest(in
);
1362 // legal requirements
1363 origin
.appendChanges(bundleDir
);
1364 createReadMe(bundleDir
, manifest
);
1367 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
1368 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
1369 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
1370 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
1373 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1374 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1375 return super.visitFile(file
, attrs
);
1376 JarEntry entry
= new JarEntry(
1377 bundleDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1378 jarOut
.putNextEntry(entry
);
1379 Files
.copy(file
, jarOut
);
1380 return super.visitFile(file
, attrs
);
1385 deleteDirectory(bundleDir
);
1387 if (separateSources
)
1388 createSourceJar(bundleDir
, manifest
, null);
1393 /** Package sources separately, in the Eclipse-SourceBundle format. */
1394 void createSourceJar(Path bundleDir
, Manifest manifest
, Properties props
) throws IOException
{
1395 boolean unmodified
= props
!= null;
1396 Path bundleCategoryDir
= bundleDir
.getParent();
1397 Path sourceDir
= bundleCategoryDir
.resolve(bundleDir
.toString() + ".src");
1398 if (!Files
.exists(sourceDir
)) {
1399 logger
.log(WARNING
, sourceDir
+ " does not exist, skipping...");
1403 Path relPath
= a2Base
.relativize(bundleCategoryDir
);
1404 Path srcCategoryDir
= a2SrcBase
.resolve(relPath
);
1405 Path srcJarP
= srcCategoryDir
.resolve(sourceDir
.getFileName() + ".jar");
1406 Files
.createDirectories(srcJarP
.getParent());
1408 String bundleSymbolicName
= manifest
.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1409 // in case there are additional directives
1410 bundleSymbolicName
= bundleSymbolicName
.split(";")[0];
1411 Manifest srcManifest
= new Manifest();
1412 srcManifest
.getMainAttributes().put(MANIFEST_VERSION
, "1.0");
1413 BUNDLE_SYMBOLICNAME
.put(srcManifest
, bundleSymbolicName
+ ".src");
1414 BUNDLE_VERSION
.put(srcManifest
, BUNDLE_VERSION
.get(manifest
));
1415 ECLIPSE_SOURCE_BUNDLE
.put(srcManifest
,
1416 bundleSymbolicName
+ ";version=\"" + BUNDLE_VERSION
.get(manifest
) + "\"");
1419 createReadMe(sourceDir
, unmodified ? props
: manifest
);
1421 try (JarOutputStream srcJarOut
= new JarOutputStream(Files
.newOutputStream(srcJarP
), srcManifest
)) {
1422 // srcJarOut.setLevel(Deflater.BEST_COMPRESSION);
1423 Files
.walkFileTree(sourceDir
, new SimpleFileVisitor
<Path
>() {
1426 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1427 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1428 return super.visitFile(file
, attrs
);
1429 JarEntry entry
= new JarEntry(
1430 sourceDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1431 srcJarOut
.putNextEntry(entry
);
1432 Files
.copy(file
, srcJarOut
);
1433 return super.visitFile(file
, attrs
);
1438 deleteDirectory(sourceDir
);
1442 * Generate a readme clarifying and prominently notifying of the repackaging and
1445 void createReadMe(Path jarDir
, Object mapping
) throws IOException
{
1446 // write repackaged README
1447 try (BufferedWriter writer
= Files
.newBufferedWriter(jarDir
.resolve(README_REPACKAGED
))) {
1448 boolean merged
= ARGEO_ORIGIN_M2_MERGE
.get(mapping
) != null;
1450 writer
.append("This component is a merging of third party components"
1451 + " in order to comply with A2 packaging standards.\n");
1453 writer
.append("This component is a repackaging of a third party component"
1454 + " in order to comply with A2 packaging standards.\n");
1457 String spdxLicenseId
= SPDX_LICENSE_IDENTIFIER
.get(mapping
);
1458 if (spdxLicenseId
== null)
1459 throw new IllegalStateException("An SPDX license id must have beend defined at this stage.");
1460 writer
.append("\nIt is redistributed under the following license:\n\n");
1461 writer
.append("SPDX-Identifier: " + spdxLicenseId
+ "\n\n");
1463 if (!spdxLicenseId
.startsWith("LicenseRef")) {// standard
1464 int withIndex
= spdxLicenseId
.indexOf(" WITH ");
1465 if (withIndex
>= 0) {
1466 String simpleId
= spdxLicenseId
.substring(0, withIndex
).trim();
1467 String exception
= spdxLicenseId
.substring(withIndex
+ " WITH ".length());
1468 writer
.append("which are available here: https://spdx.org/licenses/" + simpleId
1469 + "\nand here: https://spdx.org/licenses/" + exception
+ "\n");
1471 writer
.append("which is available here: https://spdx.org/licenses/" + spdxLicenseId
+ "\n");
1474 String url
= BUNDLE_LICENSE
.get(mapping
);
1476 writer
.write("which is available here: " + url
+ "\n");
1478 logger
.log(ERROR
, "No licence URL for " + jarDir
);
1483 String originDesc
= ARGEO_ORIGIN_URI
.get(mapping
);
1484 if (originDesc
!= null)
1485 writer
.append("\nThe original component comes from " + originDesc
+ ".\n");
1487 String m2Repo
= ARGEO_ORIGIN_M2_REPO
.get(mapping
);
1488 originDesc
= ARGEO_ORIGIN_M2
.get(mapping
);
1489 if (originDesc
!= null)
1490 writer
.append("\nThe original component has M2 coordinates:\n" + originDesc
.replace(',', '\n')
1491 + "\n" + (m2Repo
!= null ?
"\nin M2 repository " + m2Repo
+ "\n" : ""));
1493 logger
.log(ERROR
, "Cannot find origin information in " + jarDir
);
1495 String originSources
= ARGEO_ORIGIN_SOURCES_URI
.get(mapping
);
1496 if (originSources
!= null)
1497 writer
.append("\nThe original sources come from " + originSources
+ ".\n");
1499 if (Files
.exists(jarDir
.resolve(CHANGES
)))
1500 writer
.append("\nA detailed list of changes is available under " + CHANGES
+ ".\n");
1502 if (!jarDir
.getFileName().toString().endsWith(".src")) {// binary archive
1503 if (separateSources
)
1504 writer
.append("Corresponding sources are available in the related archive named "
1505 + jarDir
.toString() + ".src.jar.\n");
1507 writer
.append("Corresponding sources are available under OSGI-OPT/src.\n");
1513 * Gathers modifications performed on the original binaries and sources,
1514 * especially in order to comply with their license requirements.
1521 Set
<String
> modified
= new TreeSet
<>();
1522 Set
<String
> deleted
= new TreeSet
<>();
1523 Set
<String
> added
= new TreeSet
<>();
1524 Set
<String
> moved
= new TreeSet
<>();
1526 /** Append changes to the A2-ORIGIN/changes file. */
1527 void appendChanges(Path baseDirectory
) throws IOException
{
1528 if (modified
.isEmpty() && deleted
.isEmpty() && added
.isEmpty() && moved
.isEmpty())
1529 return; // no changes
1530 Path changesFile
= baseDirectory
.resolve(CHANGES
);
1531 Files
.createDirectories(changesFile
.getParent());
1532 try (BufferedWriter writer
= Files
.newBufferedWriter(changesFile
, APPEND
, CREATE
)) {
1533 for (String msg
: added
)
1534 writer
.write("- Added " + msg
+ ".\n");
1535 for (String msg
: modified
)
1536 writer
.write("- Modified " + msg
+ ".\n");
1537 for (String msg
: moved
)
1538 writer
.write("- Moved " + msg
+ ".\n");
1539 for (String msg
: deleted
)
1540 writer
.write("- Deleted " + msg
+ ".\n");
1546 /** Simple representation of an M2 artifact. */
1547 class M2Artifact
extends CategoryNameVersion
{
1548 private String classifier
;
1550 M2Artifact(String m2coordinates
) {
1551 this(m2coordinates
, null);
1554 M2Artifact(String m2coordinates
, String classifier
) {
1555 String
[] parts
= m2coordinates
.split(":");
1556 setCategory(parts
[0]);
1558 if (parts
.length
> 2) {
1559 setVersion(parts
[2]);
1561 this.classifier
= classifier
;
1564 String
getGroupId() {
1565 return super.getCategory();
1568 String
getArtifactId() {
1569 return super.getName();
1572 String
toM2Coordinates() {
1573 return getCategory() + ":" + getName() + (getVersion() != null ?
":" + getVersion() : "");
1576 String
getClassifier() {
1577 return classifier
!= null ? classifier
: "";
1580 String
getExtension() {
1585 /** Utilities around Maven (conventions based). */
1586 class M2ConventionsUtils
{
1587 final static String MAVEN_CENTRAL_BASE_URL
= "https://repo1.maven.org/maven2/";
1589 /** The file name of this artifact when stored */
1590 static String
artifactFileName(M2Artifact artifact
) {
1591 return artifact
.getArtifactId() + '-' + artifact
.getVersion()
1592 + (artifact
.getClassifier().equals("") ?
"" : '-' + artifact
.getClassifier()) + '.'
1593 + artifact
.getExtension();
1596 /** Absolute path to the file */
1597 static String
artifactPath(String artifactBasePath
, M2Artifact artifact
) {
1598 return artifactParentPath(artifactBasePath
, artifact
) + '/' + artifactFileName(artifact
);
1601 /** Absolute path to the file */
1602 static String
artifactUrl(String repoUrl
, M2Artifact artifact
) {
1603 if (repoUrl
.endsWith("/"))
1604 return repoUrl
+ artifactPath("/", artifact
).substring(1);
1606 return repoUrl
+ artifactPath("/", artifact
);
1609 /** Absolute path to the file */
1610 static URL
mavenRepoUrl(String repoBase
, M2Artifact artifact
) {
1611 String url
= artifactUrl(repoBase
== null ? MAVEN_CENTRAL_BASE_URL
: repoBase
, artifact
);
1613 return new URL(url
);
1614 } catch (MalformedURLException e
) {
1615 // it should not happen
1616 throw new IllegalStateException(e
);
1620 /** Absolute path to the directories where the files will be stored */
1621 static String
artifactParentPath(String artifactBasePath
, M2Artifact artifact
) {
1622 return artifactBasePath
+ (artifactBasePath
.endsWith("/") || artifactBasePath
.equals("") ?
"" : "/")
1623 + artifactParentPath(artifact
);
1626 /** Relative path to the directories where the files will be stored */
1627 static String
artifactParentPath(M2Artifact artifact
) {
1628 return artifact
.getGroupId().replace('.', '/') + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion();
1632 private M2ConventionsUtils() {
1636 /** Combination of a category, a name and a version. */
1637 class CategoryNameVersion
extends NameVersion
{
1638 private String category
;
1640 CategoryNameVersion() {
1643 CategoryNameVersion(String category
, String name
, String version
) {
1644 super(name
, version
);
1645 this.category
= category
;
1648 CategoryNameVersion(String category
, NameVersion nameVersion
) {
1650 this.category
= category
;
1653 String
getCategory() {
1657 void setCategory(String category
) {
1658 this.category
= category
;
1662 public String
toString() {
1663 return category
+ ":" + super.toString();
1668 /** Combination of a name and a version. */
1669 class NameVersion
implements Comparable
<NameVersion
> {
1670 private String name
;
1671 private String version
;
1676 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1677 NameVersion(String nameVersion
) {
1678 int index
= nameVersion
.indexOf(";version=");
1680 setName(nameVersion
);
1683 setName(nameVersion
.substring(0, index
));
1684 setVersion(nameVersion
.substring(index
+ ";version=".length()));
1688 NameVersion(String name
, String version
) {
1690 this.version
= version
;
1693 NameVersion(NameVersion nameVersion
) {
1694 this.name
= nameVersion
.getName();
1695 this.version
= nameVersion
.getVersion();
1702 void setName(String name
) {
1706 String
getVersion() {
1710 void setVersion(String version
) {
1711 this.version
= version
;
1714 String
getBranch() {
1715 String
[] parts
= getVersion().split("\\.");
1716 if (parts
.length
< 2)
1717 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1718 return parts
[0] + "." + parts
[1];
1722 public boolean equals(Object obj
) {
1723 if (obj
instanceof NameVersion
) {
1724 NameVersion nameVersion
= (NameVersion
) obj
;
1725 return name
.equals(nameVersion
.getName()) && version
.equals(nameVersion
.getVersion());
1731 public int hashCode() {
1732 return name
.hashCode();
1736 public String
toString() {
1737 return name
+ ":" + version
;
1740 public int compareTo(NameVersion o
) {
1741 if (o
.getName().equals(name
))
1742 return version
.compareTo(o
.getVersion());
1744 return name
.compareTo(o
.getName());