1 package org
.argeo
.build
;
3 import static java
.lang
.System
.Logger
.Level
.DEBUG
;
4 import static org
.argeo
.build
.Repackage
.ManifestConstants
.BUNDLE_SYMBOLICNAME
;
5 import static org
.argeo
.build
.Repackage
.ManifestConstants
.BUNDLE_VERSION
;
6 import static org
.argeo
.build
.Repackage
.ManifestConstants
.EXPORT_PACKAGE
;
7 import static org
.argeo
.build
.Repackage
.ManifestConstants
.SLC_ORIGIN_M2
;
8 import static org
.argeo
.build
.Repackage
.ManifestConstants
.SLC_ORIGIN_M2_REPO
;
10 import java
.io
.FileNotFoundException
;
11 import java
.io
.IOException
;
12 import java
.io
.InputStream
;
13 import java
.io
.OutputStream
;
14 import java
.lang
.System
.Logger
;
15 import java
.lang
.System
.Logger
.Level
;
16 import java
.net
.MalformedURLException
;
18 import java
.nio
.charset
.StandardCharsets
;
19 import java
.nio
.file
.DirectoryStream
;
20 import java
.nio
.file
.FileSystem
;
21 import java
.nio
.file
.FileSystems
;
22 import java
.nio
.file
.FileVisitResult
;
23 import java
.nio
.file
.Files
;
24 import java
.nio
.file
.Path
;
25 import java
.nio
.file
.PathMatcher
;
26 import java
.nio
.file
.Paths
;
27 import java
.nio
.file
.SimpleFileVisitor
;
28 import java
.nio
.file
.StandardOpenOption
;
29 import java
.nio
.file
.attribute
.BasicFileAttributes
;
30 import java
.util
.ArrayList
;
31 import java
.util
.HashMap
;
32 import java
.util
.Iterator
;
33 import java
.util
.List
;
35 import java
.util
.Objects
;
36 import java
.util
.Properties
;
37 import java
.util
.TreeMap
;
38 import java
.util
.concurrent
.CompletableFuture
;
39 import java
.util
.jar
.Attributes
;
40 import java
.util
.jar
.JarEntry
;
41 import java
.util
.jar
.JarInputStream
;
42 import java
.util
.jar
.JarOutputStream
;
43 import java
.util
.jar
.Manifest
;
44 import java
.util
.zip
.Deflater
;
46 import aQute
.bnd
.osgi
.Analyzer
;
47 import aQute
.bnd
.osgi
.Jar
;
49 /** The central class for A2 packaging. */
50 public class Repackage
{
51 private final static Logger logger
= System
.getLogger(Repackage
.class.getName());
53 private final static String ENV_BUILD_SOURCE_BUNDLES
= "BUILD_SOURCE_BUNDLES";
55 /** Main entry point. */
56 public static void main(String
[] args
) {
57 if (args
.length
< 2) {
58 System
.err
.println("Usage: <path to a2 output dir> <category1> <category2> ...");
61 Path a2Base
= Paths
.get(args
[0]).toAbsolutePath().normalize();
62 Path descriptorsBase
= Paths
.get(".").toAbsolutePath().normalize();
63 Repackage factory
= new Repackage(a2Base
, descriptorsBase
);
65 List
<CompletableFuture
<Void
>> toDos
= new ArrayList
<>();
66 for (int i
= 1; i
< args
.length
; i
++) {
67 Path p
= Paths
.get(args
[i
]);
68 toDos
.add(CompletableFuture
.runAsync(() -> factory
.processCategory(p
)));
70 CompletableFuture
.allOf(toDos
.toArray(new CompletableFuture
[toDos
.size()])).join();
73 private final static String COMMON_BND
= "common.bnd";
74 private final static String MERGE_BND
= "merge.bnd";
76 private Path originBase
;
78 private Path a2LibBase
;
79 private Path descriptorsBase
;
81 private Properties uris
= new Properties();
83 /** key is URI prefix, value list of base URLs */
84 private Map
<String
, List
<String
>> mirrors
= new HashMap
<String
, List
<String
>>();
86 private final boolean sourceBundles
;
88 public Repackage(Path a2Base
, Path descriptorsBase
) {
89 sourceBundles
= Boolean
.parseBoolean(System
.getenv(ENV_BUILD_SOURCE_BUNDLES
));
91 logger
.log(Level
.INFO
, "Sources will be packaged separately");
93 Objects
.requireNonNull(a2Base
);
94 Objects
.requireNonNull(descriptorsBase
);
95 this.originBase
= Paths
.get(System
.getProperty("user.home"), ".cache", "argeo/build/origin");
96 // TODO define and use a build base
98 this.a2LibBase
= a2Base
.resolve("lib");
99 this.descriptorsBase
= descriptorsBase
;
100 if (!Files
.exists(this.descriptorsBase
))
101 throw new IllegalArgumentException(this.descriptorsBase
+ " does not exist");
104 Path urisPath
= this.descriptorsBase
.resolve("uris.properties");
105 if (Files
.exists(urisPath
)) {
106 try (InputStream in
= Files
.newInputStream(urisPath
)) {
108 } catch (IOException e
) {
109 throw new IllegalStateException("Cannot load " + urisPath
, e
);
114 Path eclipseMirrorsPath
= this.descriptorsBase
.resolve("eclipse.mirrors.txt");
115 List
<String
> eclipseMirrors
= new ArrayList
<>();
116 if (Files
.exists(eclipseMirrorsPath
)) {
118 eclipseMirrors
= Files
.readAllLines(eclipseMirrorsPath
, StandardCharsets
.UTF_8
);
119 } catch (IOException e
) {
120 throw new IllegalStateException("Cannot load " + eclipseMirrorsPath
, e
);
122 for (Iterator
<String
> it
= eclipseMirrors
.iterator(); it
.hasNext();) {
123 String value
= it
.next();
124 if (value
.strip().equals(""))
129 mirrors
.put("http://www.eclipse.org/downloads", eclipseMirrors
);
136 /** Process a whole category/group id. */
137 public void processCategory(Path categoryRelativePath
) {
139 Path targetCategoryBase
= descriptorsBase
.resolve(categoryRelativePath
);
140 DirectoryStream
<Path
> bnds
= Files
.newDirectoryStream(targetCategoryBase
,
141 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
142 && !p
.getFileName().toString().equals(MERGE_BND
));
143 for (Path p
: bnds
) {
144 processSingleM2ArtifactDistributionUnit(p
);
147 DirectoryStream
<Path
> dus
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
148 for (Path duDir
: dus
) {
149 if (duDir
.getFileName().toString().startsWith("eclipse-")) {
150 processEclipseArchive(duDir
);
152 processM2BasedDistributionUnit(duDir
);
155 } catch (IOException e
) {
156 throw new RuntimeException("Cannot process category " + categoryRelativePath
, e
);
160 /** Process a standalone Maven artifact. */
161 public void processSingleM2ArtifactDistributionUnit(Path bndFile
) {
163 // String category = bndFile.getParent().getFileName().toString();
164 Path categoryRelativePath
= descriptorsBase
.relativize(bndFile
.getParent());
165 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
167 Properties fileProps
= new Properties();
168 try (InputStream in
= Files
.newInputStream(bndFile
)) {
171 String repoStr
= fileProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
172 ? fileProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
175 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
176 // use file name as symbolic name
177 String symbolicName
= bndFile
.getFileName().toString();
178 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
179 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
182 String m2Coordinates
= fileProps
.getProperty(SLC_ORIGIN_M2
.toString());
183 if (m2Coordinates
== null)
184 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile
);
185 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
186 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
187 Path downloaded
= download(url
, originBase
, artifact
);
189 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, fileProps
, artifact
);
191 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
193 createJar(targetBundleDir
);
194 } catch (Exception e
) {
195 throw new RuntimeException("Cannot process " + bndFile
, e
);
199 /** Process multiple Maven artifacts. */
200 public void processM2BasedDistributionUnit(Path duDir
) {
202 // String category = duDir.getParent().getFileName().toString();
203 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
204 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
207 Path mergeBnd
= duDir
.resolve(MERGE_BND
);
208 if (Files
.exists(mergeBnd
)) {
209 mergeM2Artifacts(mergeBnd
);
213 Path commonBnd
= duDir
.resolve(COMMON_BND
);
214 if (!Files
.exists(commonBnd
)) {
217 Properties commonProps
= new Properties();
218 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
219 commonProps
.load(in
);
222 String m2Version
= commonProps
.getProperty(SLC_ORIGIN_M2
.toString());
223 if (m2Version
== null) {
224 logger
.log(Level
.WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
225 return;// ignore, this is probably an Eclipse archive
227 if (!m2Version
.startsWith(":")) {
228 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
230 m2Version
= m2Version
.substring(1);
232 DirectoryStream
<Path
> ds
= Files
.newDirectoryStream(duDir
,
233 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
234 && !p
.getFileName().toString().equals(MERGE_BND
));
236 Properties fileProps
= new Properties();
237 try (InputStream in
= Files
.newInputStream(p
)) {
240 String m2Coordinates
= fileProps
.getProperty(SLC_ORIGIN_M2
.toString());
241 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
243 artifact
.setVersion(m2Version
);
245 // prepare manifest entries
246 Properties mergeProps
= new Properties();
247 mergeProps
.putAll(commonProps
);
249 fileEntries
: for (Object key
: fileProps
.keySet()) {
250 if (ManifestConstants
.SLC_ORIGIN_M2
.toString().equals(key
))
251 continue fileEntries
;
252 String value
= fileProps
.getProperty(key
.toString());
253 Object previousValue
= mergeProps
.put(key
.toString(), value
);
254 if (previousValue
!= null) {
255 logger
.log(Level
.WARNING
,
256 commonBnd
+ ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
259 mergeProps
.put(ManifestConstants
.SLC_ORIGIN_M2
.toString(), artifact
.toM2Coordinates());
260 if (!mergeProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
261 // use file name as symbolic name
262 String symbolicName
= p
.getFileName().toString();
263 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
264 mergeProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
267 String repoStr
= mergeProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
268 ? mergeProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
272 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
273 Path downloaded
= download(url
, originBase
, artifact
);
275 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, mergeProps
, artifact
);
276 // logger.log(Level.DEBUG, () -> "Processed " + downloaded);
279 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
281 createJar(targetBundleDir
);
283 } catch (IOException e
) {
284 throw new RuntimeException("Cannot process " + duDir
, e
);
289 /** Merge multiple Maven artifacts. */
290 protected void mergeM2Artifacts(Path mergeBnd
) throws IOException
{
291 Path duDir
= mergeBnd
.getParent();
292 String category
= duDir
.getParent().getFileName().toString();
293 Path targetCategoryBase
= a2Base
.resolve(category
);
295 Properties mergeProps
= new Properties();
296 try (InputStream in
= Files
.newInputStream(mergeBnd
)) {
301 String m2Version
= mergeProps
.getProperty(SLC_ORIGIN_M2
.toString());
302 if (m2Version
== null) {
303 logger
.log(Level
.WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
304 return;// ignore, this is probably an Eclipse archive
306 if (!m2Version
.startsWith(":")) {
307 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
309 m2Version
= m2Version
.substring(1);
310 mergeProps
.put(ManifestConstants
.BUNDLE_VERSION
.toString(), m2Version
);
312 String artifactsStr
= mergeProps
.getProperty(ManifestConstants
.SLC_ORIGIN_M2_MERGE
.toString());
313 String repoStr
= mergeProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
314 ? mergeProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
317 String bundleSymbolicName
= mergeProps
.getProperty(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
318 if (bundleSymbolicName
== null)
319 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd
);
320 CategoryNameVersion nameVersion
= new M2Artifact(category
+ ":" + bundleSymbolicName
+ ":" + m2Version
);
321 Path targetBundleDir
= targetCategoryBase
.resolve(bundleSymbolicName
+ "." + nameVersion
.getBranch());
323 String
[] artifacts
= artifactsStr
.split(",");
324 artifacts
: for (String str
: artifacts
) {
325 String m2Coordinates
= str
.trim();
326 if ("".equals(m2Coordinates
))
328 M2Artifact artifact
= new M2Artifact(m2Coordinates
.trim());
329 if (artifact
.getVersion() == null)
330 artifact
.setVersion(m2Version
);
331 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
332 Path downloaded
= download(url
, originBase
, artifact
);
334 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(downloaded
), false)) {
335 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
336 if (entry
.isDirectory())
338 else if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
340 else if (entry
.getName().startsWith("META-INF/versions/"))
342 else if (entry
.getName().startsWith("META-INF/maven/"))
344 else if (entry
.getName().equals("module-info.class"))
346 else if (entry
.getName().equals("META-INF/NOTICE"))
348 else if (entry
.getName().equals("META-INF/NOTICE.txt"))
350 else if (entry
.getName().equals("META-INF/LICENSE"))
352 else if (entry
.getName().equals("META-INF/LICENSE.md"))
354 else if (entry
.getName().equals("META-INF/LICENSE-notice.md"))
356 else if (entry
.getName().equals("META-INF/DEPENDENCIES"))
358 if (entry
.getName().startsWith(".cache/")) // Apache SSHD
360 Path target
= targetBundleDir
.resolve(entry
.getName());
361 Files
.createDirectories(target
.getParent());
362 if (!Files
.exists(target
)) {
363 Files
.copy(jarIn
, target
);
365 if (entry
.getName().startsWith("META-INF/services/")) {
366 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
367 out
.write("\n".getBytes());
368 jarIn
.transferTo(out
);
369 if (logger
.isLoggable(DEBUG
))
370 logger
.log(DEBUG
, artifact
.getArtifactId() + " - Appended " + entry
.getName());
372 } else if (entry
.getName().startsWith("org/apache/batik/")) {
373 logger
.log(Level
.WARNING
, "Skip " + entry
.getName());
376 throw new IllegalStateException("File " + target
+ " from " + artifact
+ " already exists");
379 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
383 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
386 // additional service files
387 Path servicesDir
= duDir
.resolve("services");
388 if (Files
.exists(servicesDir
)) {
389 for (Path p
: Files
.newDirectoryStream(servicesDir
)) {
390 Path target
= targetBundleDir
.resolve("META-INF/services/").resolve(p
.getFileName());
391 try (InputStream in
= Files
.newInputStream(p
);
392 OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
);) {
393 out
.write("\n".getBytes());
395 if (logger
.isLoggable(DEBUG
))
396 logger
.log(DEBUG
, "Appended " + p
);
401 Map
<String
, String
> entries
= new TreeMap
<>();
402 try (Analyzer bndAnalyzer
= new Analyzer()) {
403 bndAnalyzer
.setProperties(mergeProps
);
404 Jar jar
= new Jar(targetBundleDir
.toFile());
405 bndAnalyzer
.setJar(jar
);
406 Manifest manifest
= bndAnalyzer
.calcManifest();
408 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
409 Object value
= manifest
.getMainAttributes().get(key
);
411 switch (key
.toString()) {
413 case "Bnd-LastModified":
417 if ("Require-Capability".equals(key
.toString())
418 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
419 continue keys
;// hack for very old classes
420 entries
.put(key
.toString(), value
.toString());
421 // logger.log(DEBUG, () -> key + "=" + value);
424 } catch (Exception e
) {
425 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
428 Manifest manifest
= new Manifest();
429 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
430 Files
.createDirectories(manifestPath
.getParent());
431 for (String key
: entries
.keySet()) {
432 String value
= entries
.get(key
);
433 manifest
.getMainAttributes().putValue(key
, value
);
436 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
439 createJar(targetBundleDir
);
442 /** Generate MANIFEST using BND. */
443 protected Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
, M2Artifact artifact
) {
446 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
447 boolean doNotModify
= Boolean
.parseBoolean(fileProps
448 .getOrDefault(ManifestConstants
.SLC_ORIGIN_MANIFEST_NOT_MODIFIED
.toString(), "false").toString());
450 // we always force the symbolic name
453 fileEntries
: for (Object key
: fileProps
.keySet()) {
454 if (ManifestConstants
.SLC_ORIGIN_M2
.toString().equals(key
))
455 continue fileEntries
;
456 String value
= fileProps
.getProperty(key
.toString());
457 additionalEntries
.put(key
.toString(), value
);
460 if (artifact
!= null) {
461 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
462 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
464 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
465 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
469 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
470 fileProps
.put(EXPORT_PACKAGE
.toString(),
471 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
474 try (Analyzer bndAnalyzer
= new Analyzer()) {
475 bndAnalyzer
.setProperties(fileProps
);
476 Jar jar
= new Jar(downloaded
.toFile());
477 bndAnalyzer
.setJar(jar
);
478 Manifest manifest
= bndAnalyzer
.calcManifest();
480 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
481 Object value
= manifest
.getMainAttributes().get(key
);
483 switch (key
.toString()) {
485 case "Bnd-LastModified":
489 if ("Require-Capability".equals(key
.toString())
490 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
491 continue keys
;// hack for very old classes
492 additionalEntries
.put(key
.toString(), value
.toString());
493 // logger.log(DEBUG, () -> key + "=" + value);
498 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
);
499 logger
.log(Level
.DEBUG
, () -> "Processed " + downloaded
);
500 return targetBundleDir
;
501 } catch (Exception e
) {
502 throw new RuntimeException("Cannot BND process " + downloaded
, e
);
507 /** Download and integrates sources for a single Maven artifact. */
508 protected void downloadAndProcessM2Sources(String repoStr
, M2Artifact artifact
, Path targetBundleDir
)
512 M2Artifact sourcesArtifact
= new M2Artifact(artifact
.toM2Coordinates(), "sources");
513 URL sourcesUrl
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
514 Path sourcesDownloaded
= download(sourcesUrl
, originBase
, artifact
, true);
515 processM2SourceJar(sourcesDownloaded
, targetBundleDir
);
516 logger
.log(Level
.TRACE
, () -> "Processed source " + sourcesDownloaded
);
520 /** Integrate sources from a downloaded jar file. */
521 protected void processM2SourceJar(Path file
, Path targetBundleDir
) throws IOException
{
522 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
523 Path targetSourceDir
= targetBundleDir
.resolve("OSGI-OPT/src");
525 // TODO make it less dangerous?
526 if (Files
.exists(targetSourceDir
)) {
527 // deleteDirectory(targetSourceDir);
529 Files
.createDirectories(targetSourceDir
);
534 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
535 if (entry
.isDirectory())
537 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
539 if (entry
.getName().startsWith("module-info.java"))// skip META-INF entries
541 if (entry
.getName().startsWith("/")) // absolute paths
543 Path target
= targetSourceDir
.resolve(entry
.getName());
544 Files
.createDirectories(target
.getParent());
545 if (!Files
.exists(target
)) {
546 Files
.copy(jarIn
, target
);
547 logger
.log(Level
.TRACE
, () -> "Copied source " + target
);
549 logger
.log(Level
.WARNING
, () -> target
+ " already exists, skipping...");
556 /** Download a Maven artifact. */
557 protected Path
download(URL url
, Path dir
, M2Artifact artifact
) throws IOException
{
558 return download(url
, dir
, artifact
, false);
561 /** Download a Maven artifact. */
562 protected Path
download(URL url
, Path dir
, M2Artifact artifact
, boolean sources
) throws IOException
{
563 return download(url
, dir
, artifact
.getGroupId() + '/' + artifact
.getArtifactId() + "-" + artifact
.getVersion()
564 + (sources ?
"-sources" : "") + ".jar");
571 /** Process an archive in Eclipse format. */
572 public void processEclipseArchive(Path duDir
) {
574 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
575 // String category = categoryRelativePath.getFileName().toString();
576 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
577 Files
.createDirectories(targetCategoryBase
);
578 // first delete all directories from previous builds
579 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
))) {
580 deleteDirectory(dir
);
583 Files
.createDirectories(originBase
);
585 Path commonBnd
= duDir
.resolve(COMMON_BND
);
586 Properties commonProps
= new Properties();
587 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
588 commonProps
.load(in
);
590 String url
= commonProps
.getProperty(ManifestConstants
.SLC_ORIGIN_URI
.toString());
592 url
= uris
.getProperty(duDir
.getFileName().toString());
594 throw new IllegalStateException("No url available for " + duDir
);
595 commonProps
.put(ManifestConstants
.SLC_ORIGIN_URI
.toString(), url
);
597 Path downloaded
= tryDownload(url
, originBase
);
599 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
602 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
603 Properties includes
= new Properties();
604 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
607 for (Object pattern
: includes
.keySet()) {
608 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
609 includeMatchers
.add(pathMatcher
);
612 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
613 Path excludeFile
= duDir
.resolve("excludes.properties");
614 if (Files
.exists(excludeFile
)) {
615 Properties excludes
= new Properties();
616 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
619 for (Object pattern
: excludes
.keySet()) {
620 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
621 excludeMatchers
.add(pathMatcher
);
625 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
628 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
629 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
630 if (includeMatcher
.matches(file
)) {
631 for (PathMatcher excludeMatcher
: excludeMatchers
) {
632 if (excludeMatcher
.matches(file
)) {
633 logger
.log(Level
.TRACE
, "Skipping excluded " + file
);
634 return FileVisitResult
.CONTINUE
;
637 if (file
.getFileName().toString().contains(".source_")) {
638 if (!sourceBundles
) {
639 processEclipseSourceJar(file
, targetCategoryBase
);
640 logger
.log(Level
.DEBUG
, () -> "Processed source " + file
);
644 Map
<String
, String
> map
= new HashMap
<>();
645 for (Object key
: commonProps
.keySet())
646 map
.put(key
.toString(), commonProps
.getProperty(key
.toString()));
647 processBundleJar(file
, targetCategoryBase
, map
);
648 logger
.log(Level
.DEBUG
, () -> "Processed " + file
);
650 break includeMatchers
;
653 return FileVisitResult
.CONTINUE
;
657 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
,
658 (p
) -> Files
.isDirectory(p
) && p
.getFileName().toString().indexOf('.') >= 0);
659 for (Path dir
: dirs
) {
662 } catch (IOException e
) {
663 throw new RuntimeException("Cannot process " + duDir
, e
);
668 /** Process sources in Eclipse format. */
669 protected void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
671 Path targetBundleDir
;
672 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
673 Manifest manifest
= jarIn
.getManifest();
675 String
[] relatedBundle
= manifest
.getMainAttributes().getValue("Eclipse-SourceBundle").split(";");
676 String version
= relatedBundle
[1].substring("version=\"".length());
677 version
= version
.substring(0, version
.length() - 1);
678 NameVersion nameVersion
= new NameVersion(relatedBundle
[0], version
);
679 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
681 Path targetSourceDir
= targetBundleDir
.resolve("OSGI-OPT/src");
683 // TODO make it less dangerous?
684 if (Files
.exists(targetSourceDir
)) {
685 // deleteDirectory(targetSourceDir);
687 Files
.createDirectories(targetSourceDir
);
692 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
693 if (entry
.isDirectory())
695 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
697 Path target
= targetSourceDir
.resolve(entry
.getName());
698 Files
.createDirectories(target
.getParent());
699 Files
.copy(jarIn
, target
);
700 logger
.log(Level
.TRACE
, () -> "Copied source " + target
);
705 } catch (IOException e
) {
706 throw new IllegalStateException("Cannot process " + file
, e
);
714 /** Normalise a bundle. */
715 protected Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
) throws IOException
{
716 NameVersion nameVersion
;
717 Path targetBundleDir
;
718 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
719 Manifest sourceManifest
= jarIn
.getManifest();
720 Manifest manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
723 boolean isSingleton
= false;
724 String rawSourceSymbolicName
= manifest
.getMainAttributes()
725 .getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
726 if (rawSourceSymbolicName
!= null) {
728 // make sure there is no directive
729 String
[] arr
= rawSourceSymbolicName
.split(";");
730 for (int i
= 1; i
< arr
.length
; i
++) {
731 if (arr
[i
].trim().equals("singleton:=true"))
733 logger
.log(DEBUG
, file
.getFileName() + " is a singleton");
737 // remove problematic entries in MANIFEST
738 manifest
.getEntries().clear();
740 String ourSymbolicName
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
741 String ourVersion
= entries
.get(BUNDLE_VERSION
.toString());
743 if (ourSymbolicName
!= null && ourVersion
!= null) {
744 nameVersion
= new NameVersion(ourSymbolicName
, ourVersion
);
746 nameVersion
= nameVersionFromManifest(manifest
);
747 if (ourVersion
!= null && !nameVersion
.getVersion().equals(ourVersion
)) {
748 logger
.log(Level
.WARNING
,
749 "Original version is " + nameVersion
.getVersion() + " while new version is " + ourVersion
);
750 entries
.put(BUNDLE_VERSION
.toString(), ourVersion
);
752 if (ourSymbolicName
!= null) {
753 // we always force our symbolic name
754 nameVersion
.setName(ourSymbolicName
);
757 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
759 // force Java 9 module name
760 entries
.put(ManifestConstants
.AUTOMATIC_MODULE_NAME
.toString(), nameVersion
.getName());
762 boolean isNative
= false;
765 if (targetBundleDir
.startsWith(a2LibBase
)) {
767 Path libRelativePath
= a2LibBase
.relativize(targetBundleDir
);
768 os
= libRelativePath
.getName(0).toString();
769 arch
= libRelativePath
.getName(1).toString();
774 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
775 if (entry
.isDirectory())
777 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
779 if (entry
.getName().endsWith("module-info.class")) // skip Java 9 module info
781 if (entry
.getName().startsWith("META-INF/versions/")) // skip multi-version
783 // skip file system providers as they cause issues with native image
784 if (entry
.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider"))
786 if (entry
.getName().startsWith("OSGI-OPT/src/")) // skip embedded sources
788 Path target
= targetBundleDir
.resolve(entry
.getName());
789 Files
.createDirectories(target
.getParent());
790 Files
.copy(jarIn
, target
);
793 if (isNative
&& (entry
.getName().endsWith(".so") || entry
.getName().endsWith(".dll")
794 || entry
.getName().endsWith(".jnilib"))) {
795 Path categoryDir
= targetBundleDir
.getParent();
796 // String[] segments = categoryDir.getFileName().toString().split("\\.");
797 // String arch = segments[segments.length - 1];
798 // String os = segments[segments.length - 2];
799 boolean copyDll
= false;
800 Path targetDll
= categoryDir
.resolve(targetBundleDir
.relativize(target
));
801 if (nameVersion
.getName().equals("com.sun.jna")) {
802 if (arch
.equals("x86_64"))
804 if (os
.equals("macosx"))
806 if (target
.getParent().getFileName().toString().equals(os
+ "-" + arch
)) {
809 targetDll
= categoryDir
.resolve(target
.getFileName());
814 Files
.createDirectories(targetDll
.getParent());
815 if (Files
.exists(targetDll
))
816 Files
.delete(targetDll
);
817 Files
.copy(target
, targetDll
);
819 Files
.delete(target
);
821 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
825 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
826 Files
.createDirectories(manifestPath
.getParent());
828 if (isSingleton
&& entries
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
829 entries
.put(BUNDLE_SYMBOLICNAME
.toString(),
830 entries
.get(BUNDLE_SYMBOLICNAME
.toString()) + ";singleton:=true");
833 for (String key
: entries
.keySet()) {
834 String value
= entries
.get(key
);
835 Object previousValue
= manifest
.getMainAttributes().putValue(key
, value
);
836 if (previousValue
!= null && !previousValue
.equals(value
)) {
837 if (ManifestConstants
.IMPORT_PACKAGE
.toString().equals(key
)
838 || ManifestConstants
.EXPORT_PACKAGE
.toString().equals(key
))
839 logger
.log(Level
.TRACE
, file
.getFileName() + ": " + key
+ " was modified");
841 logger
.log(Level
.WARNING
, file
.getFileName() + ": " + key
+ " was " + previousValue
842 + ", overridden with " + value
);
845 // hack to remove unresolvable
846 if (key
.equals("Provide-Capability") || key
.equals("Require-Capability"))
847 if (nameVersion
.getName().equals("osgi.core") || nameVersion
.getName().equals("osgi.cmpn")) {
848 manifest
.getMainAttributes().remove(key
);
851 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
855 return targetBundleDir
;
862 /** Recursively deletes a directory. */
863 private static void deleteDirectory(Path path
) throws IOException
{
864 if (!Files
.exists(path
))
866 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
868 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
871 Files
.delete(directory
);
872 return FileVisitResult
.CONTINUE
;
876 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
878 return FileVisitResult
.CONTINUE
;
883 /** Extract name/version from a MANIFEST. */
884 protected NameVersion
nameVersionFromManifest(Manifest manifest
) {
885 Attributes attrs
= manifest
.getMainAttributes();
887 String symbolicName
= attrs
.getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
888 if (symbolicName
== null)
890 // make sure there is no directive
891 symbolicName
= symbolicName
.split(";")[0];
893 String version
= attrs
.getValue(ManifestConstants
.BUNDLE_VERSION
.toString());
894 return new NameVersion(symbolicName
, version
);
897 /** Try to download from an URI. */
898 protected Path
tryDownload(String uri
, Path dir
) throws IOException
{
900 List
<String
> urlBases
= null;
901 String uriPrefix
= null;
902 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
903 if (uri
.startsWith(uriPref
)) {
904 if (mirrors
.get(uriPref
).size() > 0) {
905 urlBases
= mirrors
.get(uriPref
);
911 if (urlBases
== null)
913 return download(new URL(uri
), dir
);
914 } catch (FileNotFoundException e
) {
915 throw new FileNotFoundException("Cannot find " + uri
);
919 for (String urlBase
: urlBases
) {
920 String relativePath
= uri
.substring(uriPrefix
.length());
921 URL url
= new URL(urlBase
+ relativePath
);
923 return download(url
, dir
);
924 } catch (FileNotFoundException e
) {
925 logger
.log(Level
.WARNING
, "Cannot download " + url
+ ", trying another mirror");
928 throw new FileNotFoundException("Cannot find " + uri
);
931 /** Effectively download. */
932 protected Path
download(URL url
, Path dir
) throws IOException
{
933 return download(url
, dir
, (String
) null);
936 /** Effectively download. */
937 protected Path
download(URL url
, Path dir
, String name
) throws IOException
{
941 name
= url
.getPath().substring(url
.getPath().lastIndexOf('/') + 1);
944 dest
= dir
.resolve(name
);
945 if (Files
.exists(dest
)) {
946 logger
.log(Level
.TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
949 Files
.createDirectories(dest
.getParent());
952 try (InputStream in
= url
.openStream()) {
953 Files
.copy(in
, dest
);
954 logger
.log(Level
.DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
959 /** Create a JAR file from a directory. */
960 protected Path
createJar(Path bundleDir
) throws IOException
{
962 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
963 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
965 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
966 manifest
= new Manifest(in
);
968 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
969 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
970 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
973 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
974 if (file
.getFileName().toString().equals("MANIFEST.MF"))
975 return super.visitFile(file
, attrs
);
976 JarEntry entry
= new JarEntry(bundleDir
.relativize(file
).toString());
977 jarOut
.putNextEntry(entry
);
978 Files
.copy(file
, jarOut
);
979 return super.visitFile(file
, attrs
);
984 deleteDirectory(bundleDir
);
988 enum ManifestConstants
{
990 BUNDLE_SYMBOLICNAME("Bundle-SymbolicName"), //
991 BUNDLE_VERSION("Bundle-Version"), //
992 BUNDLE_LICENSE("Bundle-License"), //
993 EXPORT_PACKAGE("Export-Package"), //
994 IMPORT_PACKAGE("Import-Package"), //
996 AUTOMATIC_MODULE_NAME("Automatic-Module-Name"), //
998 SLC_CATEGORY("SLC-Category"), //
999 SLC_ORIGIN_M2("SLC-Origin-M2"), //
1000 SLC_ORIGIN_M2_MERGE("SLC-Origin-M2-Merge"), //
1001 SLC_ORIGIN_M2_REPO("SLC-Origin-M2-Repo"), //
1002 SLC_ORIGIN_MANIFEST_NOT_MODIFIED("SLC-Origin-ManifestNotModified"), //
1003 SLC_ORIGIN_URI("SLC-Origin-URI"),//
1008 private ManifestConstants(String value
) {
1013 public String
toString() {
1021 /** Simple representation of an M2 artifact. */
1022 class M2Artifact
extends CategoryNameVersion
{
1023 private String classifier
;
1025 M2Artifact(String m2coordinates
) {
1026 this(m2coordinates
, null);
1029 M2Artifact(String m2coordinates
, String classifier
) {
1030 String
[] parts
= m2coordinates
.split(":");
1031 setCategory(parts
[0]);
1033 if (parts
.length
> 2) {
1034 setVersion(parts
[2]);
1036 this.classifier
= classifier
;
1039 String
getGroupId() {
1040 return super.getCategory();
1043 String
getArtifactId() {
1044 return super.getName();
1047 String
toM2Coordinates() {
1048 return getCategory() + ":" + getName() + (getVersion() != null ?
":" + getVersion() : "");
1051 String
getClassifier() {
1052 return classifier
!= null ? classifier
: "";
1055 String
getExtension() {
1060 /** Utilities around Maven (conventions based). */
1061 class M2ConventionsUtils
{
1062 final static String MAVEN_CENTRAL_BASE_URL
= "https://repo1.maven.org/maven2/";
1064 /** The file name of this artifact when stored */
1065 static String
artifactFileName(M2Artifact artifact
) {
1066 return artifact
.getArtifactId() + '-' + artifact
.getVersion()
1067 + (artifact
.getClassifier().equals("") ?
"" : '-' + artifact
.getClassifier()) + '.'
1068 + artifact
.getExtension();
1071 /** Absolute path to the file */
1072 static String
artifactPath(String artifactBasePath
, M2Artifact artifact
) {
1073 return artifactParentPath(artifactBasePath
, artifact
) + '/' + artifactFileName(artifact
);
1076 /** Absolute path to the file */
1077 static String
artifactUrl(String repoUrl
, M2Artifact artifact
) {
1078 if (repoUrl
.endsWith("/"))
1079 return repoUrl
+ artifactPath("/", artifact
).substring(1);
1081 return repoUrl
+ artifactPath("/", artifact
);
1084 /** Absolute path to the file */
1085 static URL
mavenRepoUrl(String repoBase
, M2Artifact artifact
) {
1086 String url
= artifactUrl(repoBase
== null ? MAVEN_CENTRAL_BASE_URL
: repoBase
, artifact
);
1088 return new URL(url
);
1089 } catch (MalformedURLException e
) {
1090 // it should not happen
1091 throw new IllegalStateException(e
);
1095 /** Absolute path to the directories where the files will be stored */
1096 static String
artifactParentPath(String artifactBasePath
, M2Artifact artifact
) {
1097 return artifactBasePath
+ (artifactBasePath
.endsWith("/") ?
"" : "/") + artifactParentPath(artifact
);
1100 /** Relative path to the directories where the files will be stored */
1101 static String
artifactParentPath(M2Artifact artifact
) {
1102 return artifact
.getGroupId().replace('.', '/') + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion();
1106 private M2ConventionsUtils() {
1110 class CategoryNameVersion
extends NameVersion
{
1111 private String category
;
1113 CategoryNameVersion() {
1116 CategoryNameVersion(String category
, String name
, String version
) {
1117 super(name
, version
);
1118 this.category
= category
;
1121 CategoryNameVersion(String category
, NameVersion nameVersion
) {
1123 this.category
= category
;
1126 String
getCategory() {
1130 void setCategory(String category
) {
1131 this.category
= category
;
1135 public String
toString() {
1136 return category
+ ":" + super.toString();
1141 class NameVersion
implements Comparable
<NameVersion
> {
1142 private String name
;
1143 private String version
;
1148 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1149 NameVersion(String nameVersion
) {
1150 int index
= nameVersion
.indexOf(";version=");
1152 setName(nameVersion
);
1155 setName(nameVersion
.substring(0, index
));
1156 setVersion(nameVersion
.substring(index
+ ";version=".length()));
1160 NameVersion(String name
, String version
) {
1162 this.version
= version
;
1165 NameVersion(NameVersion nameVersion
) {
1166 this.name
= nameVersion
.getName();
1167 this.version
= nameVersion
.getVersion();
1174 void setName(String name
) {
1178 String
getVersion() {
1182 void setVersion(String version
) {
1183 this.version
= version
;
1186 String
getBranch() {
1187 String
[] parts
= getVersion().split("\\.");
1188 if (parts
.length
< 2)
1189 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1190 return parts
[0] + "." + parts
[1];
1194 public boolean equals(Object obj
) {
1195 if (obj
instanceof NameVersion
) {
1196 NameVersion nameVersion
= (NameVersion
) obj
;
1197 return name
.equals(nameVersion
.getName()) && version
.equals(nameVersion
.getVersion());
1203 public int hashCode() {
1204 return name
.hashCode();
1208 public String
toString() {
1209 return name
+ ":" + version
;
1212 public int compareTo(NameVersion o
) {
1213 if (o
.getName().equals(name
))
1214 return version
.compareTo(o
.getVersion());
1216 return name
.compareTo(o
.getName());