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
.jar
.Attributes
;
39 import java
.util
.jar
.JarEntry
;
40 import java
.util
.jar
.JarInputStream
;
41 import java
.util
.jar
.JarOutputStream
;
42 import java
.util
.jar
.Manifest
;
43 import java
.util
.zip
.Deflater
;
45 import aQute
.bnd
.osgi
.Analyzer
;
46 import aQute
.bnd
.osgi
.Jar
;
48 /** The central class for A2 packaging. */
49 public class Repackage
{
50 private final static Logger logger
= System
.getLogger(Repackage
.class.getName());
52 /** Main entry point. */
53 public static void main(String
[] args
) {
54 if (args
.length
< 2) {
55 System
.err
.println("Usage: <path to a2 output dir> <category1> <category2> ...");
58 Path a2Base
= Paths
.get(args
[0]).toAbsolutePath().normalize();
59 Path descriptorsBase
= Paths
.get(".").toAbsolutePath().normalize();
60 Repackage factory
= new Repackage(a2Base
, descriptorsBase
, true);
62 for (int i
= 1; i
< args
.length
; i
++) {
63 Path p
= Paths
.get(args
[i
]);
64 factory
.processCategory(p
);
68 private final static String COMMON_BND
= "common.bnd";
69 private final static String MERGE_BND
= "merge.bnd";
71 private Path originBase
;
73 private Path a2LibBase
;
74 private Path descriptorsBase
;
76 private Properties uris
= new Properties();
78 private boolean includeSources
= true;
80 /** key is URI prefix, value list of base URLs */
81 private Map
<String
, List
<String
>> mirrors
= new HashMap
<String
, List
<String
>>();
83 public Repackage(Path a2Base
, Path descriptorsBase
, boolean includeSources
) {
84 Objects
.requireNonNull(a2Base
);
85 Objects
.requireNonNull(descriptorsBase
);
86 this.originBase
= Paths
.get(System
.getProperty("user.home"), ".cache", "argeo/build/origin");
87 // TODO define and use a build base
89 this.a2LibBase
= a2Base
.resolve("lib");
90 this.descriptorsBase
= descriptorsBase
;
91 if (!Files
.exists(this.descriptorsBase
))
92 throw new IllegalArgumentException(this.descriptorsBase
+ " does not exist");
93 this.includeSources
= includeSources
;
96 Path urisPath
= this.descriptorsBase
.resolve("uris.properties");
97 if (Files
.exists(urisPath
)) {
98 try (InputStream in
= Files
.newInputStream(urisPath
)) {
100 } catch (IOException e
) {
101 throw new IllegalStateException("Cannot load " + urisPath
, e
);
106 Path eclipseMirrorsPath
= this.descriptorsBase
.resolve("eclipse.mirrors.txt");
107 List
<String
> eclipseMirrors
= new ArrayList
<>();
108 if (Files
.exists(eclipseMirrorsPath
)) {
110 eclipseMirrors
= Files
.readAllLines(eclipseMirrorsPath
, StandardCharsets
.UTF_8
);
111 } catch (IOException e
) {
112 throw new IllegalStateException("Cannot load " + eclipseMirrorsPath
, e
);
114 for (Iterator
<String
> it
= eclipseMirrors
.iterator(); it
.hasNext();) {
115 String value
= it
.next();
116 if (value
.strip().equals(""))
121 mirrors
.put("http://www.eclipse.org/downloads", eclipseMirrors
);
128 /** Process a whole category/group id. */
129 public void processCategory(Path categoryRelativePath
) {
131 Path targetCategoryBase
= descriptorsBase
.resolve(categoryRelativePath
);
132 DirectoryStream
<Path
> bnds
= Files
.newDirectoryStream(targetCategoryBase
,
133 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
134 && !p
.getFileName().toString().equals(MERGE_BND
));
135 for (Path p
: bnds
) {
136 processSingleM2ArtifactDistributionUnit(p
);
139 DirectoryStream
<Path
> dus
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
140 for (Path duDir
: dus
) {
141 if (duDir
.getFileName().toString().startsWith("eclipse-")) {
142 processEclipseArchive(duDir
);
144 processM2BasedDistributionUnit(duDir
);
147 } catch (IOException e
) {
148 throw new RuntimeException("Cannot process category " + categoryRelativePath
, e
);
152 /** Process a standalone Maven artifact. */
153 public void processSingleM2ArtifactDistributionUnit(Path bndFile
) {
155 // String category = bndFile.getParent().getFileName().toString();
156 Path categoryRelativePath
= descriptorsBase
.relativize(bndFile
.getParent());
157 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
159 Properties fileProps
= new Properties();
160 try (InputStream in
= Files
.newInputStream(bndFile
)) {
163 String repoStr
= fileProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
164 ? fileProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
167 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
168 // use file name as symbolic name
169 String symbolicName
= bndFile
.getFileName().toString();
170 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
171 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
174 String m2Coordinates
= fileProps
.getProperty(SLC_ORIGIN_M2
.toString());
175 if (m2Coordinates
== null)
176 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile
);
177 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
178 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
179 Path downloaded
= download(url
, originBase
, artifact
);
181 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, fileProps
, artifact
);
183 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
185 createJar(targetBundleDir
);
186 } catch (Exception e
) {
187 throw new RuntimeException("Cannot process " + bndFile
, e
);
191 /** Process multiple Maven artifacts. */
192 public void processM2BasedDistributionUnit(Path duDir
) {
194 // String category = duDir.getParent().getFileName().toString();
195 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
196 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
199 Path mergeBnd
= duDir
.resolve(MERGE_BND
);
200 if (Files
.exists(mergeBnd
)) {
201 mergeM2Artifacts(mergeBnd
);
205 Path commonBnd
= duDir
.resolve(COMMON_BND
);
206 if (!Files
.exists(commonBnd
)) {
209 Properties commonProps
= new Properties();
210 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
211 commonProps
.load(in
);
214 String m2Version
= commonProps
.getProperty(SLC_ORIGIN_M2
.toString());
215 if (m2Version
== null) {
216 logger
.log(Level
.WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
217 return;// ignore, this is probably an Eclipse archive
219 if (!m2Version
.startsWith(":")) {
220 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
222 m2Version
= m2Version
.substring(1);
224 DirectoryStream
<Path
> ds
= Files
.newDirectoryStream(duDir
,
225 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
226 && !p
.getFileName().toString().equals(MERGE_BND
));
228 Properties fileProps
= new Properties();
229 try (InputStream in
= Files
.newInputStream(p
)) {
232 String m2Coordinates
= fileProps
.getProperty(SLC_ORIGIN_M2
.toString());
233 M2Artifact artifact
= new M2Artifact(m2Coordinates
);
235 artifact
.setVersion(m2Version
);
237 // prepare manifest entries
238 Properties mergeProps
= new Properties();
239 mergeProps
.putAll(commonProps
);
241 fileEntries
: for (Object key
: fileProps
.keySet()) {
242 if (ManifestConstants
.SLC_ORIGIN_M2
.toString().equals(key
))
243 continue fileEntries
;
244 String value
= fileProps
.getProperty(key
.toString());
245 Object previousValue
= mergeProps
.put(key
.toString(), value
);
246 if (previousValue
!= null) {
247 logger
.log(Level
.WARNING
,
248 commonBnd
+ ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
251 mergeProps
.put(ManifestConstants
.SLC_ORIGIN_M2
.toString(), artifact
.toM2Coordinates());
252 if (!mergeProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
253 // use file name as symbolic name
254 String symbolicName
= p
.getFileName().toString();
255 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
256 mergeProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
259 String repoStr
= mergeProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
260 ? mergeProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
264 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
265 Path downloaded
= download(url
, originBase
, artifact
);
267 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, mergeProps
, artifact
);
268 // logger.log(Level.DEBUG, () -> "Processed " + downloaded);
271 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
273 createJar(targetBundleDir
);
275 } catch (IOException e
) {
276 throw new RuntimeException("Cannot process " + duDir
, e
);
281 /** Merge multiple Maven artifacts. */
282 protected void mergeM2Artifacts(Path mergeBnd
) throws IOException
{
283 Path duDir
= mergeBnd
.getParent();
284 String category
= duDir
.getParent().getFileName().toString();
285 Path targetCategoryBase
= a2Base
.resolve(category
);
287 Properties mergeProps
= new Properties();
288 try (InputStream in
= Files
.newInputStream(mergeBnd
)) {
293 String m2Version
= mergeProps
.getProperty(SLC_ORIGIN_M2
.toString());
294 if (m2Version
== null) {
295 logger
.log(Level
.WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
296 return;// ignore, this is probably an Eclipse archive
298 if (!m2Version
.startsWith(":")) {
299 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
301 m2Version
= m2Version
.substring(1);
302 mergeProps
.put(ManifestConstants
.BUNDLE_VERSION
.toString(), m2Version
);
304 String artifactsStr
= mergeProps
.getProperty(ManifestConstants
.SLC_ORIGIN_M2_MERGE
.toString());
305 String repoStr
= mergeProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
306 ? mergeProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
309 String bundleSymbolicName
= mergeProps
.getProperty(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
310 if (bundleSymbolicName
== null)
311 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd
);
312 CategoryNameVersion nameVersion
= new M2Artifact(category
+ ":" + bundleSymbolicName
+ ":" + m2Version
);
313 Path targetBundleDir
= targetCategoryBase
.resolve(bundleSymbolicName
+ "." + nameVersion
.getBranch());
315 String
[] artifacts
= artifactsStr
.split(",");
316 artifacts
: for (String str
: artifacts
) {
317 String m2Coordinates
= str
.trim();
318 if ("".equals(m2Coordinates
))
320 M2Artifact artifact
= new M2Artifact(m2Coordinates
.trim());
321 if (artifact
.getVersion() == null)
322 artifact
.setVersion(m2Version
);
323 URL url
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
324 Path downloaded
= download(url
, originBase
, artifact
);
326 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(downloaded
), false)) {
327 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
328 if (entry
.isDirectory())
330 else if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
332 else if (entry
.getName().startsWith("META-INF/versions/"))
334 else if (entry
.getName().startsWith("META-INF/maven/"))
336 else if (entry
.getName().equals("module-info.class"))
338 else if (entry
.getName().equals("META-INF/NOTICE"))
340 else if (entry
.getName().equals("META-INF/NOTICE.txt"))
342 else if (entry
.getName().equals("META-INF/LICENSE"))
344 else if (entry
.getName().equals("META-INF/LICENSE.md"))
346 else if (entry
.getName().equals("META-INF/LICENSE-notice.md"))
348 else if (entry
.getName().equals("META-INF/DEPENDENCIES"))
350 if (entry
.getName().startsWith(".cache/")) // Apache SSHD
352 Path target
= targetBundleDir
.resolve(entry
.getName());
353 Files
.createDirectories(target
.getParent());
354 if (!Files
.exists(target
)) {
355 Files
.copy(jarIn
, target
);
357 if (entry
.getName().startsWith("META-INF/services/")) {
358 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
359 out
.write("\n".getBytes());
360 jarIn
.transferTo(out
);
361 if (logger
.isLoggable(DEBUG
))
362 logger
.log(DEBUG
, artifact
.getArtifactId() + " - Appended " + entry
.getName());
364 } else if (entry
.getName().startsWith("org/apache/batik/")) {
365 logger
.log(Level
.WARNING
, "Skip " + entry
.getName());
368 throw new IllegalStateException("File " + target
+ " from " + artifact
+ " already exists");
371 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
375 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
378 // additional service files
379 Path servicesDir
= duDir
.resolve("services");
380 if (Files
.exists(servicesDir
)) {
381 for (Path p
: Files
.newDirectoryStream(servicesDir
)) {
382 Path target
= targetBundleDir
.resolve("META-INF/services/").resolve(p
.getFileName());
383 try (InputStream in
= Files
.newInputStream(p
);
384 OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
);) {
385 out
.write("\n".getBytes());
387 if (logger
.isLoggable(DEBUG
))
388 logger
.log(DEBUG
, "Appended " + p
);
393 Map
<String
, String
> entries
= new TreeMap
<>();
394 try (Analyzer bndAnalyzer
= new Analyzer()) {
395 bndAnalyzer
.setProperties(mergeProps
);
396 Jar jar
= new Jar(targetBundleDir
.toFile());
397 bndAnalyzer
.setJar(jar
);
398 Manifest manifest
= bndAnalyzer
.calcManifest();
400 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
401 Object value
= manifest
.getMainAttributes().get(key
);
403 switch (key
.toString()) {
405 case "Bnd-LastModified":
409 if ("Require-Capability".equals(key
.toString())
410 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
411 continue keys
;// hack for very old classes
412 entries
.put(key
.toString(), value
.toString());
413 // logger.log(DEBUG, () -> key + "=" + value);
416 } catch (Exception e
) {
417 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
420 Manifest manifest
= new Manifest();
421 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
422 Files
.createDirectories(manifestPath
.getParent());
423 for (String key
: entries
.keySet()) {
424 String value
= entries
.get(key
);
425 manifest
.getMainAttributes().putValue(key
, value
);
428 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
431 createJar(targetBundleDir
);
434 /** Generate MANIFEST using BND. */
435 protected Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
, M2Artifact artifact
) {
438 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
439 boolean doNotModify
= Boolean
.parseBoolean(fileProps
440 .getOrDefault(ManifestConstants
.SLC_ORIGIN_MANIFEST_NOT_MODIFIED
.toString(), "false").toString());
442 // we always force the symbolic name
445 fileEntries
: for (Object key
: fileProps
.keySet()) {
446 if (ManifestConstants
.SLC_ORIGIN_M2
.toString().equals(key
))
447 continue fileEntries
;
448 String value
= fileProps
.getProperty(key
.toString());
449 additionalEntries
.put(key
.toString(), value
);
452 if (artifact
!= null) {
453 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
454 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
456 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
457 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
461 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
462 fileProps
.put(EXPORT_PACKAGE
.toString(),
463 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
466 try (Analyzer bndAnalyzer
= new Analyzer()) {
467 bndAnalyzer
.setProperties(fileProps
);
468 Jar jar
= new Jar(downloaded
.toFile());
469 bndAnalyzer
.setJar(jar
);
470 Manifest manifest
= bndAnalyzer
.calcManifest();
472 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
473 Object value
= manifest
.getMainAttributes().get(key
);
475 switch (key
.toString()) {
477 case "Bnd-LastModified":
481 if ("Require-Capability".equals(key
.toString())
482 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
483 continue keys
;// hack for very old classes
484 additionalEntries
.put(key
.toString(), value
.toString());
485 // logger.log(DEBUG, () -> key + "=" + value);
490 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
);
491 logger
.log(Level
.DEBUG
, () -> "Processed " + downloaded
);
492 return targetBundleDir
;
493 } catch (Exception e
) {
494 throw new RuntimeException("Cannot BND process " + downloaded
, e
);
499 /** Download and integrates sources for a single Maven artifact. */
500 protected void downloadAndProcessM2Sources(String repoStr
, M2Artifact artifact
, Path targetBundleDir
)
504 M2Artifact sourcesArtifact
= new M2Artifact(artifact
.toM2Coordinates(), "sources");
505 URL sourcesUrl
= M2ConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
506 Path sourcesDownloaded
= download(sourcesUrl
, originBase
, artifact
, true);
507 processM2SourceJar(sourcesDownloaded
, targetBundleDir
);
508 logger
.log(Level
.TRACE
, () -> "Processed source " + sourcesDownloaded
);
512 /** Integrate sources from a downloaded jar file. */
513 protected void processM2SourceJar(Path file
, Path targetBundleDir
) throws IOException
{
514 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
515 Path targetSourceDir
= targetBundleDir
.resolve("OSGI-OPT/src");
517 // TODO make it less dangerous?
518 if (Files
.exists(targetSourceDir
)) {
519 // deleteDirectory(targetSourceDir);
521 Files
.createDirectories(targetSourceDir
);
526 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
527 if (entry
.isDirectory())
529 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
531 if (entry
.getName().startsWith("module-info.java"))// skip META-INF entries
533 if (entry
.getName().startsWith("/")) // absolute paths
535 Path target
= targetSourceDir
.resolve(entry
.getName());
536 Files
.createDirectories(target
.getParent());
537 if (!Files
.exists(target
)) {
538 Files
.copy(jarIn
, target
);
539 logger
.log(Level
.TRACE
, () -> "Copied source " + target
);
541 logger
.log(Level
.WARNING
, () -> target
+ " already exists, skipping...");
548 /** Download a Maven artifact. */
549 protected Path
download(URL url
, Path dir
, M2Artifact artifact
) throws IOException
{
550 return download(url
, dir
, artifact
, false);
553 /** Download a Maven artifact. */
554 protected Path
download(URL url
, Path dir
, M2Artifact artifact
, boolean sources
) throws IOException
{
555 return download(url
, dir
, artifact
.getGroupId() + '/' + artifact
.getArtifactId() + "-" + artifact
.getVersion()
556 + (sources ?
"-sources" : "") + ".jar");
563 /** Process an archive in Eclipse format. */
564 public void processEclipseArchive(Path duDir
) {
566 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
567 // String category = categoryRelativePath.getFileName().toString();
568 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
569 Files
.createDirectories(targetCategoryBase
);
570 // first delete all directories from previous builds
571 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
))) {
572 deleteDirectory(dir
);
575 Files
.createDirectories(originBase
);
577 Path commonBnd
= duDir
.resolve(COMMON_BND
);
578 Properties commonProps
= new Properties();
579 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
580 commonProps
.load(in
);
582 String url
= commonProps
.getProperty(ManifestConstants
.SLC_ORIGIN_URI
.toString());
584 url
= uris
.getProperty(duDir
.getFileName().toString());
586 throw new IllegalStateException("No url available for " + duDir
);
587 commonProps
.put(ManifestConstants
.SLC_ORIGIN_URI
.toString(), url
);
589 Path downloaded
= tryDownload(url
, originBase
);
591 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
594 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
595 Properties includes
= new Properties();
596 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
599 for (Object pattern
: includes
.keySet()) {
600 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
601 includeMatchers
.add(pathMatcher
);
604 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
605 Path excludeFile
= duDir
.resolve("excludes.properties");
606 if (Files
.exists(excludeFile
)) {
607 Properties excludes
= new Properties();
608 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
611 for (Object pattern
: excludes
.keySet()) {
612 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
613 excludeMatchers
.add(pathMatcher
);
617 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
620 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
621 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
622 if (includeMatcher
.matches(file
)) {
623 for (PathMatcher excludeMatcher
: excludeMatchers
) {
624 if (excludeMatcher
.matches(file
)) {
625 logger
.log(Level
.TRACE
, "Skipping excluded " + file
);
626 return FileVisitResult
.CONTINUE
;
629 if (includeSources
&& file
.getFileName().toString().contains(".source_")) {
630 processEclipseSourceJar(file
, targetCategoryBase
);
631 logger
.log(Level
.DEBUG
, () -> "Processed source " + file
);
634 Map
<String
, String
> map
= new HashMap
<>();
635 for (Object key
: commonProps
.keySet())
636 map
.put(key
.toString(), commonProps
.getProperty(key
.toString()));
637 processBundleJar(file
, targetCategoryBase
, map
);
638 logger
.log(Level
.DEBUG
, () -> "Processed " + file
);
640 break includeMatchers
;
643 return FileVisitResult
.CONTINUE
;
647 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
,
648 (p
) -> Files
.isDirectory(p
) && p
.getFileName().toString().indexOf('.') >= 0);
649 for (Path dir
: dirs
) {
652 } catch (IOException e
) {
653 throw new RuntimeException("Cannot process " + duDir
, e
);
658 /** Process sources in Eclipse format. */
659 protected void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
661 Path targetBundleDir
;
662 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
663 Manifest manifest
= jarIn
.getManifest();
665 String
[] relatedBundle
= manifest
.getMainAttributes().getValue("Eclipse-SourceBundle").split(";");
666 String version
= relatedBundle
[1].substring("version=\"".length());
667 version
= version
.substring(0, version
.length() - 1);
668 NameVersion nameVersion
= new NameVersion(relatedBundle
[0], version
);
669 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
671 Path targetSourceDir
= targetBundleDir
.resolve("OSGI-OPT/src");
673 // TODO make it less dangerous?
674 if (Files
.exists(targetSourceDir
)) {
675 // deleteDirectory(targetSourceDir);
677 Files
.createDirectories(targetSourceDir
);
682 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
683 if (entry
.isDirectory())
685 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
687 Path target
= targetSourceDir
.resolve(entry
.getName());
688 Files
.createDirectories(target
.getParent());
689 Files
.copy(jarIn
, target
);
690 logger
.log(Level
.TRACE
, () -> "Copied source " + target
);
695 } catch (IOException e
) {
696 throw new IllegalStateException("Cannot process " + file
, e
);
704 /** Normalise a bundle. */
705 protected Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
) throws IOException
{
706 NameVersion nameVersion
;
707 Path targetBundleDir
;
708 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
709 Manifest sourceManifest
= jarIn
.getManifest();
710 Manifest manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
713 boolean isSingleton
= false;
714 String rawSourceSymbolicName
= manifest
.getMainAttributes()
715 .getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
716 if (rawSourceSymbolicName
!= null) {
718 // make sure there is no directive
719 String
[] arr
= rawSourceSymbolicName
.split(";");
720 for (int i
= 1; i
< arr
.length
; i
++) {
721 if (arr
[i
].trim().equals("singleton:=true"))
723 logger
.log(DEBUG
, file
.getFileName() + " is a singleton");
727 // remove problematic entries in MANIFEST
728 manifest
.getEntries().clear();
730 String ourSymbolicName
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
731 String ourVersion
= entries
.get(BUNDLE_VERSION
.toString());
733 if (ourSymbolicName
!= null && ourVersion
!= null) {
734 nameVersion
= new NameVersion(ourSymbolicName
, ourVersion
);
736 nameVersion
= nameVersionFromManifest(manifest
);
737 if (ourVersion
!= null && !nameVersion
.getVersion().equals(ourVersion
)) {
738 logger
.log(Level
.WARNING
,
739 "Original version is " + nameVersion
.getVersion() + " while new version is " + ourVersion
);
740 entries
.put(BUNDLE_VERSION
.toString(), ourVersion
);
742 if (ourSymbolicName
!= null) {
743 // we always force our symbolic name
744 nameVersion
.setName(ourSymbolicName
);
747 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
749 // force Java 9 module name
750 entries
.put(ManifestConstants
.AUTOMATIC_MODULE_NAME
.toString(), nameVersion
.getName());
752 boolean isNative
= false;
755 if (targetBundleDir
.startsWith(a2LibBase
)) {
757 Path libRelativePath
= a2LibBase
.relativize(targetBundleDir
);
758 os
= libRelativePath
.getName(0).toString();
759 arch
= libRelativePath
.getName(1).toString();
764 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
765 if (entry
.isDirectory())
767 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
769 if (entry
.getName().endsWith("module-info.class")) // skip Java 9 module info
771 if (entry
.getName().startsWith("META-INF/versions/")) // skip multi-version
773 // skip file system providers as they cause issues with native image
774 if (entry
.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider"))
776 if (entry
.getName().startsWith("OSGI-OPT/src/")) // skip embedded sources
778 Path target
= targetBundleDir
.resolve(entry
.getName());
779 Files
.createDirectories(target
.getParent());
780 Files
.copy(jarIn
, target
);
783 if (isNative
&& (entry
.getName().endsWith(".so") || entry
.getName().endsWith(".dll")
784 || entry
.getName().endsWith(".jnilib"))) {
785 Path categoryDir
= targetBundleDir
.getParent();
786 // String[] segments = categoryDir.getFileName().toString().split("\\.");
787 // String arch = segments[segments.length - 1];
788 // String os = segments[segments.length - 2];
789 boolean copyDll
= false;
790 Path targetDll
= categoryDir
.resolve(targetBundleDir
.relativize(target
));
791 if (nameVersion
.getName().equals("com.sun.jna")) {
792 if (arch
.equals("x86_64"))
794 if (os
.equals("macosx"))
796 if (target
.getParent().getFileName().toString().equals(os
+ "-" + arch
)) {
799 targetDll
= categoryDir
.resolve(target
.getFileName());
804 Files
.createDirectories(targetDll
.getParent());
805 if (Files
.exists(targetDll
))
806 Files
.delete(targetDll
);
807 Files
.copy(target
, targetDll
);
809 Files
.delete(target
);
811 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
815 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
816 Files
.createDirectories(manifestPath
.getParent());
818 if (isSingleton
&& entries
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
819 entries
.put(BUNDLE_SYMBOLICNAME
.toString(),
820 entries
.get(BUNDLE_SYMBOLICNAME
.toString()) + ";singleton:=true");
823 for (String key
: entries
.keySet()) {
824 String value
= entries
.get(key
);
825 Object previousValue
= manifest
.getMainAttributes().putValue(key
, value
);
826 if (previousValue
!= null && !previousValue
.equals(value
)) {
827 if (ManifestConstants
.IMPORT_PACKAGE
.toString().equals(key
)
828 || ManifestConstants
.EXPORT_PACKAGE
.toString().equals(key
))
829 logger
.log(Level
.TRACE
, file
.getFileName() + ": " + key
+ " was modified");
831 logger
.log(Level
.WARNING
, file
.getFileName() + ": " + key
+ " was " + previousValue
832 + ", overridden with " + value
);
835 // hack to remove unresolvable
836 if (key
.equals("Provide-Capability") || key
.equals("Require-Capability"))
837 if (nameVersion
.getName().equals("osgi.core") || nameVersion
.getName().equals("osgi.cmpn")) {
838 manifest
.getMainAttributes().remove(key
);
841 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
845 return targetBundleDir
;
852 /** Recursively deletes a directory. */
853 private static void deleteDirectory(Path path
) throws IOException
{
854 if (!Files
.exists(path
))
856 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
858 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
861 Files
.delete(directory
);
862 return FileVisitResult
.CONTINUE
;
866 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
868 return FileVisitResult
.CONTINUE
;
873 /** Extract name/version from a MANIFEST. */
874 protected NameVersion
nameVersionFromManifest(Manifest manifest
) {
875 Attributes attrs
= manifest
.getMainAttributes();
877 String symbolicName
= attrs
.getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
878 if (symbolicName
== null)
880 // make sure there is no directive
881 symbolicName
= symbolicName
.split(";")[0];
883 String version
= attrs
.getValue(ManifestConstants
.BUNDLE_VERSION
.toString());
884 return new NameVersion(symbolicName
, version
);
887 /** Try to download from an URI. */
888 protected Path
tryDownload(String uri
, Path dir
) throws IOException
{
890 List
<String
> urlBases
= null;
891 String uriPrefix
= null;
892 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
893 if (uri
.startsWith(uriPref
)) {
894 if (mirrors
.get(uriPref
).size() > 0) {
895 urlBases
= mirrors
.get(uriPref
);
901 if (urlBases
== null)
903 return download(new URL(uri
), dir
);
904 } catch (FileNotFoundException e
) {
905 throw new FileNotFoundException("Cannot find " + uri
);
909 for (String urlBase
: urlBases
) {
910 String relativePath
= uri
.substring(uriPrefix
.length());
911 URL url
= new URL(urlBase
+ relativePath
);
913 return download(url
, dir
);
914 } catch (FileNotFoundException e
) {
915 logger
.log(Level
.WARNING
, "Cannot download " + url
+ ", trying another mirror");
918 throw new FileNotFoundException("Cannot find " + uri
);
921 /** Effectively download. */
922 protected Path
download(URL url
, Path dir
) throws IOException
{
923 return download(url
, dir
, (String
) null);
926 /** Effectively download. */
927 protected Path
download(URL url
, Path dir
, String name
) throws IOException
{
931 name
= url
.getPath().substring(url
.getPath().lastIndexOf('/') + 1);
934 dest
= dir
.resolve(name
);
935 if (Files
.exists(dest
)) {
936 logger
.log(Level
.TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
939 Files
.createDirectories(dest
.getParent());
942 try (InputStream in
= url
.openStream()) {
943 Files
.copy(in
, dest
);
944 logger
.log(Level
.DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
949 /** Create a JAR file from a directory. */
950 protected Path
createJar(Path bundleDir
) throws IOException
{
952 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
953 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
955 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
956 manifest
= new Manifest(in
);
958 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
959 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
960 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
963 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
964 if (file
.getFileName().toString().equals("MANIFEST.MF"))
965 return super.visitFile(file
, attrs
);
966 JarEntry entry
= new JarEntry(bundleDir
.relativize(file
).toString());
967 jarOut
.putNextEntry(entry
);
968 Files
.copy(file
, jarOut
);
969 return super.visitFile(file
, attrs
);
974 deleteDirectory(bundleDir
);
978 enum ManifestConstants
{
980 BUNDLE_SYMBOLICNAME("Bundle-SymbolicName"), //
981 BUNDLE_VERSION("Bundle-Version"), //
982 BUNDLE_LICENSE("Bundle-License"), //
983 EXPORT_PACKAGE("Export-Package"), //
984 IMPORT_PACKAGE("Import-Package"), //
986 AUTOMATIC_MODULE_NAME("Automatic-Module-Name"), //
988 SLC_CATEGORY("SLC-Category"), //
989 SLC_ORIGIN_M2("SLC-Origin-M2"), //
990 SLC_ORIGIN_M2_MERGE("SLC-Origin-M2-Merge"), //
991 SLC_ORIGIN_M2_REPO("SLC-Origin-M2-Repo"), //
992 SLC_ORIGIN_MANIFEST_NOT_MODIFIED("SLC-Origin-ManifestNotModified"), //
993 SLC_ORIGIN_URI("SLC-Origin-URI"),//
998 private ManifestConstants(String value
) {
1003 public String
toString() {
1011 /** Simple representation of an M2 artifact. */
1012 class M2Artifact
extends CategoryNameVersion
{
1013 private String classifier
;
1015 M2Artifact(String m2coordinates
) {
1016 this(m2coordinates
, null);
1019 M2Artifact(String m2coordinates
, String classifier
) {
1020 String
[] parts
= m2coordinates
.split(":");
1021 setCategory(parts
[0]);
1023 if (parts
.length
> 2) {
1024 setVersion(parts
[2]);
1026 this.classifier
= classifier
;
1029 String
getGroupId() {
1030 return super.getCategory();
1033 String
getArtifactId() {
1034 return super.getName();
1037 String
toM2Coordinates() {
1038 return getCategory() + ":" + getName() + (getVersion() != null ?
":" + getVersion() : "");
1041 String
getClassifier() {
1042 return classifier
!= null ? classifier
: "";
1045 String
getExtension() {
1050 /** Utilities around Maven (conventions based). */
1051 class M2ConventionsUtils
{
1052 final static String MAVEN_CENTRAL_BASE_URL
= "https://repo1.maven.org/maven2/";
1054 /** The file name of this artifact when stored */
1055 static String
artifactFileName(M2Artifact artifact
) {
1056 return artifact
.getArtifactId() + '-' + artifact
.getVersion()
1057 + (artifact
.getClassifier().equals("") ?
"" : '-' + artifact
.getClassifier()) + '.'
1058 + artifact
.getExtension();
1061 /** Absolute path to the file */
1062 static String
artifactPath(String artifactBasePath
, M2Artifact artifact
) {
1063 return artifactParentPath(artifactBasePath
, artifact
) + '/' + artifactFileName(artifact
);
1066 /** Absolute path to the file */
1067 static String
artifactUrl(String repoUrl
, M2Artifact artifact
) {
1068 if (repoUrl
.endsWith("/"))
1069 return repoUrl
+ artifactPath("/", artifact
).substring(1);
1071 return repoUrl
+ artifactPath("/", artifact
);
1074 /** Absolute path to the file */
1075 static URL
mavenRepoUrl(String repoBase
, M2Artifact artifact
) {
1076 String url
= artifactUrl(repoBase
== null ? MAVEN_CENTRAL_BASE_URL
: repoBase
, artifact
);
1078 return new URL(url
);
1079 } catch (MalformedURLException e
) {
1080 // it should not happen
1081 throw new IllegalStateException(e
);
1085 /** Absolute path to the directories where the files will be stored */
1086 static String
artifactParentPath(String artifactBasePath
, M2Artifact artifact
) {
1087 return artifactBasePath
+ (artifactBasePath
.endsWith("/") ?
"" : "/") + artifactParentPath(artifact
);
1090 /** Relative path to the directories where the files will be stored */
1091 static String
artifactParentPath(M2Artifact artifact
) {
1092 return artifact
.getGroupId().replace('.', '/') + '/' + artifact
.getArtifactId() + '/' + artifact
.getVersion();
1096 private M2ConventionsUtils() {
1100 class CategoryNameVersion
extends NameVersion
{
1101 private String category
;
1103 CategoryNameVersion() {
1106 CategoryNameVersion(String category
, String name
, String version
) {
1107 super(name
, version
);
1108 this.category
= category
;
1111 CategoryNameVersion(String category
, NameVersion nameVersion
) {
1113 this.category
= category
;
1116 String
getCategory() {
1120 void setCategory(String category
) {
1121 this.category
= category
;
1125 public String
toString() {
1126 return category
+ ":" + super.toString();
1131 class NameVersion
implements Comparable
<NameVersion
> {
1132 private String name
;
1133 private String version
;
1138 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1139 NameVersion(String nameVersion
) {
1140 int index
= nameVersion
.indexOf(";version=");
1142 setName(nameVersion
);
1145 setName(nameVersion
.substring(0, index
));
1146 setVersion(nameVersion
.substring(index
+ ";version=".length()));
1150 NameVersion(String name
, String version
) {
1152 this.version
= version
;
1155 NameVersion(NameVersion nameVersion
) {
1156 this.name
= nameVersion
.getName();
1157 this.version
= nameVersion
.getVersion();
1164 void setName(String name
) {
1168 String
getVersion() {
1172 void setVersion(String version
) {
1173 this.version
= version
;
1176 String
getBranch() {
1177 String
[] parts
= getVersion().split("\\.");
1178 if (parts
.length
< 2)
1179 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1180 return parts
[0] + "." + parts
[1];
1184 public boolean equals(Object obj
) {
1185 if (obj
instanceof NameVersion
) {
1186 NameVersion nameVersion
= (NameVersion
) obj
;
1187 return name
.equals(nameVersion
.getName()) && version
.equals(nameVersion
.getVersion());
1193 public int hashCode() {
1194 return name
.hashCode();
1198 public String
toString() {
1199 return name
+ ":" + version
;
1202 public int compareTo(NameVersion o
) {
1203 if (o
.getName().equals(name
))
1204 return version
.compareTo(o
.getVersion());
1206 return name
.compareTo(o
.getName());