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
.util
.jar
.Attributes
.Name
.MANIFEST_VERSION
;
10 import static org
.argeo
.build
.Repackage
.ManifestConstants
.ARGEO_ORIGIN_EMBED
;
11 import static org
.argeo
.build
.Repackage
.ManifestConstants
.ARGEO_ORIGIN_M2
;
12 import static org
.argeo
.build
.Repackage
.ManifestConstants
.ARGEO_ORIGIN_M2_MERGE
;
13 import static org
.argeo
.build
.Repackage
.ManifestConstants
.ARGEO_ORIGIN_M2_REPO
;
14 import static org
.argeo
.build
.Repackage
.ManifestConstants
.ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED
;
15 import static org
.argeo
.build
.Repackage
.ManifestConstants
.ARGEO_ORIGIN_URI
;
16 import static org
.argeo
.build
.Repackage
.ManifestConstants
.BUNDLE_LICENSE
;
17 import static org
.argeo
.build
.Repackage
.ManifestConstants
.BUNDLE_SYMBOLICNAME
;
18 import static org
.argeo
.build
.Repackage
.ManifestConstants
.BUNDLE_VERSION
;
19 import static org
.argeo
.build
.Repackage
.ManifestConstants
.ECLIPSE_SOURCE_BUNDLE
;
20 import static org
.argeo
.build
.Repackage
.ManifestConstants
.EXPORT_PACKAGE
;
21 import static org
.argeo
.build
.Repackage
.ManifestConstants
.IMPORT_PACKAGE
;
22 import static org
.argeo
.build
.Repackage
.ManifestConstants
.SPDX_LICENSE_IDENTIFIER
;
24 import java
.io
.BufferedWriter
;
26 import java
.io
.FileNotFoundException
;
27 import java
.io
.IOException
;
28 import java
.io
.InputStream
;
29 import java
.io
.OutputStream
;
30 import java
.lang
.System
.Logger
;
31 import java
.net
.MalformedURLException
;
33 import java
.nio
.charset
.StandardCharsets
;
34 import java
.nio
.file
.DirectoryStream
;
35 import java
.nio
.file
.FileSystem
;
36 import java
.nio
.file
.FileSystems
;
37 import java
.nio
.file
.FileVisitResult
;
38 import java
.nio
.file
.Files
;
39 import java
.nio
.file
.Path
;
40 import java
.nio
.file
.PathMatcher
;
41 import java
.nio
.file
.Paths
;
42 import java
.nio
.file
.SimpleFileVisitor
;
43 import java
.nio
.file
.StandardCopyOption
;
44 import java
.nio
.file
.StandardOpenOption
;
45 import java
.nio
.file
.attribute
.BasicFileAttributes
;
46 import java
.util
.ArrayList
;
47 import java
.util
.HashMap
;
48 import java
.util
.Iterator
;
49 import java
.util
.List
;
51 import java
.util
.Objects
;
52 import java
.util
.Properties
;
54 import java
.util
.TreeMap
;
55 import java
.util
.TreeSet
;
56 import java
.util
.concurrent
.CompletableFuture
;
57 import java
.util
.jar
.Attributes
;
58 import java
.util
.jar
.JarEntry
;
59 import java
.util
.jar
.JarInputStream
;
60 import java
.util
.jar
.JarOutputStream
;
61 import java
.util
.jar
.Manifest
;
62 import java
.util
.zip
.Deflater
;
64 import aQute
.bnd
.osgi
.Analyzer
;
65 import aQute
.bnd
.osgi
.Jar
;
68 * Simple tool repackaging existing jar files into OSGi bundles in an A2
71 public class Repackage
{
72 final static Logger logger
= System
.getLogger(Repackage
.class.getName());
75 * Environment variable on whether sources should be packaged separately or
76 * integrated in the bundles.
78 final static String ENV_SOURCE_BUNDLES
= "SOURCE_BUNDLES";
80 /** Whether repackaging should run in parallel or sequentially. */
81 final static boolean parallel
= true;
84 /** Summary of all license seen during the repackaging. */
85 final static Map
<String
, Set
<String
>> licensesUsed
= new TreeMap
<>();
87 /** Main entry point. */
88 public static void main(String
[] args
) {
89 if (args
.length
< 2) {
90 System
.err
.println("Usage: <path to a2 output dir> <category1> <category2> ...");
93 Path a2Base
= Paths
.get(args
[0]).toAbsolutePath().normalize();
94 Path descriptorsBase
= Paths
.get(".").toAbsolutePath().normalize();
95 Repackage factory
= new Repackage(a2Base
, descriptorsBase
);
97 List
<CompletableFuture
<Void
>> toDos
= new ArrayList
<>();
98 for (int i
= 1; i
< args
.length
; i
++) {
99 Path p
= Paths
.get(args
[i
]);
101 toDos
.add(CompletableFuture
.runAsync(() -> factory
.processCategory(p
)));
103 factory
.processCategory(p
);
105 CompletableFuture
.allOf(toDos
.toArray(new CompletableFuture
[toDos
.size()])).join();
108 StringBuilder sb
= new StringBuilder();
109 for (String licenseId
: licensesUsed
.keySet())
110 for (String name
: licensesUsed
.get(licenseId
))
111 sb
.append((licenseId
.equals("") ?
"Proprietary" : licenseId
) + "\t\t" + name
+ "\n");
112 logger
.log(INFO
, "# License summary:\n" + sb
);
115 /** Name of the file centralising information for multiple M2 artifacts. */
116 final static String COMMON_BND
= "common.bnd";
117 /** Name of the file centralising information for mergin M2 artifacts. */
118 final static String MERGE_BND
= "merge.bnd";
120 * Subdirectory of the jar file where origin informations (changes, legal
121 * notices etc. are stored)
123 final static String A2_ORIGIN
= "A2-ORIGIN";
125 /** Directory where to download archives */
126 final Path originBase
;
127 /** Directory where to download Maven artifacts */
128 final Path mavenBase
;
130 /** A2 repository base for binary bundles */
132 /** A2 repository base for source bundles */
133 final Path a2SrcBase
;
134 /** A2 base for native components */
135 final Path a2LibBase
;
136 /** Location of the descriptors driving the packaging */
137 final Path descriptorsBase
;
138 /** URIs of archives to download */
139 final Properties uris
= new Properties();
140 /** Mirrors for archive download. Key is URI prefix, value list of base URLs */
141 final Map
<String
, List
<String
>> mirrors
= new HashMap
<String
, List
<String
>>();
143 /** Whether sources should be packaged separately */
144 final boolean sourceBundles
;
146 /** Constructor initialises the various variables */
147 public Repackage(Path a2Base
, Path descriptorsBase
) {
148 sourceBundles
= Boolean
.parseBoolean(System
.getenv(ENV_SOURCE_BUNDLES
));
150 logger
.log(INFO
, "Sources will be packaged separately");
152 Objects
.requireNonNull(a2Base
);
153 Objects
.requireNonNull(descriptorsBase
);
154 this.originBase
= Paths
.get(System
.getProperty("user.home"), ".cache", "argeo/build/origin");
155 this.mavenBase
= Paths
.get(System
.getProperty("user.home"), ".m2", "repository");
157 // TODO define and use a build base
158 this.a2Base
= a2Base
;
159 this.a2SrcBase
= a2Base
.getParent().resolve(a2Base
.getFileName() + ".src");
160 this.a2LibBase
= a2Base
.resolve("lib");
161 this.descriptorsBase
= descriptorsBase
;
162 if (!Files
.exists(this.descriptorsBase
))
163 throw new IllegalArgumentException(this.descriptorsBase
+ " does not exist");
166 Path urisPath
= this.descriptorsBase
.resolve("uris.properties");
167 if (Files
.exists(urisPath
)) {
168 try (InputStream in
= Files
.newInputStream(urisPath
)) {
170 } catch (IOException e
) {
171 throw new IllegalStateException("Cannot load " + urisPath
, e
);
176 Path eclipseMirrorsPath
= this.descriptorsBase
.resolve("eclipse.mirrors.txt");
177 List
<String
> eclipseMirrors
= new ArrayList
<>();
178 if (Files
.exists(eclipseMirrorsPath
)) {
180 eclipseMirrors
= Files
.readAllLines(eclipseMirrorsPath
, StandardCharsets
.UTF_8
);
181 } catch (IOException e
) {
182 throw new IllegalStateException("Cannot load " + eclipseMirrorsPath
, e
);
184 for (Iterator
<String
> it
= eclipseMirrors
.iterator(); it
.hasNext();) {
185 String value
= it
.next();
186 if (value
.strip().equals(""))
190 mirrors
.put("http://www.eclipse.org/downloads", eclipseMirrors
);
196 /** Process a whole category/group id. */
197 void processCategory(Path categoryRelativePath
) {
199 Path targetCategoryBase
= descriptorsBase
.resolve(categoryRelativePath
);
200 DirectoryStream
<Path
> bnds
= Files
.newDirectoryStream(targetCategoryBase
,
201 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
202 && !p
.getFileName().toString().equals(MERGE_BND
));
203 for (Path p
: bnds
) {
204 processSingleM2ArtifactDistributionUnit(p
);
207 DirectoryStream
<Path
> dus
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
208 for (Path duDir
: dus
) {
209 if (duDir
.getFileName().toString().startsWith("eclipse-")) {
210 processEclipseArchive(duDir
);
212 processM2BasedDistributionUnit(duDir
);
215 } catch (IOException e
) {
216 throw new RuntimeException("Cannot process category " + categoryRelativePath
, e
);
220 /** Process a standalone Maven artifact. */
221 void processSingleM2ArtifactDistributionUnit(Path bndFile
) {
223 Path categoryRelativePath
= descriptorsBase
.relativize(bndFile
.getParent());
224 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
226 Properties fileProps
= new Properties();
227 try (InputStream in
= Files
.newInputStream(bndFile
)) {
230 String repoStr
= fileProps
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
231 ? fileProps
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
234 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
235 // use file name as symbolic name
236 String symbolicName
= bndFile
.getFileName().toString();
237 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
238 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
241 String m2Coordinates
= fileProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
242 if (m2Coordinates
== null)
243 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile
);
244 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
245 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
246 Path downloaded
= downloadMaven(url
, artifact
);
248 // some proprietary artifacts do not allow any modification
249 // when releasing (with separate sources) we just copy it
250 boolean doNotModify
= Boolean
.parseBoolean(
251 fileProps
.getOrDefault(ManifestConstants
.ARGEO_DO_NOT_MODIFY
.toString(), "false").toString());
252 if (doNotModify
&& sourceBundles
) {
253 Path unmodifiedTarget
= targetCategoryBase
.resolve(
254 fileProps
.getProperty(BUNDLE_SYMBOLICNAME
.toString()) + "." + artifact
.getBranch() + ".jar");
255 Files
.copy(downloaded
, unmodifiedTarget
, StandardCopyOption
.REPLACE_EXISTING
);
256 Path bundleDir
= targetCategoryBase
257 .resolve(fileProps
.getProperty(BUNDLE_SYMBOLICNAME
.toString()) + "." + artifact
.getBranch());
258 downloadAndProcessM2Sources(repoStr
, artifact
, bundleDir
, false);
260 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(unmodifiedTarget
))) {
261 manifest
= jarIn
.getManifest();
263 createSourceJar(unmodifiedTarget
, manifest
);
267 // regular processing
268 A2Origin origin
= new A2Origin();
269 Path bundleDir
= processBndJar(downloaded
, targetCategoryBase
, fileProps
, artifact
, origin
);
270 downloadAndProcessM2Sources(repoStr
, artifact
, bundleDir
, false);
271 createJar(bundleDir
, origin
);
272 } catch (Exception e
) {
273 throw new RuntimeException("Cannot process " + bndFile
, e
);
278 * Process multiple Maven artifacts coming from a same project and therefore
279 * with information in common (typically the version), generating single bundles
280 * or merging them if necessary.
282 void processM2BasedDistributionUnit(Path duDir
) {
284 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
285 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
287 Path mergeBnd
= duDir
.resolve(MERGE_BND
);
288 if (Files
.exists(mergeBnd
)) // merge
289 mergeM2Artifacts(mergeBnd
);
291 Path commonBnd
= duDir
.resolve(COMMON_BND
);
292 if (!Files
.exists(commonBnd
))
295 Properties commonProps
= new Properties();
296 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
297 commonProps
.load(in
);
300 String m2Version
= commonProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
301 if (m2Version
== null) {
302 logger
.log(WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
303 return;// ignore, this is probably an Eclipse archive
305 if (!m2Version
.startsWith(":")) {
306 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
308 m2Version
= m2Version
.substring(1);
310 DirectoryStream
<Path
> ds
= Files
.newDirectoryStream(duDir
,
311 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
312 && !p
.getFileName().toString().equals(MERGE_BND
));
314 Properties fileProps
= new Properties();
315 try (InputStream in
= Files
.newInputStream(p
)) {
318 String m2Coordinates
= fileProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
319 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
320 artifact
.setVersion(m2Version
);
322 // prepare manifest entries
323 Properties mergeProps
= new Properties();
324 mergeProps
.putAll(commonProps
);
326 fileEntries
: for (Object key
: fileProps
.keySet()) {
327 if (ARGEO_ORIGIN_M2
.toString().equals(key
))
328 continue fileEntries
;
329 String value
= fileProps
.getProperty(key
.toString());
330 Object previousValue
= mergeProps
.put(key
.toString(), value
);
331 if (previousValue
!= null) {
333 commonBnd
+ ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
336 mergeProps
.put(ARGEO_ORIGIN_M2
.toString(), artifact
.toM2Coordinates());
337 if (!mergeProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
338 // use file name as symbolic name
339 String symbolicName
= p
.getFileName().toString();
340 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
341 mergeProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
344 String repoStr
= mergeProps
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
345 ? mergeProps
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
349 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
350 Path downloaded
= downloadMaven(url
, artifact
);
352 A2Origin origin
= new A2Origin();
353 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, mergeProps
, artifact
, origin
);
354 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
, false);
355 createJar(targetBundleDir
, origin
);
357 } catch (IOException e
) {
358 throw new RuntimeException("Cannot process " + duDir
, e
);
362 /** Merge multiple Maven artifacts. */
363 void mergeM2Artifacts(Path mergeBnd
) throws IOException
{
364 Path duDir
= mergeBnd
.getParent();
365 String category
= duDir
.getParent().getFileName().toString();
366 Path targetCategoryBase
= a2Base
.resolve(category
);
368 Properties mergeProps
= new Properties();
369 try (InputStream in
= Files
.newInputStream(mergeBnd
)) {
373 String m2Version
= mergeProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
374 if (m2Version
== null) {
375 logger
.log(WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
376 return;// ignore, this is probably an Eclipse archive
378 if (!m2Version
.startsWith(":")) {
379 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
381 m2Version
= m2Version
.substring(1);
382 mergeProps
.put(BUNDLE_VERSION
.toString(), m2Version
);
384 String artifactsStr
= mergeProps
.getProperty(ARGEO_ORIGIN_M2_MERGE
.toString());
385 if (artifactsStr
== null)
386 throw new IllegalArgumentException(mergeBnd
+ ": " + ARGEO_ORIGIN_M2_MERGE
+ " must be set");
388 String repoStr
= mergeProps
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
389 ? mergeProps
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
392 String bundleSymbolicName
= mergeProps
.getProperty(BUNDLE_SYMBOLICNAME
.toString());
393 if (bundleSymbolicName
== null)
394 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd
);
395 CategoryNameVersion nameVersion
= new M2Artifact(category
+ ":" + bundleSymbolicName
+ ":" + m2Version
);
397 A2Origin origin
= new A2Origin();
398 Path bundleDir
= targetCategoryBase
.resolve(bundleSymbolicName
+ "." + nameVersion
.getBranch());
400 String
[] artifacts
= artifactsStr
.split(",");
401 artifacts
: for (String str
: artifacts
) {
402 String m2Coordinates
= str
.trim();
403 if ("".equals(m2Coordinates
))
405 M2Artifact artifact
= new M2Artifact(m2Coordinates
.trim());
406 if (artifact
.getVersion() == null)
407 artifact
.setVersion(m2Version
);
408 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
409 Path downloaded
= downloadMaven(url
, artifact
);
411 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(downloaded
), false)) {
412 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
413 if (entry
.isDirectory())
415 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF")) {
416 origin
.deleted
.add("cryptographic signatures from " + artifact
);
419 if (entry
.getName().endsWith("module-info.class")) { // skip Java 9 module info
420 origin
.deleted
.add("Java module information (module-info.class) from " + artifact
);
423 if (entry
.getName().startsWith("META-INF/versions/")) { // skip multi-version
424 origin
.deleted
.add("additional Java versions (META-INF/versions) from " + artifact
);
427 if (entry
.getName().startsWith("META-INF/maven/")) {
428 origin
.deleted
.add("Maven information (META-INF/maven) from " + artifact
);
431 if (entry
.getName().startsWith(".cache/")) { // Apache SSHD
432 origin
.deleted
.add("cache directory (.cache) from " + artifact
);
435 if (entry
.getName().equals("META-INF/DEPENDENCIES")) {
436 origin
.deleted
.add("Dependencies (META-INF/DEPENDENCIES) from " + artifact
);
439 if (entry
.getName().equals("META-INF/MANIFEST.MF")) {
440 Path originalManifest
= bundleDir
.resolve(A2_ORIGIN
).resolve(artifact
.getGroupId())
441 .resolve(artifact
.getArtifactId()).resolve("MANIFEST.MF");
442 Files
.createDirectories(originalManifest
.getParent());
443 try (OutputStream out
= Files
.newOutputStream(originalManifest
)) {
444 Files
.copy(jarIn
, originalManifest
);
447 "original MANIFEST (" + bundleDir
.relativize(originalManifest
) + ") from " + artifact
);
451 if (entry
.getName().endsWith("NOTICE") || entry
.getName().endsWith("NOTICE.txt")
452 || entry
.getName().endsWith("LICENSE") || entry
.getName().endsWith("LICENSE.md")
453 || entry
.getName().endsWith("LICENSE-notice.md") || entry
.getName().endsWith("COPYING")
454 || entry
.getName().endsWith("COPYING.LESSER")) {
455 Path artifactOriginDir
= bundleDir
.resolve(A2_ORIGIN
).resolve(artifact
.getGroupId())
456 .resolve(artifact
.getArtifactId());
457 Path target
= artifactOriginDir
.resolve(entry
.getName());
458 Files
.createDirectories(target
.getParent());
459 Files
.copy(jarIn
, target
);
460 origin
.moved
.add(entry
.getName() + " in " + artifact
+ " to " + bundleDir
.relativize(target
));
463 Path target
= bundleDir
.resolve(entry
.getName());
464 Files
.createDirectories(target
.getParent());
465 if (!Files
.exists(target
)) {
466 Files
.copy(jarIn
, target
);
468 if (entry
.getName().startsWith("META-INF/services/")) {
469 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
470 out
.write("\n".getBytes());
471 jarIn
.transferTo(out
);
472 logger
.log(DEBUG
, artifact
.getArtifactId() + " - Appended " + entry
.getName());
474 origin
.modified
.add(entry
.getName() + ", merging from " + artifact
);
475 } else if (entry
.getName().startsWith("org/apache/batik/")) {
476 logger
.log(TRACE
, "Skip " + entry
.getName());
479 throw new IllegalStateException("File " + target
+ " from " + artifact
+ " already exists");
482 logger
.log(TRACE
, () -> "Copied " + target
);
485 origin
.added
.add("binary content of " + artifact
);
488 downloadAndProcessM2Sources(repoStr
, artifact
, bundleDir
, true);
491 // additional service files
492 Path servicesDir
= duDir
.resolve("services");
493 if (Files
.exists(servicesDir
)) {
494 for (Path p
: Files
.newDirectoryStream(servicesDir
)) {
495 Path target
= bundleDir
.resolve("META-INF/services/").resolve(p
.getFileName());
496 try (InputStream in
= Files
.newInputStream(p
);
497 OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
);) {
498 out
.write("\n".getBytes());
500 logger
.log(DEBUG
, "Appended " + p
);
502 origin
.added
.add(bundleDir
.relativize(target
).toString());
506 Map
<String
, String
> entries
= new TreeMap
<>();
507 try (Analyzer bndAnalyzer
= new Analyzer()) {
508 bndAnalyzer
.setProperties(mergeProps
);
509 Jar jar
= new Jar(bundleDir
.toFile());
510 bndAnalyzer
.setJar(jar
);
511 Manifest manifest
= bndAnalyzer
.calcManifest();
513 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
514 Object value
= manifest
.getMainAttributes().get(key
);
516 switch (key
.toString()) {
518 case "Bnd-LastModified":
522 if ("Require-Capability".equals(key
.toString())
523 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
524 continue keys
;// hack for very old classes
525 entries
.put(key
.toString(), value
.toString());
527 } catch (Exception e
) {
528 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
531 Manifest manifest
= new Manifest();
532 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
533 Files
.createDirectories(manifestPath
.getParent());
534 for (String key
: entries
.keySet()) {
535 String value
= entries
.get(key
);
536 manifest
.getMainAttributes().putValue(key
, value
);
539 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
542 createJar(bundleDir
, origin
);
545 /** Generate MANIFEST using BND. */
546 Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
, M2Artifact artifact
,
549 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
550 boolean doNotModifyManifest
= Boolean
.parseBoolean(
551 fileProps
.getOrDefault(ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED
.toString(), "false").toString());
553 // Note: we always force the symbolic name
554 if (doNotModifyManifest
) {
555 fileEntries
: for (Object key
: fileProps
.keySet()) {
556 if (ARGEO_ORIGIN_M2
.toString().equals(key
))
557 continue fileEntries
;
558 String value
= fileProps
.getProperty(key
.toString());
559 additionalEntries
.put(key
.toString(), value
);
562 if (artifact
!= null) {
563 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
564 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
566 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
567 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
571 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
572 fileProps
.put(EXPORT_PACKAGE
.toString(),
573 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
576 try (Analyzer bndAnalyzer
= new Analyzer()) {
577 bndAnalyzer
.setProperties(fileProps
);
578 Jar jar
= new Jar(downloaded
.toFile());
579 bndAnalyzer
.setJar(jar
);
580 Manifest manifest
= bndAnalyzer
.calcManifest();
582 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
583 Object value
= manifest
.getMainAttributes().get(key
);
585 switch (key
.toString()) {
587 case "Bnd-LastModified":
591 if ("Require-Capability".equals(key
.toString())
592 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
593 continue keys
;// !! hack for very old classes
594 additionalEntries
.put(key
.toString(), value
.toString());
598 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
, origin
);
599 logger
.log(DEBUG
, () -> "Processed " + downloaded
);
600 return targetBundleDir
;
601 } catch (Exception e
) {
602 throw new RuntimeException("Cannot BND process " + downloaded
, e
);
607 /** Download and integrates sources for a single Maven artifact. */
608 void downloadAndProcessM2Sources(String repoStr
, M2Artifact artifact
, Path targetBundleDir
, boolean merging
)
611 M2Artifact sourcesArtifact
= new M2Artifact(artifact
.toM2Coordinates(), "sources");
612 URL sourcesUrl
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
613 Path sourcesDownloaded
= downloadMaven(sourcesUrl
, artifact
, true);
614 processM2SourceJar(sourcesDownloaded
, targetBundleDir
, merging ? artifact
: null);
615 logger
.log(TRACE
, () -> "Processed source " + sourcesDownloaded
);
616 } catch (Exception e
) {
617 logger
.log(ERROR
, () -> "Cannot download source for " + artifact
);
622 /** Integrate sources from a downloaded jar file. */
623 void processM2SourceJar(Path file
, Path bundleDir
, M2Artifact mergingFrom
) throws IOException
{
624 A2Origin origin
= new A2Origin();
625 Path sourceDir
= sourceBundles ? bundleDir
.getParent().resolve(bundleDir
.toString() + ".src")
626 : bundleDir
.resolve("OSGI-OPT/src");
627 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
629 String mergingMsg
= "";
630 if (mergingFrom
!= null)
631 mergingMsg
= " of " + mergingFrom
;
633 Files
.createDirectories(sourceDir
);
635 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
636 if (entry
.isDirectory())
638 if (entry
.getName().startsWith("META-INF")) {// skip META-INF entries
639 origin
.deleted
.add("META-INF directory from the sources" + mergingMsg
);
642 if (entry
.getName().startsWith("module-info.java")) {// skip Java module information
643 origin
.deleted
.add("Java module information from the sources (module-info.java)" + mergingMsg
);
646 if (entry
.getName().startsWith("/")) { // absolute paths
647 // TODO does it really happen?
648 logger
.log(WARNING
, entry
.getName() + " has an absolute path");
649 origin
.deleted
.add(entry
.getName() + " from the sources" + mergingMsg
);
652 Path target
= sourceDir
.resolve(entry
.getName());
653 Files
.createDirectories(target
.getParent());
654 if (!Files
.exists(target
)) {
655 Files
.copy(jarIn
, target
);
656 logger
.log(TRACE
, () -> "Copied source " + target
);
658 logger
.log(TRACE
, () -> target
+ " already exists, skipping...");
664 origin
.appendChanges(sourceDir
);
666 origin
.added
.add("source code under OSGI-OPT/src");
667 origin
.appendChanges(bundleDir
);
671 /** Download a Maven artifact. */
672 Path
downloadMaven(URL url
, M2Artifact artifact
) throws IOException
{
673 return downloadMaven(url
, artifact
, false);
676 /** Download a Maven artifact. */
677 Path
downloadMaven(URL url
, M2Artifact artifact
, boolean sources
) throws IOException
{
678 return download(url
, mavenBase
, artifact
.getGroupId().replace(".", "/") //
679 + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion() //
680 + '/' + artifact
.getArtifactId() + "-" + artifact
.getVersion() + (sources ?
"-sources" : "") + ".jar");
686 /** Process an archive in Eclipse format. */
687 void processEclipseArchive(Path duDir
) {
689 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
690 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
691 Files
.createDirectories(targetCategoryBase
);
692 // first delete all directories from previous builds
693 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)))
694 deleteDirectory(dir
);
696 Files
.createDirectories(originBase
);
698 Path commonBnd
= duDir
.resolve(COMMON_BND
);
699 Properties commonProps
= new Properties();
700 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
701 commonProps
.load(in
);
703 String url
= commonProps
.getProperty(ARGEO_ORIGIN_URI
.toString());
705 url
= uris
.getProperty(duDir
.getFileName().toString());
707 throw new IllegalStateException("No url available for " + duDir
);
708 commonProps
.put(ARGEO_ORIGIN_URI
.toString(), url
);
710 Path downloaded
= tryDownloadArchive(url
, originBase
);
712 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
715 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
716 Properties includes
= new Properties();
717 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
720 for (Object pattern
: includes
.keySet()) {
721 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
722 includeMatchers
.add(pathMatcher
);
725 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
726 Path excludeFile
= duDir
.resolve("excludes.properties");
727 if (Files
.exists(excludeFile
)) {
728 Properties excludes
= new Properties();
729 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
732 for (Object pattern
: excludes
.keySet()) {
733 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
734 excludeMatchers
.add(pathMatcher
);
738 // keys are the bundle directories
739 Map
<Path
, A2Origin
> origins
= new HashMap
<>();
740 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
743 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
744 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
745 if (includeMatcher
.matches(file
)) {
746 for (PathMatcher excludeMatcher
: excludeMatchers
) {
747 if (excludeMatcher
.matches(file
)) {
748 logger
.log(TRACE
, "Skipping excluded " + file
);
749 return FileVisitResult
.CONTINUE
;
752 if (file
.getFileName().toString().contains(".source_")) {
753 processEclipseSourceJar(file
, targetCategoryBase
);
754 logger
.log(DEBUG
, () -> "Processed source " + file
);
756 Map
<String
, String
> map
= new HashMap
<>();
757 for (Object key
: commonProps
.keySet())
758 map
.put(key
.toString(), commonProps
.getProperty(key
.toString()));
759 A2Origin origin
= new A2Origin();
760 Path bundleDir
= processBundleJar(file
, targetCategoryBase
, map
, origin
);
761 origins
.put(bundleDir
, origin
);
762 logger
.log(DEBUG
, () -> "Processed " + file
);
764 break includeMatchers
;
767 return FileVisitResult
.CONTINUE
;
771 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)
772 && p
.getFileName().toString().indexOf('.') >= 0 && !p
.getFileName().toString().endsWith(".src"));
773 for (Path bundleDir
: dirs
) {
774 A2Origin origin
= origins
.get(bundleDir
);
775 Objects
.requireNonNull(origin
, "No A2 origin found for " + bundleDir
);
776 createJar(bundleDir
, origin
);
778 } catch (IOException e
) {
779 throw new RuntimeException("Cannot process " + duDir
, e
);
784 /** Process sources in Eclipse format. */
785 void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
787 A2Origin origin
= new A2Origin();
789 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
790 Manifest manifest
= jarIn
.getManifest();
792 String
[] relatedBundle
= manifest
.getMainAttributes().getValue(ECLIPSE_SOURCE_BUNDLE
.toString())
794 String version
= relatedBundle
[1].substring("version=\"".length());
795 version
= version
.substring(0, version
.length() - 1);
796 NameVersion nameVersion
= new NameVersion(relatedBundle
[0], version
);
797 bundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
799 Path sourceDir
= sourceBundles ? bundleDir
.getParent().resolve(bundleDir
.toString() + ".src")
800 : bundleDir
.resolve("OSGI-OPT/src");
802 Files
.createDirectories(sourceDir
);
804 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
805 if (entry
.isDirectory())
807 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
809 Path target
= sourceDir
.resolve(entry
.getName());
810 Files
.createDirectories(target
.getParent());
811 Files
.copy(jarIn
, target
);
812 logger
.log(TRACE
, () -> "Copied source " + target
);
817 origin
.appendChanges(sourceDir
);
819 origin
.added
.add("source code under OSGI-OPT/src");
820 origin
.appendChanges(bundleDir
);
823 } catch (IOException e
) {
824 throw new IllegalStateException("Cannot process " + file
, e
);
831 /** Normalise a bundle. */
832 Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
, A2Origin origin
) throws IOException
{
833 boolean embed
= Boolean
.parseBoolean(entries
.getOrDefault(ARGEO_ORIGIN_EMBED
.toString(), "false").toString());
834 NameVersion nameVersion
;
837 boolean isSingleton
= false;
839 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
840 Manifest sourceManifest
= jarIn
.getManifest();
841 manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
843 String rawSourceSymbolicName
= manifest
.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME
.toString());
844 if (rawSourceSymbolicName
!= null) {
845 // make sure there is no directive
846 String
[] arr
= rawSourceSymbolicName
.split(";");
847 for (int i
= 1; i
< arr
.length
; i
++) {
848 if (arr
[i
].trim().equals("singleton:=true"))
850 logger
.log(DEBUG
, file
.getFileName() + " is a singleton");
853 // remove problematic entries in MANIFEST
854 manifest
.getEntries().clear();
856 String ourSymbolicName
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
857 String ourVersion
= entries
.get(BUNDLE_VERSION
.toString());
859 if (ourSymbolicName
!= null && ourVersion
!= null) {
860 nameVersion
= new NameVersion(ourSymbolicName
, ourVersion
);
862 nameVersion
= nameVersionFromManifest(manifest
);
863 if (ourVersion
!= null && !nameVersion
.getVersion().equals(ourVersion
)) {
865 "Original version is " + nameVersion
.getVersion() + " while new version is " + ourVersion
);
866 entries
.put(BUNDLE_VERSION
.toString(), ourVersion
);
868 if (ourSymbolicName
!= null) {
869 // we always force our symbolic name
870 nameVersion
.setName(ourSymbolicName
);
873 bundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
875 if (sourceManifest
!= null) {// copy original MANIFEST
876 Path originalManifest
= bundleDir
.resolve(A2_ORIGIN
).resolve("MANIFEST.MF");
877 Files
.createDirectories(originalManifest
.getParent());
878 try (OutputStream out
= Files
.newOutputStream(originalManifest
)) {
879 sourceManifest
.write(out
);
881 origin
.added
.add("original MANIFEST (" + bundleDir
.relativize(originalManifest
) + ")");
884 // force Java 9 module name
885 entries
.put(ManifestConstants
.AUTOMATIC_MODULE_NAME
.toString(), nameVersion
.getName());
887 boolean isNative
= false;
890 if (bundleDir
.startsWith(a2LibBase
)) {
892 Path libRelativePath
= a2LibBase
.relativize(bundleDir
);
893 os
= libRelativePath
.getName(0).toString();
894 arch
= libRelativePath
.getName(1).toString();
900 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
901 if (entry
.isDirectory())
903 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".DSA")
904 || entry
.getName().endsWith(".SF")) {
905 origin
.deleted
.add("cryptographic signatures");
908 if (entry
.getName().endsWith("module-info.class")) { // skip Java 9 module info
909 origin
.deleted
.add("Java module information (module-info.class)");
912 if (entry
.getName().startsWith("META-INF/versions/")) { // skip multi-version
913 origin
.deleted
.add("additional Java versions (META-INF/versions)");
916 if (entry
.getName().startsWith("META-INF/maven/")) {
917 origin
.deleted
.add("Maven information (META-INF/maven)");
920 // skip file system providers as they cause issues with native image
921 if (entry
.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider")) {
923 .add("file system providers (META-INF/services/java.nio.file.spi.FileSystemProvider)");
926 if (entry
.getName().startsWith("OSGI-OPT/src/")) { // skip embedded sources
927 origin
.deleted
.add("embedded sources");
930 Path target
= bundleDir
.resolve(entry
.getName());
931 Files
.createDirectories(target
.getParent());
932 Files
.copy(jarIn
, target
);
935 if (isNative
&& (entry
.getName().endsWith(".so") || entry
.getName().endsWith(".dll")
936 || entry
.getName().endsWith(".jnilib"))) {
937 Path categoryDir
= bundleDir
.getParent();
938 boolean copyDll
= false;
939 Path targetDll
= categoryDir
.resolve(bundleDir
.relativize(target
));
940 if (nameVersion
.getName().equals("com.sun.jna")) {
941 if (arch
.equals("x86_64"))
943 if (os
.equals("macosx"))
945 if (target
.getParent().getFileName().toString().equals(os
+ "-" + arch
)) {
948 targetDll
= categoryDir
.resolve(target
.getFileName());
953 Files
.createDirectories(targetDll
.getParent());
954 if (Files
.exists(targetDll
))
955 Files
.delete(targetDll
);
956 Files
.copy(target
, targetDll
);
958 Files
.delete(target
);
959 origin
.deleted
.add(bundleDir
.relativize(target
).toString());
961 logger
.log(TRACE
, () -> "Copied " + target
);
967 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
968 Files
.createDirectories(manifestPath
.getParent());
970 if (isSingleton
&& entries
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
971 entries
.put(BUNDLE_SYMBOLICNAME
.toString(),
972 entries
.get(BUNDLE_SYMBOLICNAME
.toString()) + ";singleton:=true");
975 if (embed
) {// copy embedded jar
976 Files
.copy(file
, bundleDir
.resolve(file
.getFileName()));
977 entries
.put(ManifestConstants
.BUNDLE_CLASSPATH
.toString(), file
.getFileName().toString());
980 // Final MANIFEST decisions
981 // This also where we check the original OSGi metadata and compare with our
983 for (String key
: entries
.keySet()) {
984 String value
= entries
.get(key
);
985 String previousValue
= manifest
.getMainAttributes().getValue(key
);
986 boolean wasDifferent
= previousValue
!= null && !previousValue
.equals(value
);
987 boolean keepPrevious
= false;
989 if (SPDX_LICENSE_IDENTIFIER
.toString().equals(key
) && previousValue
!= null)
991 else if (BUNDLE_VERSION
.toString().equals(key
) && wasDifferent
)
992 if (previousValue
.equals(value
+ ".0")) // typically a Maven first release
996 if (logger
.isLoggable(DEBUG
))
997 logger
.log(DEBUG
, file
.getFileName() + ": " + key
+ " was NOT modified, value kept is "
998 + previousValue
+ ", not overriden with " + value
);
999 value
= previousValue
;
1003 manifest
.getMainAttributes().putValue(key
, value
);
1004 if (wasDifferent
&& !keepPrevious
) {
1005 if (IMPORT_PACKAGE
.toString().equals(key
) || EXPORT_PACKAGE
.toString().equals(key
))
1006 logger
.log(TRACE
, () -> file
.getFileName() + ": " + key
+ " was modified");
1009 file
.getFileName() + ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
1012 // de-pollute MANIFEST
1014 case "Archiver-Version":
1017 case "Originally-Created-By":
1019 case "Bnd-LastModified":
1020 manifest
.getMainAttributes().remove(key
);
1022 default: // do nothing
1025 // !! hack to remove unresolvable
1026 if (key
.equals("Provide-Capability") || key
.equals("Require-Capability"))
1027 if (nameVersion
.getName().equals("osgi.core") || nameVersion
.getName().equals("osgi.cmpn")) {
1028 manifest
.getMainAttributes().remove(key
);
1033 String spdxLicenceId
= manifest
.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER
.toString());
1034 String bundleLicense
= manifest
.getMainAttributes().getValue(BUNDLE_LICENSE
.toString());
1035 if (spdxLicenceId
== null) {
1036 logger
.log(ERROR
, file
.getFileName() + ": " + SPDX_LICENSE_IDENTIFIER
+ " not available, " + BUNDLE_LICENSE
1037 + " is " + bundleLicense
);
1039 if (!licensesUsed
.containsKey(spdxLicenceId
))
1040 licensesUsed
.put(spdxLicenceId
, new TreeSet
<>());
1041 licensesUsed
.get(spdxLicenceId
).add(nameVersion
.toString());
1044 origin
.modified
.add("jar MANIFEST (META-INF/MANIFEST.MF)");
1045 // write the MANIFEST
1046 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
1047 manifest
.write(out
);
1055 /** Recursively deletes a directory. */
1056 static void deleteDirectory(Path path
) throws IOException
{
1057 if (!Files
.exists(path
))
1059 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
1061 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
1064 Files
.delete(directory
);
1069 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1076 /** Extract name/version from a MANIFEST. */
1077 NameVersion
nameVersionFromManifest(Manifest manifest
) {
1078 Attributes attrs
= manifest
.getMainAttributes();
1080 String symbolicName
= attrs
.getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
1081 if (symbolicName
== null)
1083 // make sure there is no directive
1084 symbolicName
= symbolicName
.split(";")[0];
1086 String version
= attrs
.getValue(ManifestConstants
.BUNDLE_VERSION
.toString());
1087 return new NameVersion(symbolicName
, version
);
1090 /** Try to download from an URI. */
1091 Path
tryDownloadArchive(String uri
, Path dir
) throws IOException
{
1093 List
<String
> urlBases
= null;
1094 String uriPrefix
= null;
1095 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
1096 if (uri
.startsWith(uriPref
)) {
1097 if (mirrors
.get(uriPref
).size() > 0) {
1098 urlBases
= mirrors
.get(uriPref
);
1099 uriPrefix
= uriPref
;
1104 if (urlBases
== null)
1106 return downloadArchive(new URL(uri
), dir
);
1107 } catch (FileNotFoundException e
) {
1108 throw new FileNotFoundException("Cannot find " + uri
);
1112 for (String urlBase
: urlBases
) {
1113 String relativePath
= uri
.substring(uriPrefix
.length());
1114 URL url
= new URL(urlBase
+ relativePath
);
1116 return downloadArchive(url
, dir
);
1117 } catch (FileNotFoundException e
) {
1118 logger
.log(WARNING
, "Cannot download " + url
+ ", trying another mirror");
1121 throw new FileNotFoundException("Cannot find " + uri
);
1125 * Effectively download. Synchronised in order to avoid downloading twice in
1128 synchronized Path
downloadArchive(URL url
, Path dir
) throws IOException
{
1129 return download(url
, dir
, (String
) null);
1132 /** Effectively download. */
1133 Path
download(URL url
, Path dir
, String name
) throws IOException
{
1137 // We use also use parent directory in case the archive itself has a fixed name
1138 String
[] segments
= url
.getPath().split("/");
1139 name
= segments
.length
> 1 ? segments
[segments
.length
- 2] + '-' + segments
[segments
.length
- 1]
1140 : segments
[segments
.length
- 1];
1143 dest
= dir
.resolve(name
);
1144 if (Files
.exists(dest
)) {
1145 logger
.log(TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
1148 Files
.createDirectories(dest
.getParent());
1151 try (InputStream in
= url
.openStream()) {
1152 Files
.copy(in
, dest
);
1153 logger
.log(DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
1158 /** Create a JAR file from a directory. */
1159 Path
createJar(Path bundleDir
, A2Origin origin
) throws IOException
{
1161 origin
.appendChanges(bundleDir
);
1163 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
1164 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
1166 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
1167 manifest
= new Manifest(in
);
1169 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
1170 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
1171 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
1174 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1175 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1176 return super.visitFile(file
, attrs
);
1177 JarEntry entry
= new JarEntry(
1178 bundleDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1179 jarOut
.putNextEntry(entry
);
1180 Files
.copy(file
, jarOut
);
1181 return super.visitFile(file
, attrs
);
1186 deleteDirectory(bundleDir
);
1189 createSourceJar(bundleDir
, manifest
);
1194 void createSourceJar(Path bundleDir
, Manifest manifest
) throws IOException
{
1195 Path bundleCategoryDir
= bundleDir
.getParent();
1196 Path sourceDir
= bundleCategoryDir
.resolve(bundleDir
.toString() + ".src");
1197 if (!Files
.exists(sourceDir
)) {
1198 logger
.log(WARNING
, sourceDir
+ " does not exist, skipping...");
1203 Path relPath
= a2Base
.relativize(bundleCategoryDir
);
1204 Path srcCategoryDir
= a2SrcBase
.resolve(relPath
);
1205 Path srcJarP
= srcCategoryDir
.resolve(sourceDir
.getFileName() + ".jar");
1206 Files
.createDirectories(srcJarP
.getParent());
1208 String bundleSymbolicName
= manifest
.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1209 // in case there are additional directives
1210 bundleSymbolicName
= bundleSymbolicName
.split(";")[0];
1211 Manifest srcManifest
= new Manifest();
1212 srcManifest
.getMainAttributes().put(MANIFEST_VERSION
, "1.0");
1213 srcManifest
.getMainAttributes().putValue(BUNDLE_SYMBOLICNAME
.toString(), bundleSymbolicName
+ ".src");
1214 srcManifest
.getMainAttributes().putValue(BUNDLE_VERSION
.toString(),
1215 manifest
.getMainAttributes().getValue(BUNDLE_VERSION
.toString()).toString());
1216 srcManifest
.getMainAttributes().putValue(ECLIPSE_SOURCE_BUNDLE
.toString(),
1217 bundleSymbolicName
+ ";version=\"" + manifest
.getMainAttributes().getValue(BUNDLE_VERSION
.toString()));
1219 try (JarOutputStream srcJarOut
= new JarOutputStream(Files
.newOutputStream(srcJarP
), srcManifest
)) {
1220 srcJarOut
.setLevel(Deflater
.BEST_COMPRESSION
);
1221 Files
.walkFileTree(sourceDir
, new SimpleFileVisitor
<Path
>() {
1224 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1225 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1226 return super.visitFile(file
, attrs
);
1227 JarEntry entry
= new JarEntry(
1228 sourceDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1229 srcJarOut
.putNextEntry(entry
);
1230 Files
.copy(file
, srcJarOut
);
1231 return super.visitFile(file
, attrs
);
1236 deleteDirectory(sourceDir
);
1239 /** MANIFEST headers. */
1240 enum ManifestConstants
{
1242 /** OSGi bundle symbolic name. */
1243 BUNDLE_SYMBOLICNAME("Bundle-SymbolicName"), //
1244 /** OSGi bundle version. */
1245 BUNDLE_VERSION("Bundle-Version"), //
1246 /** OSGi bundle license. */
1247 BUNDLE_LICENSE("Bundle-License"), //
1248 /** OSGi exported packages list. */
1249 EXPORT_PACKAGE("Export-Package"), //
1250 /** OSGi imported packages list. */
1251 IMPORT_PACKAGE("Import-Package"), //
1252 /** OSGi path to embedded jar. */
1253 BUNDLE_CLASSPATH("Bundle-Classpath"), //
1255 /** Java module name. */
1256 AUTOMATIC_MODULE_NAME("Automatic-Module-Name"), //
1258 /** Eclipse source bundle. */
1259 ECLIPSE_SOURCE_BUNDLE("Eclipse-SourceBundle"), //
1262 * SPDX license identifier.
1264 * @see https://spdx.org/licenses/
1266 SPDX_LICENSE_IDENTIFIER("SPDX-License-Identifier"), //
1269 * Maven coordinates of the origin, possibly partial when using common.bnd or
1272 ARGEO_ORIGIN_M2("Argeo-Origin-M2"), //
1273 /** List of Maven coordinates to merge. */
1274 ARGEO_ORIGIN_M2_MERGE("Argeo-Origin-M2-Merge"), //
1275 /** Maven repository, if not the default one. */
1276 ARGEO_ORIGIN_M2_REPO("Argeo-Origin-M2-Repo"), //
1278 * Do not perform BND analysis of the origin component. Typically IMport_package
1279 * and Export-Package will be kept untouched.
1281 ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED("Argeo-Origin-ManifestNotModified"), //
1283 * Embed the original jar without modifying it (may be required by some
1284 * proprietary licenses, such as JCR Day License).
1286 ARGEO_ORIGIN_EMBED("Argeo-Origin-Embed"), //
1288 * Do not modify original jar (may be required by some proprietary licenses,
1289 * such as JCR Day License).
1291 ARGEO_DO_NOT_MODIFY("Argeo-Origin-Do-Not-Modify"), //
1293 * Origin (non-Maven) URI of the component. It may be anything (jar, archive,
1296 ARGEO_ORIGIN_URI("Argeo-Origin-URI"), //
1301 private ManifestConstants(String value
) {
1306 public String
toString() {
1313 * Gathers modifications performed on the original binaries and sources,
1314 * especially in order to comply with their license requirements.
1317 Set
<String
> modified
= new TreeSet
<>();
1318 Set
<String
> deleted
= new TreeSet
<>();
1319 Set
<String
> added
= new TreeSet
<>();
1320 Set
<String
> moved
= new TreeSet
<>();
1322 /** Append changes to the A2-ORIGIN/changes file. */
1323 void appendChanges(Path baseDirectory
) throws IOException
{
1324 Path changesFile
= baseDirectory
.resolve("A2-ORIGIN/changes");
1325 Files
.createDirectories(changesFile
.getParent());
1326 try (BufferedWriter writer
= Files
.newBufferedWriter(changesFile
, StandardOpenOption
.APPEND
,
1327 StandardOpenOption
.CREATE
)) {
1328 for (String msg
: added
)
1329 writer
.write("- Added " + msg
+ ".\n");
1330 for (String msg
: modified
)
1331 writer
.write("- Modified " + msg
+ ".\n");
1332 for (String msg
: moved
)
1333 writer
.write("- Moved " + msg
+ ".\n");
1334 for (String msg
: deleted
)
1335 writer
.write("- Deleted " + msg
+ ".\n");
1340 /** Simple representation of an M2 artifact. */
1341 class M2Artifact
extends CategoryNameVersion
{
1342 private String classifier
;
1344 M2Artifact(String m2coordinates
) {
1345 this(m2coordinates
, null);
1348 M2Artifact(String m2coordinates
, String classifier
) {
1349 String
[] parts
= m2coordinates
.split(":");
1350 setCategory(parts
[0]);
1352 if (parts
.length
> 2) {
1353 setVersion(parts
[2]);
1355 this.classifier
= classifier
;
1358 String
getGroupId() {
1359 return super.getCategory();
1362 String
getArtifactId() {
1363 return super.getName();
1366 String
toM2Coordinates() {
1367 return getCategory() + ":" + getName() + (getVersion() != null ?
":" + getVersion() : "");
1370 String
getClassifier() {
1371 return classifier
!= null ? classifier
: "";
1374 String
getExtension() {
1379 /** Utilities around Maven (conventions based). */
1380 class M2ConventionsUtils
{
1381 final static String MAVEN_CENTRAL_BASE_URL
= "https://repo1.maven.org/maven2/";
1383 /** The file name of this artifact when stored */
1384 static String
artifactFileName(M2Artifact artifact
) {
1385 return artifact
.getArtifactId() + '-' + artifact
.getVersion()
1386 + (artifact
.getClassifier().equals("") ?
"" : '-' + artifact
.getClassifier()) + '.'
1387 + artifact
.getExtension();
1390 /** Absolute path to the file */
1391 static String
artifactPath(String artifactBasePath
, M2Artifact artifact
) {
1392 return artifactParentPath(artifactBasePath
, artifact
) + '/' + artifactFileName(artifact
);
1395 /** Absolute path to the file */
1396 static String
artifactUrl(String repoUrl
, M2Artifact artifact
) {
1397 if (repoUrl
.endsWith("/"))
1398 return repoUrl
+ artifactPath("/", artifact
).substring(1);
1400 return repoUrl
+ artifactPath("/", artifact
);
1403 /** Absolute path to the file */
1404 static URL
mavenRepoUrl(String repoBase
, M2Artifact artifact
) {
1405 String url
= artifactUrl(repoBase
== null ? MAVEN_CENTRAL_BASE_URL
: repoBase
, artifact
);
1407 return new URL(url
);
1408 } catch (MalformedURLException e
) {
1409 // it should not happen
1410 throw new IllegalStateException(e
);
1414 /** Absolute path to the directories where the files will be stored */
1415 static String
artifactParentPath(String artifactBasePath
, M2Artifact artifact
) {
1416 return artifactBasePath
+ (artifactBasePath
.endsWith("/") ?
"" : "/") + artifactParentPath(artifact
);
1419 /** Relative path to the directories where the files will be stored */
1420 static String
artifactParentPath(M2Artifact artifact
) {
1421 return artifact
.getGroupId().replace('.', '/') + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion();
1425 private M2ConventionsUtils() {
1429 /** Combination of a category, a name and a version. */
1430 class CategoryNameVersion
extends NameVersion
{
1431 private String category
;
1433 CategoryNameVersion() {
1436 CategoryNameVersion(String category
, String name
, String version
) {
1437 super(name
, version
);
1438 this.category
= category
;
1441 CategoryNameVersion(String category
, NameVersion nameVersion
) {
1443 this.category
= category
;
1446 String
getCategory() {
1450 void setCategory(String category
) {
1451 this.category
= category
;
1455 public String
toString() {
1456 return category
+ ":" + super.toString();
1461 /** Combination of a name and a version. */
1462 class NameVersion
implements Comparable
<NameVersion
> {
1463 private String name
;
1464 private String version
;
1469 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1470 NameVersion(String nameVersion
) {
1471 int index
= nameVersion
.indexOf(";version=");
1473 setName(nameVersion
);
1476 setName(nameVersion
.substring(0, index
));
1477 setVersion(nameVersion
.substring(index
+ ";version=".length()));
1481 NameVersion(String name
, String version
) {
1483 this.version
= version
;
1486 NameVersion(NameVersion nameVersion
) {
1487 this.name
= nameVersion
.getName();
1488 this.version
= nameVersion
.getVersion();
1495 void setName(String name
) {
1499 String
getVersion() {
1503 void setVersion(String version
) {
1504 this.version
= version
;
1507 String
getBranch() {
1508 String
[] parts
= getVersion().split("\\.");
1509 if (parts
.length
< 2)
1510 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1511 return parts
[0] + "." + parts
[1];
1515 public boolean equals(Object obj
) {
1516 if (obj
instanceof NameVersion
) {
1517 NameVersion nameVersion
= (NameVersion
) obj
;
1518 return name
.equals(nameVersion
.getName()) && version
.equals(nameVersion
.getVersion());
1524 public int hashCode() {
1525 return name
.hashCode();
1529 public String
toString() {
1530 return name
+ ":" + version
;
1533 public int compareTo(NameVersion o
) {
1534 if (o
.getName().equals(name
))
1535 return version
.compareTo(o
.getVersion());
1537 return name
.compareTo(o
.getName());