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().equals("META-INF/DEPENDENCIES")) {
409 origin
.deleted
.add("dependency list (META-INF/DEPENDENCIES) from " + artifact
);
412 if (entry
.getName().startsWith("META-INF/maven/")) {
413 origin
.deleted
.add("Maven information (META-INF/maven) from " + artifact
);
416 if (entry
.getName().startsWith(".cache/")) { // Apache SSHD
417 origin
.deleted
.add("cache directory (.cache) from " + artifact
);
421 if (entry
.getName().endsWith("NOTICE") || entry
.getName().endsWith("NOTICE.txt")
422 || entry
.getName().endsWith("LICENSE") || entry
.getName().endsWith("LICENSE.md")
423 || entry
.getName().endsWith("LICENSE-notice.md") || entry
.getName().endsWith("COPYING")
424 || entry
.getName().endsWith("COPYING.LESSER")) {
425 Path artifactOriginDir
= bundleDir
.resolve(A2_ORIGIN
).resolve(artifact
.getGroupId())
426 .resolve(artifact
.getArtifactId());
427 Path target
= artifactOriginDir
.resolve(entry
.getName());
428 Files
.createDirectories(target
.getParent());
429 Files
.copy(jarIn
, target
);
430 origin
.moved
.add(entry
.getName() + " in " + artifact
+ " to " + bundleDir
.relativize(target
));
433 Path target
= bundleDir
.resolve(entry
.getName());
434 Files
.createDirectories(target
.getParent());
435 if (!Files
.exists(target
)) {
436 Files
.copy(jarIn
, target
);
438 if (entry
.getName().startsWith("META-INF/services/")) {
439 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
440 out
.write("\n".getBytes());
441 jarIn
.transferTo(out
);
442 logger
.log(DEBUG
, artifact
.getArtifactId() + " - Appended " + entry
.getName());
444 origin
.modified
.add(entry
.getName() + ", merging from " + artifact
);
445 } else if (entry
.getName().startsWith("org/apache/batik/")) {
446 logger
.log(TRACE
, "Skip " + entry
.getName());
449 throw new IllegalStateException("File " + target
+ " from " + artifact
+ " already exists");
452 logger
.log(TRACE
, () -> "Copied " + target
);
455 origin
.added
.add("binary content of " + artifact
);
458 downloadAndProcessM2Sources(repoStr
, artifact
, bundleDir
, true);
461 // additional service files
462 Path servicesDir
= duDir
.resolve("services");
463 if (Files
.exists(servicesDir
)) {
464 for (Path p
: Files
.newDirectoryStream(servicesDir
)) {
465 Path target
= bundleDir
.resolve("META-INF/services/").resolve(p
.getFileName());
466 try (InputStream in
= Files
.newInputStream(p
);
467 OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
);) {
468 out
.write("\n".getBytes());
470 logger
.log(DEBUG
, "Appended " + p
);
472 origin
.added
.add(bundleDir
.relativize(target
).toString());
476 Map
<String
, String
> entries
= new TreeMap
<>();
477 try (Analyzer bndAnalyzer
= new Analyzer()) {
478 bndAnalyzer
.setProperties(mergeProps
);
479 Jar jar
= new Jar(bundleDir
.toFile());
480 bndAnalyzer
.setJar(jar
);
481 Manifest manifest
= bndAnalyzer
.calcManifest();
483 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
484 Object value
= manifest
.getMainAttributes().get(key
);
486 switch (key
.toString()) {
488 case "Bnd-LastModified":
492 if ("Require-Capability".equals(key
.toString())
493 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
494 continue keys
;// hack for very old classes
495 entries
.put(key
.toString(), value
.toString());
497 } catch (Exception e
) {
498 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
501 Manifest manifest
= new Manifest();
502 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
503 Files
.createDirectories(manifestPath
.getParent());
504 for (String key
: entries
.keySet()) {
505 String value
= entries
.get(key
);
506 manifest
.getMainAttributes().putValue(key
, value
);
509 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
512 createJar(bundleDir
, origin
);
515 /** Generate MANIFEST using BND. */
516 Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
, M2Artifact artifact
,
520 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
521 boolean doNotModify
= Boolean
.parseBoolean(
522 fileProps
.getOrDefault(ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED
.toString(), "false").toString());
524 // Note: we always force the symbolic name
526 fileEntries
: for (Object key
: fileProps
.keySet()) {
527 if (ARGEO_ORIGIN_M2
.toString().equals(key
))
528 continue fileEntries
;
529 String value
= fileProps
.getProperty(key
.toString());
530 additionalEntries
.put(key
.toString(), value
);
533 if (artifact
!= null) {
534 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
535 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
537 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
538 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
542 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
543 fileProps
.put(EXPORT_PACKAGE
.toString(),
544 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
547 try (Analyzer bndAnalyzer
= new Analyzer()) {
548 bndAnalyzer
.setProperties(fileProps
);
549 Jar jar
= new Jar(downloaded
.toFile());
550 bndAnalyzer
.setJar(jar
);
551 Manifest manifest
= bndAnalyzer
.calcManifest();
553 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
554 Object value
= manifest
.getMainAttributes().get(key
);
556 switch (key
.toString()) {
558 case "Bnd-LastModified":
562 if ("Require-Capability".equals(key
.toString())
563 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
564 continue keys
;// !! hack for very old classes
565 additionalEntries
.put(key
.toString(), value
.toString());
569 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
, origin
);
570 logger
.log(DEBUG
, () -> "Processed " + downloaded
);
571 return targetBundleDir
;
572 } catch (Exception e
) {
573 throw new RuntimeException("Cannot BND process " + downloaded
, e
);
578 /** Download and integrates sources for a single Maven artifact. */
579 void downloadAndProcessM2Sources(String repoStr
, M2Artifact artifact
, Path targetBundleDir
, boolean merging
)
582 M2Artifact sourcesArtifact
= new M2Artifact(artifact
.toM2Coordinates(), "sources");
583 URL sourcesUrl
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
584 Path sourcesDownloaded
= downloadMaven(sourcesUrl
, artifact
, true);
585 processM2SourceJar(sourcesDownloaded
, targetBundleDir
, merging ? artifact
: null);
586 logger
.log(TRACE
, () -> "Processed source " + sourcesDownloaded
);
587 } catch (Exception e
) {
588 logger
.log(ERROR
, () -> "Cannot download source for " + artifact
);
593 /** Integrate sources from a downloaded jar file. */
594 void processM2SourceJar(Path file
, Path bundleDir
, M2Artifact mergingFrom
) throws IOException
{
595 A2Origin origin
= new A2Origin();
596 Path sourceDir
= sourceBundles ? bundleDir
.getParent().resolve(bundleDir
.toString() + ".src")
597 : bundleDir
.resolve("OSGI-OPT/src");
598 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
600 String mergingMsg
= "";
601 if (mergingFrom
!= null)
602 mergingMsg
= " of " + mergingFrom
;
604 Files
.createDirectories(sourceDir
);
606 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
607 if (entry
.isDirectory())
609 if (entry
.getName().startsWith("META-INF")) {// skip META-INF entries
610 origin
.deleted
.add("META-INF directory from the sources" + mergingMsg
);
613 if (entry
.getName().startsWith("module-info.java")) {// skip Java module information
614 origin
.deleted
.add("Java module information from the sources (module-info.java)" + mergingMsg
);
617 if (entry
.getName().startsWith("/")) { // absolute paths
618 // TODO does it really happen?
619 logger
.log(WARNING
, entry
.getName() + " has an absolute path");
620 origin
.deleted
.add(entry
.getName() + " from the sources" + mergingMsg
);
623 Path target
= sourceDir
.resolve(entry
.getName());
624 Files
.createDirectories(target
.getParent());
625 if (!Files
.exists(target
)) {
626 Files
.copy(jarIn
, target
);
627 logger
.log(TRACE
, () -> "Copied source " + target
);
629 logger
.log(TRACE
, () -> target
+ " already exists, skipping...");
635 origin
.appendChanges(sourceDir
);
637 origin
.added
.add("source code under OSGI-OPT/src");
638 origin
.appendChanges(bundleDir
);
642 /** Download a Maven artifact. */
643 Path
downloadMaven(URL url
, M2Artifact artifact
) throws IOException
{
644 return downloadMaven(url
, artifact
, false);
647 /** Download a Maven artifact. */
648 Path
downloadMaven(URL url
, M2Artifact artifact
, boolean sources
) throws IOException
{
649 return download(url
, mavenBase
, artifact
.getGroupId().replace(".", "/") //
650 + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion() //
651 + '/' + artifact
.getArtifactId() + "-" + artifact
.getVersion() + (sources ?
"-sources" : "") + ".jar");
657 /** Process an archive in Eclipse format. */
658 void processEclipseArchive(Path duDir
) {
660 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
661 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
662 Files
.createDirectories(targetCategoryBase
);
663 // first delete all directories from previous builds
664 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)))
665 deleteDirectory(dir
);
667 Files
.createDirectories(originBase
);
669 Path commonBnd
= duDir
.resolve(COMMON_BND
);
670 Properties commonProps
= new Properties();
671 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
672 commonProps
.load(in
);
674 String url
= commonProps
.getProperty(ARGEO_ORIGIN_URI
.toString());
676 url
= uris
.getProperty(duDir
.getFileName().toString());
678 throw new IllegalStateException("No url available for " + duDir
);
679 commonProps
.put(ARGEO_ORIGIN_URI
.toString(), url
);
681 Path downloaded
= tryDownloadArchive(url
, originBase
);
683 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
686 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
687 Properties includes
= new Properties();
688 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
691 for (Object pattern
: includes
.keySet()) {
692 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
693 includeMatchers
.add(pathMatcher
);
696 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
697 Path excludeFile
= duDir
.resolve("excludes.properties");
698 if (Files
.exists(excludeFile
)) {
699 Properties excludes
= new Properties();
700 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
703 for (Object pattern
: excludes
.keySet()) {
704 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
705 excludeMatchers
.add(pathMatcher
);
709 // keys are the bundle directories
710 Map
<Path
, A2Origin
> origins
= new HashMap
<>();
711 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
714 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
715 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
716 if (includeMatcher
.matches(file
)) {
717 for (PathMatcher excludeMatcher
: excludeMatchers
) {
718 if (excludeMatcher
.matches(file
)) {
719 logger
.log(TRACE
, "Skipping excluded " + file
);
720 return FileVisitResult
.CONTINUE
;
723 if (file
.getFileName().toString().contains(".source_")) {
724 processEclipseSourceJar(file
, targetCategoryBase
);
725 logger
.log(DEBUG
, () -> "Processed source " + file
);
727 Map
<String
, String
> map
= new HashMap
<>();
728 for (Object key
: commonProps
.keySet())
729 map
.put(key
.toString(), commonProps
.getProperty(key
.toString()));
730 A2Origin origin
= new A2Origin();
731 Path bundleDir
= processBundleJar(file
, targetCategoryBase
, map
, origin
);
732 origins
.put(bundleDir
, origin
);
733 logger
.log(DEBUG
, () -> "Processed " + file
);
735 break includeMatchers
;
738 return FileVisitResult
.CONTINUE
;
742 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
)
743 && p
.getFileName().toString().indexOf('.') >= 0 && !p
.getFileName().toString().endsWith(".src"));
744 for (Path bundleDir
: dirs
) {
745 A2Origin origin
= origins
.get(bundleDir
);
746 Objects
.requireNonNull(origin
, "No A2 origin found for " + bundleDir
);
747 createJar(bundleDir
, origin
);
749 } catch (IOException e
) {
750 throw new RuntimeException("Cannot process " + duDir
, e
);
755 /** Process sources in Eclipse format. */
756 void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
758 A2Origin origin
= new A2Origin();
760 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
761 Manifest manifest
= jarIn
.getManifest();
763 String
[] relatedBundle
= manifest
.getMainAttributes().getValue(ECLIPSE_SOURCE_BUNDLE
.toString())
765 String version
= relatedBundle
[1].substring("version=\"".length());
766 version
= version
.substring(0, version
.length() - 1);
767 NameVersion nameVersion
= new NameVersion(relatedBundle
[0], version
);
768 bundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
770 Path sourceDir
= sourceBundles ? bundleDir
.getParent().resolve(bundleDir
.toString() + ".src")
771 : bundleDir
.resolve("OSGI-OPT/src");
773 Files
.createDirectories(sourceDir
);
775 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
776 if (entry
.isDirectory())
778 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
780 Path target
= sourceDir
.resolve(entry
.getName());
781 Files
.createDirectories(target
.getParent());
782 Files
.copy(jarIn
, target
);
783 logger
.log(TRACE
, () -> "Copied source " + target
);
788 origin
.appendChanges(sourceDir
);
790 origin
.added
.add("source code under OSGI-OPT/src");
791 origin
.appendChanges(bundleDir
);
794 } catch (IOException e
) {
795 throw new IllegalStateException("Cannot process " + file
, e
);
802 /** Normalise a bundle. */
803 Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
, A2Origin origin
) throws IOException
{
804 boolean embed
= Boolean
.parseBoolean(entries
.getOrDefault(ARGEO_ORIGIN_EMBED
.toString(), "false").toString());
805 NameVersion nameVersion
;
808 boolean isSingleton
= false;
810 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
811 Manifest sourceManifest
= jarIn
.getManifest();
812 manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
814 String rawSourceSymbolicName
= manifest
.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME
.toString());
815 if (rawSourceSymbolicName
!= null) {
816 // make sure there is no directive
817 String
[] arr
= rawSourceSymbolicName
.split(";");
818 for (int i
= 1; i
< arr
.length
; i
++) {
819 if (arr
[i
].trim().equals("singleton:=true"))
821 logger
.log(DEBUG
, file
.getFileName() + " is a singleton");
824 // remove problematic entries in MANIFEST
825 manifest
.getEntries().clear();
827 String ourSymbolicName
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
828 String ourVersion
= entries
.get(BUNDLE_VERSION
.toString());
830 if (ourSymbolicName
!= null && ourVersion
!= null) {
831 nameVersion
= new NameVersion(ourSymbolicName
, ourVersion
);
833 nameVersion
= nameVersionFromManifest(manifest
);
834 if (ourVersion
!= null && !nameVersion
.getVersion().equals(ourVersion
)) {
836 "Original version is " + nameVersion
.getVersion() + " while new version is " + ourVersion
);
837 entries
.put(BUNDLE_VERSION
.toString(), ourVersion
);
839 if (ourSymbolicName
!= null) {
840 // we always force our symbolic name
841 nameVersion
.setName(ourSymbolicName
);
844 bundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
846 if (sourceManifest
!= null) {
847 Path originalManifest
= bundleDir
.resolve(A2_ORIGIN
).resolve("MANIFEST.MF");
848 try (OutputStream out
= Files
.newOutputStream(originalManifest
)) {
849 sourceManifest
.write(null);
851 origin
.added
.add("original MANIFEST (" + bundleDir
.relativize(originalManifest
) + ")");
854 // force Java 9 module name
855 entries
.put(ManifestConstants
.AUTOMATIC_MODULE_NAME
.toString(), nameVersion
.getName());
857 boolean isNative
= false;
860 if (bundleDir
.startsWith(a2LibBase
)) {
862 Path libRelativePath
= a2LibBase
.relativize(bundleDir
);
863 os
= libRelativePath
.getName(0).toString();
864 arch
= libRelativePath
.getName(1).toString();
870 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
871 if (entry
.isDirectory())
873 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF")) {
874 origin
.deleted
.add("cryptographic signatures");
877 if (entry
.getName().endsWith("module-info.class")) { // skip Java 9 module info
878 origin
.deleted
.add("Java module information (module-info.class)");
881 if (entry
.getName().startsWith("META-INF/versions/")) { // skip multi-version
882 origin
.deleted
.add("additional Java versions (META-INF/versions)");
885 if (entry
.getName().startsWith("META-INF/maven/")) {
886 origin
.deleted
.add("Maven information (META-INF/maven)");
889 // skip file system providers as they cause issues with native image
890 if (entry
.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider")) {
892 .add("file system providers (META-INF/services/java.nio.file.spi.FileSystemProvider)");
895 if (entry
.getName().startsWith("OSGI-OPT/src/")) { // skip embedded sources
896 origin
.deleted
.add("embedded sources");
899 Path target
= bundleDir
.resolve(entry
.getName());
900 Files
.createDirectories(target
.getParent());
901 Files
.copy(jarIn
, target
);
904 if (isNative
&& (entry
.getName().endsWith(".so") || entry
.getName().endsWith(".dll")
905 || entry
.getName().endsWith(".jnilib"))) {
906 Path categoryDir
= bundleDir
.getParent();
907 boolean copyDll
= false;
908 Path targetDll
= categoryDir
.resolve(bundleDir
.relativize(target
));
909 if (nameVersion
.getName().equals("com.sun.jna")) {
910 if (arch
.equals("x86_64"))
912 if (os
.equals("macosx"))
914 if (target
.getParent().getFileName().toString().equals(os
+ "-" + arch
)) {
917 targetDll
= categoryDir
.resolve(target
.getFileName());
922 Files
.createDirectories(targetDll
.getParent());
923 if (Files
.exists(targetDll
))
924 Files
.delete(targetDll
);
925 Files
.copy(target
, targetDll
);
927 Files
.delete(target
);
928 origin
.deleted
.add(bundleDir
.relativize(target
).toString());
930 logger
.log(TRACE
, () -> "Copied " + target
);
936 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
937 Files
.createDirectories(manifestPath
.getParent());
939 if (isSingleton
&& entries
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
940 entries
.put(BUNDLE_SYMBOLICNAME
.toString(),
941 entries
.get(BUNDLE_SYMBOLICNAME
.toString()) + ";singleton:=true");
944 if (embed
) {// copy embedded jar
945 Files
.copy(file
, bundleDir
.resolve(file
.getFileName()));
946 entries
.put(ManifestConstants
.BUNDLE_CLASSPATH
.toString(), file
.getFileName().toString());
949 // Final MANIFEST decisions
950 // This also where we check the original OSGi metadata and compare with our
952 for (String key
: entries
.keySet()) {
953 String value
= entries
.get(key
);
954 String previousValue
= manifest
.getMainAttributes().getValue(key
);
955 boolean wasDifferent
= previousValue
!= null && !previousValue
.equals(value
);
956 boolean keepPrevious
= false;
958 if (SPDX_LICENSE_IDENTIFIER
.toString().equals(key
) && previousValue
!= null)
960 else if (BUNDLE_VERSION
.toString().equals(key
) && wasDifferent
)
961 if (previousValue
.equals(value
+ ".0")) // typically a Maven first release
965 if (logger
.isLoggable(DEBUG
))
966 logger
.log(DEBUG
, file
.getFileName() + ": " + key
+ " was NOT modified, value kept is "
967 + previousValue
+ ", not overriden with " + value
);
968 value
= previousValue
;
972 manifest
.getMainAttributes().putValue(key
, value
);
973 if (wasDifferent
&& !keepPrevious
) {
974 if (IMPORT_PACKAGE
.toString().equals(key
) || EXPORT_PACKAGE
.toString().equals(key
))
975 logger
.log(TRACE
, () -> file
.getFileName() + ": " + key
+ " was modified");
978 file
.getFileName() + ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
981 // de-pollute MANIFEST
983 case "Archiver-Version":
986 case "Originally-Created-By":
988 case "Bnd-LastModified":
989 manifest
.getMainAttributes().remove(key
);
991 default: // do nothing
994 // !! hack to remove unresolvable
995 if (key
.equals("Provide-Capability") || key
.equals("Require-Capability"))
996 if (nameVersion
.getName().equals("osgi.core") || nameVersion
.getName().equals("osgi.cmpn")) {
997 manifest
.getMainAttributes().remove(key
);
1002 String spdxLicenceId
= manifest
.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER
.toString());
1003 String bundleLicense
= manifest
.getMainAttributes().getValue(BUNDLE_LICENSE
.toString());
1004 if (spdxLicenceId
== null) {
1005 logger
.log(ERROR
, file
.getFileName() + ": " + SPDX_LICENSE_IDENTIFIER
+ " not available, " + BUNDLE_LICENSE
1006 + " is " + bundleLicense
);
1008 if (!licensesUsed
.containsKey(spdxLicenceId
))
1009 licensesUsed
.put(spdxLicenceId
, new TreeSet
<>());
1010 licensesUsed
.get(spdxLicenceId
).add(nameVersion
.toString());
1013 origin
.modified
.add("jar MANIFEST (META-INF/MANIFEST.MF)");
1014 // write the MANIFEST
1015 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
1016 manifest
.write(out
);
1024 /** Recursively deletes a directory. */
1025 static void deleteDirectory(Path path
) throws IOException
{
1026 if (!Files
.exists(path
))
1028 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
1030 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
1033 Files
.delete(directory
);
1038 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1045 /** Extract name/version from a MANIFEST. */
1046 NameVersion
nameVersionFromManifest(Manifest manifest
) {
1047 Attributes attrs
= manifest
.getMainAttributes();
1049 String symbolicName
= attrs
.getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
1050 if (symbolicName
== null)
1052 // make sure there is no directive
1053 symbolicName
= symbolicName
.split(";")[0];
1055 String version
= attrs
.getValue(ManifestConstants
.BUNDLE_VERSION
.toString());
1056 return new NameVersion(symbolicName
, version
);
1059 /** Try to download from an URI. */
1060 Path
tryDownloadArchive(String uri
, Path dir
) throws IOException
{
1062 List
<String
> urlBases
= null;
1063 String uriPrefix
= null;
1064 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
1065 if (uri
.startsWith(uriPref
)) {
1066 if (mirrors
.get(uriPref
).size() > 0) {
1067 urlBases
= mirrors
.get(uriPref
);
1068 uriPrefix
= uriPref
;
1073 if (urlBases
== null)
1075 return downloadArchive(new URL(uri
), dir
);
1076 } catch (FileNotFoundException e
) {
1077 throw new FileNotFoundException("Cannot find " + uri
);
1081 for (String urlBase
: urlBases
) {
1082 String relativePath
= uri
.substring(uriPrefix
.length());
1083 URL url
= new URL(urlBase
+ relativePath
);
1085 return downloadArchive(url
, dir
);
1086 } catch (FileNotFoundException e
) {
1087 logger
.log(WARNING
, "Cannot download " + url
+ ", trying another mirror");
1090 throw new FileNotFoundException("Cannot find " + uri
);
1094 * Effectively download. Synchronised in order to avoid downloading twice in
1097 synchronized Path
downloadArchive(URL url
, Path dir
) throws IOException
{
1098 return download(url
, dir
, (String
) null);
1101 /** Effectively download. */
1102 Path
download(URL url
, Path dir
, String name
) throws IOException
{
1106 // We use also use parent directory in case the archive itself has a fixed name
1107 String
[] segments
= url
.getPath().split("/");
1108 name
= segments
.length
> 1 ? segments
[segments
.length
- 2] + '-' + segments
[segments
.length
- 1]
1109 : segments
[segments
.length
- 1];
1112 dest
= dir
.resolve(name
);
1113 if (Files
.exists(dest
)) {
1114 logger
.log(TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
1117 Files
.createDirectories(dest
.getParent());
1120 try (InputStream in
= url
.openStream()) {
1121 Files
.copy(in
, dest
);
1122 logger
.log(DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
1127 /** Create a JAR file from a directory. */
1128 Path
createJar(Path bundleDir
, A2Origin origin
) throws IOException
{
1130 origin
.appendChanges(bundleDir
);
1132 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
1133 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
1135 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
1136 manifest
= new Manifest(in
);
1138 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
1139 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
1140 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
1143 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1144 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1145 return super.visitFile(file
, attrs
);
1146 JarEntry entry
= new JarEntry(
1147 bundleDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1148 jarOut
.putNextEntry(entry
);
1149 Files
.copy(file
, jarOut
);
1150 return super.visitFile(file
, attrs
);
1155 deleteDirectory(bundleDir
);
1157 if (sourceBundles
) {
1158 Path bundleCategoryDir
= bundleDir
.getParent();
1159 Path sourceDir
= bundleCategoryDir
.resolve(bundleDir
.toString() + ".src");
1160 if (!Files
.exists(sourceDir
)) {
1161 logger
.log(WARNING
, sourceDir
+ " does not exist, skipping...");
1166 Path relPath
= a2Base
.relativize(bundleCategoryDir
);
1167 Path srcCategoryDir
= a2SrcBase
.resolve(relPath
);
1168 Path srcJarP
= srcCategoryDir
.resolve(sourceDir
.getFileName() + ".jar");
1169 Files
.createDirectories(srcJarP
.getParent());
1171 String bundleSymbolicName
= manifest
.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1172 // in case there are additional directives
1173 bundleSymbolicName
= bundleSymbolicName
.split(";")[0];
1174 Manifest srcManifest
= new Manifest();
1175 srcManifest
.getMainAttributes().put(MANIFEST_VERSION
, "1.0");
1176 srcManifest
.getMainAttributes().putValue(BUNDLE_SYMBOLICNAME
.toString(), bundleSymbolicName
+ ".src");
1177 srcManifest
.getMainAttributes().putValue(BUNDLE_VERSION
.toString(),
1178 manifest
.getMainAttributes().getValue(BUNDLE_VERSION
.toString()).toString());
1179 srcManifest
.getMainAttributes().putValue(ECLIPSE_SOURCE_BUNDLE
.toString(), bundleSymbolicName
1180 + ";version=\"" + manifest
.getMainAttributes().getValue(BUNDLE_VERSION
.toString()));
1182 try (JarOutputStream srcJarOut
= new JarOutputStream(Files
.newOutputStream(srcJarP
), srcManifest
)) {
1183 srcJarOut
.setLevel(Deflater
.BEST_COMPRESSION
);
1184 Files
.walkFileTree(sourceDir
, new SimpleFileVisitor
<Path
>() {
1187 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
1188 if (file
.getFileName().toString().equals("MANIFEST.MF"))
1189 return super.visitFile(file
, attrs
);
1190 JarEntry entry
= new JarEntry(
1191 sourceDir
.relativize(file
).toString().replace(File
.separatorChar
, '/'));
1192 srcJarOut
.putNextEntry(entry
);
1193 Files
.copy(file
, srcJarOut
);
1194 return super.visitFile(file
, attrs
);
1199 deleteDirectory(sourceDir
);
1205 /** MANIFEST headers. */
1206 enum ManifestConstants
{
1208 /** OSGi bundle symbolic name. */
1209 BUNDLE_SYMBOLICNAME("Bundle-SymbolicName"), //
1210 /** OSGi bundle version. */
1211 BUNDLE_VERSION("Bundle-Version"), //
1212 /** OSGi bundle license. */
1213 BUNDLE_LICENSE("Bundle-License"), //
1214 /** OSGi exported packages list. */
1215 EXPORT_PACKAGE("Export-Package"), //
1216 /** OSGi imported packages list. */
1217 IMPORT_PACKAGE("Import-Package"), //
1218 /** OSGi path to embedded jar. */
1219 BUNDLE_CLASSPATH("Bundle-Classpath"), //
1221 /** Java module name. */
1222 AUTOMATIC_MODULE_NAME("Automatic-Module-Name"), //
1224 /** Eclipse source bundle. */
1225 ECLIPSE_SOURCE_BUNDLE("Eclipse-SourceBundle"), //
1228 * SPDX license identifier.
1230 * @see https://spdx.org/licenses/
1232 SPDX_LICENSE_IDENTIFIER("SPDX-License-Identifier"), //
1235 * Maven coordinates of the origin, possibly partial when using common.bnd or
1238 ARGEO_ORIGIN_M2("Argeo-Origin-M2"), //
1239 /** List of Maven coordinates to merge. */
1240 ARGEO_ORIGIN_M2_MERGE("Argeo-Origin-M2-Merge"), //
1241 /** Maven repository, if not the default one. */
1242 ARGEO_ORIGIN_M2_REPO("Argeo-Origin-M2-Repo"), //
1244 * Do not perform BND analysis of the origin component. Typically IMport_package
1245 * and Export-Package will be kept untouched.
1247 ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED("Argeo-Origin-ManifestNotModified"), //
1249 * Embed the original jar without modifying it (may be required by some
1250 * proprietary licenses, such as JCR Day License).
1252 ARGEO_ORIGIN_EMBED("Argeo-Origin-Embed"), //
1254 * Origin (non-Maven) URI of the component. It may be anything (jar, archive,
1257 ARGEO_ORIGIN_URI("Argeo-Origin-URI"), //
1262 private ManifestConstants(String value
) {
1267 public String
toString() {
1274 * Gathers modifications performed on the original binaries and sources,
1275 * especially in order to comply with their license requirements.
1278 Set
<String
> modified
= new TreeSet
<>();
1279 Set
<String
> deleted
= new TreeSet
<>();
1280 Set
<String
> added
= new TreeSet
<>();
1281 Set
<String
> moved
= new TreeSet
<>();
1283 /** Append changes to the A2-ORIGIN/changes file. */
1284 void appendChanges(Path baseDirectory
) throws IOException
{
1285 Path changesFile
= baseDirectory
.resolve("A2-ORIGIN/changes");
1286 Files
.createDirectories(changesFile
.getParent());
1287 try (BufferedWriter writer
= Files
.newBufferedWriter(changesFile
, StandardOpenOption
.APPEND
,
1288 StandardOpenOption
.CREATE
)) {
1289 for (String msg
: added
)
1290 writer
.write("- Added " + msg
+ ".\n");
1291 for (String msg
: modified
)
1292 writer
.write("- Modified " + msg
+ ".\n");
1293 for (String msg
: moved
)
1294 writer
.write("- Moved " + msg
+ ".\n");
1295 for (String msg
: deleted
)
1296 writer
.write("- Deleted " + msg
+ ".\n");
1301 /** Simple representation of an M2 artifact. */
1302 class M2Artifact
extends CategoryNameVersion
{
1303 private String classifier
;
1305 M2Artifact(String m2coordinates
) {
1306 this(m2coordinates
, null);
1309 M2Artifact(String m2coordinates
, String classifier
) {
1310 String
[] parts
= m2coordinates
.split(":");
1311 setCategory(parts
[0]);
1313 if (parts
.length
> 2) {
1314 setVersion(parts
[2]);
1316 this.classifier
= classifier
;
1319 String
getGroupId() {
1320 return super.getCategory();
1323 String
getArtifactId() {
1324 return super.getName();
1327 String
toM2Coordinates() {
1328 return getCategory() + ":" + getName() + (getVersion() != null ?
":" + getVersion() : "");
1331 String
getClassifier() {
1332 return classifier
!= null ? classifier
: "";
1335 String
getExtension() {
1340 /** Utilities around Maven (conventions based). */
1341 class M2ConventionsUtils
{
1342 final static String MAVEN_CENTRAL_BASE_URL
= "https://repo1.maven.org/maven2/";
1344 /** The file name of this artifact when stored */
1345 static String
artifactFileName(M2Artifact artifact
) {
1346 return artifact
.getArtifactId() + '-' + artifact
.getVersion()
1347 + (artifact
.getClassifier().equals("") ?
"" : '-' + artifact
.getClassifier()) + '.'
1348 + artifact
.getExtension();
1351 /** Absolute path to the file */
1352 static String
artifactPath(String artifactBasePath
, M2Artifact artifact
) {
1353 return artifactParentPath(artifactBasePath
, artifact
) + '/' + artifactFileName(artifact
);
1356 /** Absolute path to the file */
1357 static String
artifactUrl(String repoUrl
, M2Artifact artifact
) {
1358 if (repoUrl
.endsWith("/"))
1359 return repoUrl
+ artifactPath("/", artifact
).substring(1);
1361 return repoUrl
+ artifactPath("/", artifact
);
1364 /** Absolute path to the file */
1365 static URL
mavenRepoUrl(String repoBase
, M2Artifact artifact
) {
1366 String url
= artifactUrl(repoBase
== null ? MAVEN_CENTRAL_BASE_URL
: repoBase
, artifact
);
1368 return new URL(url
);
1369 } catch (MalformedURLException e
) {
1370 // it should not happen
1371 throw new IllegalStateException(e
);
1375 /** Absolute path to the directories where the files will be stored */
1376 static String
artifactParentPath(String artifactBasePath
, M2Artifact artifact
) {
1377 return artifactBasePath
+ (artifactBasePath
.endsWith("/") ?
"" : "/") + artifactParentPath(artifact
);
1380 /** Relative path to the directories where the files will be stored */
1381 static String
artifactParentPath(M2Artifact artifact
) {
1382 return artifact
.getGroupId().replace('.', '/') + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion();
1386 private M2ConventionsUtils() {
1390 /** Combination of a category, a name and a version. */
1391 class CategoryNameVersion
extends NameVersion
{
1392 private String category
;
1394 CategoryNameVersion() {
1397 CategoryNameVersion(String category
, String name
, String version
) {
1398 super(name
, version
);
1399 this.category
= category
;
1402 CategoryNameVersion(String category
, NameVersion nameVersion
) {
1404 this.category
= category
;
1407 String
getCategory() {
1411 void setCategory(String category
) {
1412 this.category
= category
;
1416 public String
toString() {
1417 return category
+ ":" + super.toString();
1422 /** Combination of a name and a version. */
1423 class NameVersion
implements Comparable
<NameVersion
> {
1424 private String name
;
1425 private String version
;
1430 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1431 NameVersion(String nameVersion
) {
1432 int index
= nameVersion
.indexOf(";version=");
1434 setName(nameVersion
);
1437 setName(nameVersion
.substring(0, index
));
1438 setVersion(nameVersion
.substring(index
+ ";version=".length()));
1442 NameVersion(String name
, String version
) {
1444 this.version
= version
;
1447 NameVersion(NameVersion nameVersion
) {
1448 this.name
= nameVersion
.getName();
1449 this.version
= nameVersion
.getVersion();
1456 void setName(String name
) {
1460 String
getVersion() {
1464 void setVersion(String version
) {
1465 this.version
= version
;
1468 String
getBranch() {
1469 String
[] parts
= getVersion().split("\\.");
1470 if (parts
.length
< 2)
1471 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1472 return parts
[0] + "." + parts
[1];
1476 public boolean equals(Object obj
) {
1477 if (obj
instanceof NameVersion
) {
1478 NameVersion nameVersion
= (NameVersion
) obj
;
1479 return name
.equals(nameVersion
.getName()) && version
.equals(nameVersion
.getVersion());
1485 public int hashCode() {
1486 return name
.hashCode();
1490 public String
toString() {
1491 return name
+ ":" + version
;
1494 public int compareTo(NameVersion o
) {
1495 if (o
.getName().equals(name
))
1496 return version
.compareTo(o
.getVersion());
1498 return name
.compareTo(o
.getName());