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
.StandardOpenOption
;
44 import java
.nio
.file
.attribute
.BasicFileAttributes
;
45 import java
.util
.ArrayList
;
46 import java
.util
.HashMap
;
47 import java
.util
.Iterator
;
48 import java
.util
.List
;
50 import java
.util
.Objects
;
51 import java
.util
.Properties
;
53 import java
.util
.TreeMap
;
54 import java
.util
.TreeSet
;
55 import java
.util
.concurrent
.CompletableFuture
;
56 import java
.util
.jar
.Attributes
;
57 import java
.util
.jar
.JarEntry
;
58 import java
.util
.jar
.JarInputStream
;
59 import java
.util
.jar
.JarOutputStream
;
60 import java
.util
.jar
.Manifest
;
61 import java
.util
.zip
.Deflater
;
63 import aQute
.bnd
.osgi
.Analyzer
;
64 import aQute
.bnd
.osgi
.Jar
;
67 * Simple tool repackaging existing jar files into OSGi bundles in an A2
70 public class Repackage
{
71 final static Logger logger
= System
.getLogger(Repackage
.class.getName());
74 * Environment variable on whether sources should be packaged separately or
75 * integrated in the bundles.
77 final static String ENV_SOURCE_BUNDLES
= "SOURCE_BUNDLES";
79 /** Whether repackaging should run in parallel or sequentially. */
80 final static boolean parallel
= true;
83 /** Summary of all license seen during the repackaging. */
84 final static Map
<String
, Set
<String
>> licensesUsed
= new TreeMap
<>();
86 /** Main entry point. */
87 public static void main(String
[] args
) {
88 if (args
.length
< 2) {
89 System
.err
.println("Usage: <path to a2 output dir> <category1> <category2> ...");
92 Path a2Base
= Paths
.get(args
[0]).toAbsolutePath().normalize();
93 Path descriptorsBase
= Paths
.get(".").toAbsolutePath().normalize();
94 Repackage factory
= new Repackage(a2Base
, descriptorsBase
);
96 List
<CompletableFuture
<Void
>> toDos
= new ArrayList
<>();
97 for (int i
= 1; i
< args
.length
; i
++) {
98 Path p
= Paths
.get(args
[i
]);
100 toDos
.add(CompletableFuture
.runAsync(() -> factory
.processCategory(p
)));
102 factory
.processCategory(p
);
104 CompletableFuture
.allOf(toDos
.toArray(new CompletableFuture
[toDos
.size()])).join();
107 StringBuilder sb
= new StringBuilder();
108 for (String licenseId
: licensesUsed
.keySet())
109 for (String name
: licensesUsed
.get(licenseId
))
110 sb
.append((licenseId
.equals("") ?
"Proprietary" : licenseId
) + "\t\t" + name
+ "\n");
111 logger
.log(INFO
, "# License summary:\n" + sb
);
114 /** Name of the file centralising information for multiple M2 artifacts. */
115 final static String COMMON_BND
= "common.bnd";
116 /** Name of the file centralising information for mergin M2 artifacts. */
117 final static String MERGE_BND
= "merge.bnd";
119 * Subdirectory of the jar file where origin informations (changes, legal
120 * notices etc. are stored)
122 final static String A2_ORIGIN
= "A2-ORIGIN";
124 /** Directory where to download archives */
126 /** Directory where to download Maven artifacts */
129 /** A2 repository base for binary bundles */
131 /** A2 repository base for source bundles */
133 /** A2 base for native components */
135 /** Location of the descriptors driving the packaging */
136 Path descriptorsBase
;
137 /** URIs of archives to download */
138 Properties uris
= new Properties();
139 /** Mirrors for archive download. Key is URI prefix, value list of base URLs */
140 Map
<String
, List
<String
>> mirrors
= new HashMap
<String
, List
<String
>>();
142 /** Whether sources should be packaged separately */
143 final boolean sourceBundles
;
145 /** Constructor initialises the various variables */
146 public Repackage(Path a2Base
, Path descriptorsBase
) {
147 sourceBundles
= Boolean
.parseBoolean(System
.getenv(ENV_SOURCE_BUNDLES
));
149 logger
.log(INFO
, "Sources will be packaged separately");
151 Objects
.requireNonNull(a2Base
);
152 Objects
.requireNonNull(descriptorsBase
);
153 this.originBase
= Paths
.get(System
.getProperty("user.home"), ".cache", "argeo/build/origin");
154 this.mavenBase
= Paths
.get(System
.getProperty("user.home"), ".m2", "repository");
156 // TODO define and use a build base
157 this.a2Base
= a2Base
;
158 this.a2SrcBase
= a2Base
.getParent().resolve(a2Base
.getFileName() + ".src");
159 this.a2LibBase
= a2Base
.resolve("lib");
160 this.descriptorsBase
= descriptorsBase
;
161 if (!Files
.exists(this.descriptorsBase
))
162 throw new IllegalArgumentException(this.descriptorsBase
+ " does not exist");
165 Path urisPath
= this.descriptorsBase
.resolve("uris.properties");
166 if (Files
.exists(urisPath
)) {
167 try (InputStream in
= Files
.newInputStream(urisPath
)) {
169 } catch (IOException e
) {
170 throw new IllegalStateException("Cannot load " + urisPath
, e
);
175 Path eclipseMirrorsPath
= this.descriptorsBase
.resolve("eclipse.mirrors.txt");
176 List
<String
> eclipseMirrors
= new ArrayList
<>();
177 if (Files
.exists(eclipseMirrorsPath
)) {
179 eclipseMirrors
= Files
.readAllLines(eclipseMirrorsPath
, StandardCharsets
.UTF_8
);
180 } catch (IOException e
) {
181 throw new IllegalStateException("Cannot load " + eclipseMirrorsPath
, e
);
183 for (Iterator
<String
> it
= eclipseMirrors
.iterator(); it
.hasNext();) {
184 String value
= it
.next();
185 if (value
.strip().equals(""))
189 mirrors
.put("http://www.eclipse.org/downloads", eclipseMirrors
);
195 /** Process a whole category/group id. */
196 void processCategory(Path categoryRelativePath
) {
198 Path targetCategoryBase
= descriptorsBase
.resolve(categoryRelativePath
);
199 DirectoryStream
<Path
> bnds
= Files
.newDirectoryStream(targetCategoryBase
,
200 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
201 && !p
.getFileName().toString().equals(MERGE_BND
));
202 for (Path p
: bnds
) {
203 processSingleM2ArtifactDistributionUnit(p
);
206 DirectoryStream
<Path
> dus
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
207 for (Path duDir
: dus
) {
208 if (duDir
.getFileName().toString().startsWith("eclipse-")) {
209 processEclipseArchive(duDir
);
211 processM2BasedDistributionUnit(duDir
);
214 } catch (IOException e
) {
215 throw new RuntimeException("Cannot process category " + categoryRelativePath
, e
);
219 /** Process a standalone Maven artifact. */
220 void processSingleM2ArtifactDistributionUnit(Path bndFile
) {
222 Path categoryRelativePath
= descriptorsBase
.relativize(bndFile
.getParent());
223 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
225 Properties fileProps
= new Properties();
226 try (InputStream in
= Files
.newInputStream(bndFile
)) {
229 String repoStr
= fileProps
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
230 ? fileProps
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
233 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
234 // use file name as symbolic name
235 String symbolicName
= bndFile
.getFileName().toString();
236 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
237 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
240 String m2Coordinates
= fileProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
241 if (m2Coordinates
== null)
242 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile
);
243 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
244 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
245 Path downloaded
= downloadMaven(url
, artifact
);
247 A2Origin origin
= new A2Origin();
248 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, fileProps
, artifact
, origin
);
250 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
, false);
252 createJar(targetBundleDir
, origin
);
253 } catch (Exception e
) {
254 throw new RuntimeException("Cannot process " + bndFile
, e
);
259 * Process multiple Maven artifacts coming from a same project and therefore
260 * with information in common (typically the version), generating single bundles
261 * or merging them if necessary.
263 void processM2BasedDistributionUnit(Path duDir
) {
265 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
266 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
268 Path mergeBnd
= duDir
.resolve(MERGE_BND
);
269 if (Files
.exists(mergeBnd
)) // merge
270 mergeM2Artifacts(mergeBnd
);
272 Path commonBnd
= duDir
.resolve(COMMON_BND
);
273 if (!Files
.exists(commonBnd
))
276 Properties commonProps
= new Properties();
277 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
278 commonProps
.load(in
);
281 String m2Version
= commonProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
282 if (m2Version
== null) {
283 logger
.log(WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
284 return;// ignore, this is probably an Eclipse archive
286 if (!m2Version
.startsWith(":")) {
287 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
289 m2Version
= m2Version
.substring(1);
291 DirectoryStream
<Path
> ds
= Files
.newDirectoryStream(duDir
,
292 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
293 && !p
.getFileName().toString().equals(MERGE_BND
));
295 Properties fileProps
= new Properties();
296 try (InputStream in
= Files
.newInputStream(p
)) {
299 String m2Coordinates
= fileProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
300 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
301 artifact
.setVersion(m2Version
);
303 // prepare manifest entries
304 Properties mergeProps
= new Properties();
305 mergeProps
.putAll(commonProps
);
307 fileEntries
: for (Object key
: fileProps
.keySet()) {
308 if (ARGEO_ORIGIN_M2
.toString().equals(key
))
309 continue fileEntries
;
310 String value
= fileProps
.getProperty(key
.toString());
311 Object previousValue
= mergeProps
.put(key
.toString(), value
);
312 if (previousValue
!= null) {
314 commonBnd
+ ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
317 mergeProps
.put(ARGEO_ORIGIN_M2
.toString(), artifact
.toM2Coordinates());
318 if (!mergeProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
319 // use file name as symbolic name
320 String symbolicName
= p
.getFileName().toString();
321 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
322 mergeProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
325 String repoStr
= mergeProps
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
326 ? mergeProps
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
330 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
331 Path downloaded
= downloadMaven(url
, artifact
);
333 A2Origin origin
= new A2Origin();
334 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, mergeProps
, artifact
, origin
);
335 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
, false);
336 createJar(targetBundleDir
, origin
);
338 } catch (IOException e
) {
339 throw new RuntimeException("Cannot process " + duDir
, e
);
343 /** Merge multiple Maven artifacts. */
344 void mergeM2Artifacts(Path mergeBnd
) throws IOException
{
345 Path duDir
= mergeBnd
.getParent();
346 String category
= duDir
.getParent().getFileName().toString();
347 Path targetCategoryBase
= a2Base
.resolve(category
);
349 Properties mergeProps
= new Properties();
350 try (InputStream in
= Files
.newInputStream(mergeBnd
)) {
354 String m2Version
= mergeProps
.getProperty(ARGEO_ORIGIN_M2
.toString());
355 if (m2Version
== null) {
356 logger
.log(WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
357 return;// ignore, this is probably an Eclipse archive
359 if (!m2Version
.startsWith(":")) {
360 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
362 m2Version
= m2Version
.substring(1);
363 mergeProps
.put(BUNDLE_VERSION
.toString(), m2Version
);
365 String artifactsStr
= mergeProps
.getProperty(ARGEO_ORIGIN_M2_MERGE
.toString());
366 if (artifactsStr
== null)
367 throw new IllegalArgumentException(mergeBnd
+ ": " + ARGEO_ORIGIN_M2_MERGE
+ " must be set");
369 String repoStr
= mergeProps
.containsKey(ARGEO_ORIGIN_M2_REPO
.toString())
370 ? mergeProps
.getProperty(ARGEO_ORIGIN_M2_REPO
.toString())
373 String bundleSymbolicName
= mergeProps
.getProperty(BUNDLE_SYMBOLICNAME
.toString());
374 if (bundleSymbolicName
== null)
375 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd
);
376 CategoryNameVersion nameVersion
= new M2Artifact(category
+ ":" + bundleSymbolicName
+ ":" + m2Version
);
378 A2Origin origin
= new A2Origin();
379 Path bundleDir
= targetCategoryBase
.resolve(bundleSymbolicName
+ "." + nameVersion
.getBranch());
381 String
[] artifacts
= artifactsStr
.split(",");
382 artifacts
: for (String str
: artifacts
) {
383 String m2Coordinates
= str
.trim();
384 if ("".equals(m2Coordinates
))
386 M2Artifact artifact
= new M2Artifact(m2Coordinates
.trim());
387 if (artifact
.getVersion() == null)
388 artifact
.setVersion(m2Version
);
389 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
390 Path downloaded
= downloadMaven(url
, artifact
);
392 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(downloaded
), false)) {
393 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
394 if (entry
.isDirectory())
396 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF")) {
397 origin
.deleted
.add("cryptographic signatures from " + artifact
);
400 if (entry
.getName().endsWith("module-info.class")) { // skip Java 9 module info
401 origin
.deleted
.add("Java module information (module-info.class) from " + artifact
);
404 if (entry
.getName().startsWith("META-INF/versions/")) { // skip multi-version
405 origin
.deleted
.add("additional Java versions (META-INF/versions) from " + artifact
);
408 if (entry
.getName().startsWith("META-INF/maven/")) {
409 origin
.deleted
.add("Maven information (META-INF/maven) from " + artifact
);
412 if (entry
.getName().startsWith(".cache/")) { // Apache SSHD
413 origin
.deleted
.add("cache directory (.cache) from " + artifact
);
416 if (entry
.getName().equals("META-INF/DEPENDENCIES")) {
417 origin
.deleted
.add("Dependencies (META-INF/DEPENDENCIES) from " + artifact
);
420 if (entry
.getName().equals("META-INF/MANIFEST.MF")) {
421 Path originalManifest
= bundleDir
.resolve(A2_ORIGIN
).resolve(artifact
.getGroupId())
422 .resolve(artifact
.getArtifactId()).resolve("MANIFEST.MF");
423 Files
.createDirectories(originalManifest
.getParent());
424 try (OutputStream out
= Files
.newOutputStream(originalManifest
)) {
425 Files
.copy(jarIn
, originalManifest
);
428 "original MANIFEST (" + bundleDir
.relativize(originalManifest
) + ") from " + artifact
);
432 if (entry
.getName().endsWith("NOTICE") || entry
.getName().endsWith("NOTICE.txt")
433 || entry
.getName().endsWith("LICENSE") || entry
.getName().endsWith("LICENSE.md")
434 || entry
.getName().endsWith("LICENSE-notice.md") || entry
.getName().endsWith("COPYING")
435 || entry
.getName().endsWith("COPYING.LESSER")) {
436 Path artifactOriginDir
= bundleDir
.resolve(A2_ORIGIN
).resolve(artifact
.getGroupId())
437 .resolve(artifact
.getArtifactId());
438 Path target
= artifactOriginDir
.resolve(entry
.getName());
439 Files
.createDirectories(target
.getParent());
440 Files
.copy(jarIn
, target
);
441 origin
.moved
.add(entry
.getName() + " in " + artifact
+ " to " + bundleDir
.relativize(target
));
444 Path target
= bundleDir
.resolve(entry
.getName());
445 Files
.createDirectories(target
.getParent());
446 if (!Files
.exists(target
)) {
447 Files
.copy(jarIn
, target
);
449 if (entry
.getName().startsWith("META-INF/services/")) {
450 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
451 out
.write("\n".getBytes());
452 jarIn
.transferTo(out
);
453 logger
.log(DEBUG
, artifact
.getArtifactId() + " - Appended " + entry
.getName());
455 origin
.modified
.add(entry
.getName() + ", merging from " + artifact
);
456 } else if (entry
.getName().startsWith("org/apache/batik/")) {
457 logger
.log(TRACE
, "Skip " + entry
.getName());
460 throw new IllegalStateException("File " + target
+ " from " + artifact
+ " already exists");
463 logger
.log(TRACE
, () -> "Copied " + target
);
466 origin
.added
.add("binary content of " + artifact
);
469 downloadAndProcessM2Sources(repoStr
, artifact
, bundleDir
, true);
472 // additional service files
473 Path servicesDir
= duDir
.resolve("services");
474 if (Files
.exists(servicesDir
)) {
475 for (Path p
: Files
.newDirectoryStream(servicesDir
)) {
476 Path target
= bundleDir
.resolve("META-INF/services/").resolve(p
.getFileName());
477 try (InputStream in
= Files
.newInputStream(p
);
478 OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
);) {
479 out
.write("\n".getBytes());
481 logger
.log(DEBUG
, "Appended " + p
);
483 origin
.added
.add(bundleDir
.relativize(target
).toString());
487 Map
<String
, String
> entries
= new TreeMap
<>();
488 try (Analyzer bndAnalyzer
= new Analyzer()) {
489 bndAnalyzer
.setProperties(mergeProps
);
490 Jar jar
= new Jar(bundleDir
.toFile());
491 bndAnalyzer
.setJar(jar
);
492 Manifest manifest
= bndAnalyzer
.calcManifest();
494 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
495 Object value
= manifest
.getMainAttributes().get(key
);
497 switch (key
.toString()) {
499 case "Bnd-LastModified":
503 if ("Require-Capability".equals(key
.toString())
504 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
505 continue keys
;// hack for very old classes
506 entries
.put(key
.toString(), value
.toString());
508 } catch (Exception e
) {
509 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
512 Manifest manifest
= new Manifest();
513 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
514 Files
.createDirectories(manifestPath
.getParent());
515 for (String key
: entries
.keySet()) {
516 String value
= entries
.get(key
);
517 manifest
.getMainAttributes().putValue(key
, value
);
520 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
523 createJar(bundleDir
, origin
);
526 /** Generate MANIFEST using BND. */
527 Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
, M2Artifact artifact
,
531 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
532 boolean doNotModify
= Boolean
.parseBoolean(
533 fileProps
.getOrDefault(ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED
.toString(), "false").toString());
535 // Note: we always force the symbolic name
537 fileEntries
: for (Object key
: fileProps
.keySet()) {
538 if (ARGEO_ORIGIN_M2
.toString().equals(key
))
539 continue fileEntries
;
540 String value
= fileProps
.getProperty(key
.toString());
541 additionalEntries
.put(key
.toString(), value
);
544 if (artifact
!= null) {
545 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
546 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
548 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
549 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
553 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
554 fileProps
.put(EXPORT_PACKAGE
.toString(),
555 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
558 try (Analyzer bndAnalyzer
= new Analyzer()) {
559 bndAnalyzer
.setProperties(fileProps
);
560 Jar jar
= new Jar(downloaded
.toFile());
561 bndAnalyzer
.setJar(jar
);
562 Manifest manifest
= bndAnalyzer
.calcManifest();
564 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
565 Object value
= manifest
.getMainAttributes().get(key
);
567 switch (key
.toString()) {
569 case "Bnd-LastModified":
573 if ("Require-Capability".equals(key
.toString())
574 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
575 continue keys
;// !! hack for very old classes
576 additionalEntries
.put(key
.toString(), value
.toString());
580 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
, origin
);
581 logger
.log(DEBUG
, () -> "Processed " + downloaded
);
582 return targetBundleDir
;
583 } catch (Exception e
) {
584 throw new RuntimeException("Cannot BND process " + downloaded
, e
);
589 /** Download and integrates sources for a single Maven artifact. */
590 void downloadAndProcessM2Sources(String repoStr
, M2Artifact artifact
, Path targetBundleDir
, boolean merging
)
593 M2Artifact sourcesArtifact
= new M2Artifact(artifact
.toM2Coordinates(), "sources");
594 URL sourcesUrl
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
595 Path sourcesDownloaded
= downloadMaven(sourcesUrl
, artifact
, true);
596 processM2SourceJar(sourcesDownloaded
, targetBundleDir
, merging ? artifact
: null);
597 logger
.log(TRACE
, () -> "Processed source " + sourcesDownloaded
);
598 } catch (Exception e
) {
599 logger
.log(ERROR
, () -> "Cannot download source for " + artifact
);
604 /** Integrate sources from a downloaded jar file. */
605 void processM2SourceJar(Path file
, Path bundleDir
, M2Artifact mergingFrom
) throws IOException
{
606 A2Origin origin
= new A2Origin();
607 Path sourceDir
= sourceBundles ? bundleDir
.getParent().resolve(bundleDir
.toString() + ".src")
608 : bundleDir
.resolve("OSGI-OPT/src");
609 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
611 String mergingMsg
= "";
612 if (mergingFrom
!= null)
613 mergingMsg
= " of " + mergingFrom
;
615 Files
.createDirectories(sourceDir
);
617 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
618 if (entry
.isDirectory())
620 if (entry
.getName().startsWith("META-INF")) {// skip META-INF entries
621 origin
.deleted
.add("META-INF directory from the sources" + mergingMsg
);
624 if (entry
.getName().startsWith("module-info.java")) {// skip Java module information
625 origin
.deleted
.add("Java module information from the sources (module-info.java)" + mergingMsg
);
628 if (entry
.getName().startsWith("/")) { // absolute paths
629 // TODO does it really happen?
630 logger
.log(WARNING
, entry
.getName() + " has an absolute path");
631 origin
.deleted
.add(entry
.getName() + " from the sources" + mergingMsg
);
634 Path target
= sourceDir
.resolve(entry
.getName());
635 Files
.createDirectories(target
.getParent());
636 if (!Files
.exists(target
)) {
637 Files
.copy(jarIn
, target
);
638 logger
.log(TRACE
, () -> "Copied source " + target
);
640 logger
.log(TRACE
, () -> target
+ " already exists, skipping...");
646 origin
.appendChanges(sourceDir
);
648 origin
.added
.add("source code under OSGI-OPT/src");
649 origin
.appendChanges(bundleDir
);
653 /** Download a Maven artifact. */
654 Path
downloadMaven(URL url
, M2Artifact artifact
) throws IOException
{
655 return downloadMaven(url
, artifact
, false);
658 /** Download a Maven artifact. */
659 Path
downloadMaven(URL url
, M2Artifact artifact
, boolean sources
) throws IOException
{
660 return download(url
, mavenBase
, artifact
.getGroupId().replace(".", "/") //
661 + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion() //
662 + '/' + artifact
.getArtifactId() + "-" + artifact
.getVersion() + (sources ?
"-sources" : "") + ".jar");
668 /** Process an archive in Eclipse format. */
669 void processEclipseArchive(Path duDir
) {
671 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
672 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
673 Files
.createDirectories(targetCategoryBase
);
674 // first delete all directories from previous builds
675 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)))
676 deleteDirectory(dir
);
678 Files
.createDirectories(originBase
);
680 Path commonBnd
= duDir
.resolve(COMMON_BND
);
681 Properties commonProps
= new Properties();
682 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
683 commonProps
.load(in
);
685 String url
= commonProps
.getProperty(ARGEO_ORIGIN_URI
.toString());
687 url
= uris
.getProperty(duDir
.getFileName().toString());
689 throw new IllegalStateException("No url available for " + duDir
);
690 commonProps
.put(ARGEO_ORIGIN_URI
.toString(), url
);
692 Path downloaded
= tryDownloadArchive(url
, originBase
);
694 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
697 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
698 Properties includes
= new Properties();
699 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
702 for (Object pattern
: includes
.keySet()) {
703 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
704 includeMatchers
.add(pathMatcher
);
707 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
708 Path excludeFile
= duDir
.resolve("excludes.properties");
709 if (Files
.exists(excludeFile
)) {
710 Properties excludes
= new Properties();
711 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
714 for (Object pattern
: excludes
.keySet()) {
715 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
716 excludeMatchers
.add(pathMatcher
);
720 // keys are the bundle directories
721 Map
<Path
, A2Origin
> origins
= new HashMap
<>();
722 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
725 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
726 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
727 if (includeMatcher
.matches(file
)) {
728 for (PathMatcher excludeMatcher
: excludeMatchers
) {
729 if (excludeMatcher
.matches(file
)) {
730 logger
.log(TRACE
, "Skipping excluded " + file
);
731 return FileVisitResult
.CONTINUE
;
734 if (file
.getFileName().toString().contains(".source_")) {
735 processEclipseSourceJar(file
, targetCategoryBase
);
736 logger
.log(DEBUG
, () -> "Processed source " + file
);
738 Map
<String
, String
> map
= new HashMap
<>();
739 for (Object key
: commonProps
.keySet())
740 map
.put(key
.toString(), commonProps
.getProperty(key
.toString()));
741 A2Origin origin
= new A2Origin();
742 Path bundleDir
= processBundleJar(file
, targetCategoryBase
, map
, origin
);
743 origins
.put(bundleDir
, origin
);
744 logger
.log(DEBUG
, () -> "Processed " + file
);
746 break includeMatchers
;
749 return FileVisitResult
.CONTINUE
;
753 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)
754 && p
.getFileName().toString().indexOf('.') >= 0 && !p
.getFileName().toString().endsWith(".src"));
755 for (Path bundleDir
: dirs
) {
756 A2Origin origin
= origins
.get(bundleDir
);
757 Objects
.requireNonNull(origin
, "No A2 origin found for " + bundleDir
);
758 createJar(bundleDir
, origin
);
760 } catch (IOException e
) {
761 throw new RuntimeException("Cannot process " + duDir
, e
);
766 /** Process sources in Eclipse format. */
767 void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
769 A2Origin origin
= new A2Origin();
771 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
772 Manifest manifest
= jarIn
.getManifest();
774 String
[] relatedBundle
= manifest
.getMainAttributes().getValue(ECLIPSE_SOURCE_BUNDLE
.toString())
776 String version
= relatedBundle
[1].substring("version=\"".length());
777 version
= version
.substring(0, version
.length() - 1);
778 NameVersion nameVersion
= new NameVersion(relatedBundle
[0], version
);
779 bundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
781 Path sourceDir
= sourceBundles ? bundleDir
.getParent().resolve(bundleDir
.toString() + ".src")
782 : bundleDir
.resolve("OSGI-OPT/src");
784 Files
.createDirectories(sourceDir
);
786 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
787 if (entry
.isDirectory())
789 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
791 Path target
= sourceDir
.resolve(entry
.getName());
792 Files
.createDirectories(target
.getParent());
793 Files
.copy(jarIn
, target
);
794 logger
.log(TRACE
, () -> "Copied source " + target
);
799 origin
.appendChanges(sourceDir
);
801 origin
.added
.add("source code under OSGI-OPT/src");
802 origin
.appendChanges(bundleDir
);
805 } catch (IOException e
) {
806 throw new IllegalStateException("Cannot process " + file
, e
);
813 /** Normalise a bundle. */
814 Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
, A2Origin origin
) throws IOException
{
815 boolean embed
= Boolean
.parseBoolean(entries
.getOrDefault(ARGEO_ORIGIN_EMBED
.toString(), "false").toString());
816 NameVersion nameVersion
;
819 boolean isSingleton
= false;
821 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
822 Manifest sourceManifest
= jarIn
.getManifest();
823 manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
825 String rawSourceSymbolicName
= manifest
.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME
.toString());
826 if (rawSourceSymbolicName
!= null) {
827 // make sure there is no directive
828 String
[] arr
= rawSourceSymbolicName
.split(";");
829 for (int i
= 1; i
< arr
.length
; i
++) {
830 if (arr
[i
].trim().equals("singleton:=true"))
832 logger
.log(DEBUG
, file
.getFileName() + " is a singleton");
835 // remove problematic entries in MANIFEST
836 manifest
.getEntries().clear();
838 String ourSymbolicName
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
839 String ourVersion
= entries
.get(BUNDLE_VERSION
.toString());
841 if (ourSymbolicName
!= null && ourVersion
!= null) {
842 nameVersion
= new NameVersion(ourSymbolicName
, ourVersion
);
844 nameVersion
= nameVersionFromManifest(manifest
);
845 if (ourVersion
!= null && !nameVersion
.getVersion().equals(ourVersion
)) {
847 "Original version is " + nameVersion
.getVersion() + " while new version is " + ourVersion
);
848 entries
.put(BUNDLE_VERSION
.toString(), ourVersion
);
850 if (ourSymbolicName
!= null) {
851 // we always force our symbolic name
852 nameVersion
.setName(ourSymbolicName
);
855 bundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
857 if (sourceManifest
!= null) {// copy original MANIFEST
858 Path originalManifest
= bundleDir
.resolve(A2_ORIGIN
).resolve("MANIFEST.MF");
859 Files
.createDirectories(originalManifest
.getParent());
860 try (OutputStream out
= Files
.newOutputStream(originalManifest
)) {
861 sourceManifest
.write(out
);
863 origin
.added
.add("original MANIFEST (" + bundleDir
.relativize(originalManifest
) + ")");
866 // force Java 9 module name
867 entries
.put(ManifestConstants
.AUTOMATIC_MODULE_NAME
.toString(), nameVersion
.getName());
869 boolean isNative
= false;
872 if (bundleDir
.startsWith(a2LibBase
)) {
874 Path libRelativePath
= a2LibBase
.relativize(bundleDir
);
875 os
= libRelativePath
.getName(0).toString();
876 arch
= libRelativePath
.getName(1).toString();
882 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
883 if (entry
.isDirectory())
885 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF")) {
886 origin
.deleted
.add("cryptographic signatures");
889 if (entry
.getName().endsWith("module-info.class")) { // skip Java 9 module info
890 origin
.deleted
.add("Java module information (module-info.class)");
893 if (entry
.getName().startsWith("META-INF/versions/")) { // skip multi-version
894 origin
.deleted
.add("additional Java versions (META-INF/versions)");
897 if (entry
.getName().startsWith("META-INF/maven/")) {
898 origin
.deleted
.add("Maven information (META-INF/maven)");
901 // skip file system providers as they cause issues with native image
902 if (entry
.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider")) {
904 .add("file system providers (META-INF/services/java.nio.file.spi.FileSystemProvider)");
907 if (entry
.getName().startsWith("OSGI-OPT/src/")) { // skip embedded sources
908 origin
.deleted
.add("embedded sources");
911 Path target
= bundleDir
.resolve(entry
.getName());
912 Files
.createDirectories(target
.getParent());
913 Files
.copy(jarIn
, target
);
916 if (isNative
&& (entry
.getName().endsWith(".so") || entry
.getName().endsWith(".dll")
917 || entry
.getName().endsWith(".jnilib"))) {
918 Path categoryDir
= bundleDir
.getParent();
919 boolean copyDll
= false;
920 Path targetDll
= categoryDir
.resolve(bundleDir
.relativize(target
));
921 if (nameVersion
.getName().equals("com.sun.jna")) {
922 if (arch
.equals("x86_64"))
924 if (os
.equals("macosx"))
926 if (target
.getParent().getFileName().toString().equals(os
+ "-" + arch
)) {
929 targetDll
= categoryDir
.resolve(target
.getFileName());
934 Files
.createDirectories(targetDll
.getParent());
935 if (Files
.exists(targetDll
))
936 Files
.delete(targetDll
);
937 Files
.copy(target
, targetDll
);
939 Files
.delete(target
);
940 origin
.deleted
.add(bundleDir
.relativize(target
).toString());
942 logger
.log(TRACE
, () -> "Copied " + target
);
948 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
949 Files
.createDirectories(manifestPath
.getParent());
951 if (isSingleton
&& entries
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
952 entries
.put(BUNDLE_SYMBOLICNAME
.toString(),
953 entries
.get(BUNDLE_SYMBOLICNAME
.toString()) + ";singleton:=true");
956 if (embed
) {// copy embedded jar
957 Files
.copy(file
, bundleDir
.resolve(file
.getFileName()));
958 entries
.put(ManifestConstants
.BUNDLE_CLASSPATH
.toString(), file
.getFileName().toString());
961 // Final MANIFEST decisions
962 // This also where we check the original OSGi metadata and compare with our
964 for (String key
: entries
.keySet()) {
965 String value
= entries
.get(key
);
966 String previousValue
= manifest
.getMainAttributes().getValue(key
);
967 boolean wasDifferent
= previousValue
!= null && !previousValue
.equals(value
);
968 boolean keepPrevious
= false;
970 if (SPDX_LICENSE_IDENTIFIER
.toString().equals(key
) && previousValue
!= null)
972 else if (BUNDLE_VERSION
.toString().equals(key
) && wasDifferent
)
973 if (previousValue
.equals(value
+ ".0")) // typically a Maven first release
977 if (logger
.isLoggable(DEBUG
))
978 logger
.log(DEBUG
, file
.getFileName() + ": " + key
+ " was NOT modified, value kept is "
979 + previousValue
+ ", not overriden with " + value
);
980 value
= previousValue
;
984 manifest
.getMainAttributes().putValue(key
, value
);
985 if (wasDifferent
&& !keepPrevious
) {
986 if (IMPORT_PACKAGE
.toString().equals(key
) || EXPORT_PACKAGE
.toString().equals(key
))
987 logger
.log(TRACE
, () -> file
.getFileName() + ": " + key
+ " was modified");
990 file
.getFileName() + ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
993 // de-pollute MANIFEST
995 case "Archiver-Version":
998 case "Originally-Created-By":
1000 case "Bnd-LastModified":
1001 manifest
.getMainAttributes().remove(key
);
1003 default: // do nothing
1006 // !! hack to remove unresolvable
1007 if (key
.equals("Provide-Capability") || key
.equals("Require-Capability"))
1008 if (nameVersion
.getName().equals("osgi.core") || nameVersion
.getName().equals("osgi.cmpn")) {
1009 manifest
.getMainAttributes().remove(key
);
1014 String spdxLicenceId
= manifest
.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER
.toString());
1015 String bundleLicense
= manifest
.getMainAttributes().getValue(BUNDLE_LICENSE
.toString());
1016 if (spdxLicenceId
== null) {
1017 logger
.log(ERROR
, file
.getFileName() + ": " + SPDX_LICENSE_IDENTIFIER
+ " not available, " + BUNDLE_LICENSE
1018 + " is " + bundleLicense
);
1020 if (!licensesUsed
.containsKey(spdxLicenceId
))
1021 licensesUsed
.put(spdxLicenceId
, new TreeSet
<>());
1022 licensesUsed
.get(spdxLicenceId
).add(nameVersion
.toString());
1025 origin
.modified
.add("jar MANIFEST (META-INF/MANIFEST.MF)");
1026 // write the MANIFEST
1027 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
1028 manifest
.write(out
);
1036 /** Recursively deletes a directory. */
1037 static void deleteDirectory(Path path
) throws IOException
{
1038 if (!Files
.exists(path
))
1040 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
1042 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
1045 Files
.delete(directory
);
1050 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1057 /** Extract name/version from a MANIFEST. */
1058 NameVersion
nameVersionFromManifest(Manifest manifest
) {
1059 Attributes attrs
= manifest
.getMainAttributes();
1061 String symbolicName
= attrs
.getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
1062 if (symbolicName
== null)
1064 // make sure there is no directive
1065 symbolicName
= symbolicName
.split(";")[0];
1067 String version
= attrs
.getValue(ManifestConstants
.BUNDLE_VERSION
.toString());
1068 return new NameVersion(symbolicName
, version
);
1071 /** Try to download from an URI. */
1072 Path
tryDownloadArchive(String uri
, Path dir
) throws IOException
{
1074 List
<String
> urlBases
= null;
1075 String uriPrefix
= null;
1076 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
1077 if (uri
.startsWith(uriPref
)) {
1078 if (mirrors
.get(uriPref
).size() > 0) {
1079 urlBases
= mirrors
.get(uriPref
);
1080 uriPrefix
= uriPref
;
1085 if (urlBases
== null)
1087 return downloadArchive(new URL(uri
), dir
);
1088 } catch (FileNotFoundException e
) {
1089 throw new FileNotFoundException("Cannot find " + uri
);
1093 for (String urlBase
: urlBases
) {
1094 String relativePath
= uri
.substring(uriPrefix
.length());
1095 URL url
= new URL(urlBase
+ relativePath
);
1097 return downloadArchive(url
, dir
);
1098 } catch (FileNotFoundException e
) {
1099 logger
.log(WARNING
, "Cannot download " + url
+ ", trying another mirror");
1102 throw new FileNotFoundException("Cannot find " + uri
);
1106 * Effectively download. Synchronised in order to avoid downloading twice in
1109 synchronized Path
downloadArchive(URL url
, Path dir
) throws IOException
{
1110 return download(url
, dir
, (String
) null);
1113 /** Effectively download. */
1114 Path
download(URL url
, Path dir
, String name
) throws IOException
{
1118 // We use also use parent directory in case the archive itself has a fixed name
1119 String
[] segments
= url
.getPath().split("/");
1120 name
= segments
.length
> 1 ? segments
[segments
.length
- 2] + '-' + segments
[segments
.length
- 1]
1121 : segments
[segments
.length
- 1];
1124 dest
= dir
.resolve(name
);
1125 if (Files
.exists(dest
)) {
1126 logger
.log(TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
1129 Files
.createDirectories(dest
.getParent());
1132 try (InputStream in
= url
.openStream()) {
1133 Files
.copy(in
, dest
);
1134 logger
.log(DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
1139 /** Create a JAR file from a directory. */
1140 Path
createJar(Path bundleDir
, A2Origin origin
) throws IOException
{
1142 origin
.appendChanges(bundleDir
);
1144 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
1145 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
1147 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
1148 manifest
= new Manifest(in
);
1150 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
1151 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
1152 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
1155 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1156 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1157 return super.visitFile(file
, attrs
);
1158 JarEntry entry
= new JarEntry(
1159 bundleDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1160 jarOut
.putNextEntry(entry
);
1161 Files
.copy(file
, jarOut
);
1162 return super.visitFile(file
, attrs
);
1167 deleteDirectory(bundleDir
);
1169 if (sourceBundles
) {
1170 Path bundleCategoryDir
= bundleDir
.getParent();
1171 Path sourceDir
= bundleCategoryDir
.resolve(bundleDir
.toString() + ".src");
1172 if (!Files
.exists(sourceDir
)) {
1173 logger
.log(WARNING
, sourceDir
+ " does not exist, skipping...");
1178 Path relPath
= a2Base
.relativize(bundleCategoryDir
);
1179 Path srcCategoryDir
= a2SrcBase
.resolve(relPath
);
1180 Path srcJarP
= srcCategoryDir
.resolve(sourceDir
.getFileName() + ".jar");
1181 Files
.createDirectories(srcJarP
.getParent());
1183 String bundleSymbolicName
= manifest
.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1184 // in case there are additional directives
1185 bundleSymbolicName
= bundleSymbolicName
.split(";")[0];
1186 Manifest srcManifest
= new Manifest();
1187 srcManifest
.getMainAttributes().put(MANIFEST_VERSION
, "1.0");
1188 srcManifest
.getMainAttributes().putValue(BUNDLE_SYMBOLICNAME
.toString(), bundleSymbolicName
+ ".src");
1189 srcManifest
.getMainAttributes().putValue(BUNDLE_VERSION
.toString(),
1190 manifest
.getMainAttributes().getValue(BUNDLE_VERSION
.toString()).toString());
1191 srcManifest
.getMainAttributes().putValue(ECLIPSE_SOURCE_BUNDLE
.toString(), bundleSymbolicName
1192 + ";version=\"" + manifest
.getMainAttributes().getValue(BUNDLE_VERSION
.toString()));
1194 try (JarOutputStream srcJarOut
= new JarOutputStream(Files
.newOutputStream(srcJarP
), srcManifest
)) {
1195 srcJarOut
.setLevel(Deflater
.BEST_COMPRESSION
);
1196 Files
.walkFileTree(sourceDir
, new SimpleFileVisitor
<Path
>() {
1199 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1200 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1201 return super.visitFile(file
, attrs
);
1202 JarEntry entry
= new JarEntry(
1203 sourceDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1204 srcJarOut
.putNextEntry(entry
);
1205 Files
.copy(file
, srcJarOut
);
1206 return super.visitFile(file
, attrs
);
1211 deleteDirectory(sourceDir
);
1217 /** MANIFEST headers. */
1218 enum ManifestConstants
{
1220 /** OSGi bundle symbolic name. */
1221 BUNDLE_SYMBOLICNAME("Bundle-SymbolicName"), //
1222 /** OSGi bundle version. */
1223 BUNDLE_VERSION("Bundle-Version"), //
1224 /** OSGi bundle license. */
1225 BUNDLE_LICENSE("Bundle-License"), //
1226 /** OSGi exported packages list. */
1227 EXPORT_PACKAGE("Export-Package"), //
1228 /** OSGi imported packages list. */
1229 IMPORT_PACKAGE("Import-Package"), //
1230 /** OSGi path to embedded jar. */
1231 BUNDLE_CLASSPATH("Bundle-Classpath"), //
1233 /** Java module name. */
1234 AUTOMATIC_MODULE_NAME("Automatic-Module-Name"), //
1236 /** Eclipse source bundle. */
1237 ECLIPSE_SOURCE_BUNDLE("Eclipse-SourceBundle"), //
1240 * SPDX license identifier.
1242 * @see https://spdx.org/licenses/
1244 SPDX_LICENSE_IDENTIFIER("SPDX-License-Identifier"), //
1247 * Maven coordinates of the origin, possibly partial when using common.bnd or
1250 ARGEO_ORIGIN_M2("Argeo-Origin-M2"), //
1251 /** List of Maven coordinates to merge. */
1252 ARGEO_ORIGIN_M2_MERGE("Argeo-Origin-M2-Merge"), //
1253 /** Maven repository, if not the default one. */
1254 ARGEO_ORIGIN_M2_REPO("Argeo-Origin-M2-Repo"), //
1256 * Do not perform BND analysis of the origin component. Typically IMport_package
1257 * and Export-Package will be kept untouched.
1259 ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED("Argeo-Origin-ManifestNotModified"), //
1261 * Embed the original jar without modifying it (may be required by some
1262 * proprietary licenses, such as JCR Day License).
1264 ARGEO_ORIGIN_EMBED("Argeo-Origin-Embed"), //
1266 * Origin (non-Maven) URI of the component. It may be anything (jar, archive,
1269 ARGEO_ORIGIN_URI("Argeo-Origin-URI"), //
1274 private ManifestConstants(String value
) {
1279 public String
toString() {
1286 * Gathers modifications performed on the original binaries and sources,
1287 * especially in order to comply with their license requirements.
1290 Set
<String
> modified
= new TreeSet
<>();
1291 Set
<String
> deleted
= new TreeSet
<>();
1292 Set
<String
> added
= new TreeSet
<>();
1293 Set
<String
> moved
= new TreeSet
<>();
1295 /** Append changes to the A2-ORIGIN/changes file. */
1296 void appendChanges(Path baseDirectory
) throws IOException
{
1297 Path changesFile
= baseDirectory
.resolve("A2-ORIGIN/changes");
1298 Files
.createDirectories(changesFile
.getParent());
1299 try (BufferedWriter writer
= Files
.newBufferedWriter(changesFile
, StandardOpenOption
.APPEND
,
1300 StandardOpenOption
.CREATE
)) {
1301 for (String msg
: added
)
1302 writer
.write("- Added " + msg
+ ".\n");
1303 for (String msg
: modified
)
1304 writer
.write("- Modified " + msg
+ ".\n");
1305 for (String msg
: moved
)
1306 writer
.write("- Moved " + msg
+ ".\n");
1307 for (String msg
: deleted
)
1308 writer
.write("- Deleted " + msg
+ ".\n");
1313 /** Simple representation of an M2 artifact. */
1314 class M2Artifact
extends CategoryNameVersion
{
1315 private String classifier
;
1317 M2Artifact(String m2coordinates
) {
1318 this(m2coordinates
, null);
1321 M2Artifact(String m2coordinates
, String classifier
) {
1322 String
[] parts
= m2coordinates
.split(":");
1323 setCategory(parts
[0]);
1325 if (parts
.length
> 2) {
1326 setVersion(parts
[2]);
1328 this.classifier
= classifier
;
1331 String
getGroupId() {
1332 return super.getCategory();
1335 String
getArtifactId() {
1336 return super.getName();
1339 String
toM2Coordinates() {
1340 return getCategory() + ":" + getName() + (getVersion() != null ?
":" + getVersion() : "");
1343 String
getClassifier() {
1344 return classifier
!= null ? classifier
: "";
1347 String
getExtension() {
1352 /** Utilities around Maven (conventions based). */
1353 class M2ConventionsUtils
{
1354 final static String MAVEN_CENTRAL_BASE_URL
= "https://repo1.maven.org/maven2/";
1356 /** The file name of this artifact when stored */
1357 static String
artifactFileName(M2Artifact artifact
) {
1358 return artifact
.getArtifactId() + '-' + artifact
.getVersion()
1359 + (artifact
.getClassifier().equals("") ?
"" : '-' + artifact
.getClassifier()) + '.'
1360 + artifact
.getExtension();
1363 /** Absolute path to the file */
1364 static String
artifactPath(String artifactBasePath
, M2Artifact artifact
) {
1365 return artifactParentPath(artifactBasePath
, artifact
) + '/' + artifactFileName(artifact
);
1368 /** Absolute path to the file */
1369 static String
artifactUrl(String repoUrl
, M2Artifact artifact
) {
1370 if (repoUrl
.endsWith("/"))
1371 return repoUrl
+ artifactPath("/", artifact
).substring(1);
1373 return repoUrl
+ artifactPath("/", artifact
);
1376 /** Absolute path to the file */
1377 static URL
mavenRepoUrl(String repoBase
, M2Artifact artifact
) {
1378 String url
= artifactUrl(repoBase
== null ? MAVEN_CENTRAL_BASE_URL
: repoBase
, artifact
);
1380 return new URL(url
);
1381 } catch (MalformedURLException e
) {
1382 // it should not happen
1383 throw new IllegalStateException(e
);
1387 /** Absolute path to the directories where the files will be stored */
1388 static String
artifactParentPath(String artifactBasePath
, M2Artifact artifact
) {
1389 return artifactBasePath
+ (artifactBasePath
.endsWith("/") ?
"" : "/") + artifactParentPath(artifact
);
1392 /** Relative path to the directories where the files will be stored */
1393 static String
artifactParentPath(M2Artifact artifact
) {
1394 return artifact
.getGroupId().replace('.', '/') + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion();
1398 private M2ConventionsUtils() {
1402 /** Combination of a category, a name and a version. */
1403 class CategoryNameVersion
extends NameVersion
{
1404 private String category
;
1406 CategoryNameVersion() {
1409 CategoryNameVersion(String category
, String name
, String version
) {
1410 super(name
, version
);
1411 this.category
= category
;
1414 CategoryNameVersion(String category
, NameVersion nameVersion
) {
1416 this.category
= category
;
1419 String
getCategory() {
1423 void setCategory(String category
) {
1424 this.category
= category
;
1428 public String
toString() {
1429 return category
+ ":" + super.toString();
1434 /** Combination of a name and a version. */
1435 class NameVersion
implements Comparable
<NameVersion
> {
1436 private String name
;
1437 private String version
;
1442 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1443 NameVersion(String nameVersion
) {
1444 int index
= nameVersion
.indexOf(";version=");
1446 setName(nameVersion
);
1449 setName(nameVersion
.substring(0, index
));
1450 setVersion(nameVersion
.substring(index
+ ";version=".length()));
1454 NameVersion(String name
, String version
) {
1456 this.version
= version
;
1459 NameVersion(NameVersion nameVersion
) {
1460 this.name
= nameVersion
.getName();
1461 this.version
= nameVersion
.getVersion();
1468 void setName(String name
) {
1472 String
getVersion() {
1476 void setVersion(String version
) {
1477 this.version
= version
;
1480 String
getBranch() {
1481 String
[] parts
= getVersion().split("\\.");
1482 if (parts
.length
< 2)
1483 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1484 return parts
[0] + "." + parts
[1];
1488 public boolean equals(Object obj
) {
1489 if (obj
instanceof NameVersion
) {
1490 NameVersion nameVersion
= (NameVersion
) obj
;
1491 return name
.equals(nameVersion
.getName()) && version
.equals(nameVersion
.getVersion());
1497 public int hashCode() {
1498 return name
.hashCode();
1502 public String
toString() {
1503 return name
+ ":" + version
;
1506 public int compareTo(NameVersion o
) {
1507 if (o
.getName().equals(name
))
1508 return version
.compareTo(o
.getVersion());
1510 return name
.compareTo(o
.getName());