1 package org
.argeo
.slc
.factory
;
3 import static java
.lang
.System
.Logger
.Level
.DEBUG
;
4 import static org
.argeo
.slc
.ManifestConstants
.BUNDLE_SYMBOLICNAME
;
5 import static org
.argeo
.slc
.ManifestConstants
.BUNDLE_VERSION
;
6 import static org
.argeo
.slc
.ManifestConstants
.EXPORT_PACKAGE
;
7 import static org
.argeo
.slc
.ManifestConstants
.SLC_ORIGIN_M2
;
8 import static org
.argeo
.slc
.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
;
17 import java
.nio
.file
.DirectoryStream
;
18 import java
.nio
.file
.FileSystem
;
19 import java
.nio
.file
.FileSystems
;
20 import java
.nio
.file
.FileVisitResult
;
21 import java
.nio
.file
.Files
;
22 import java
.nio
.file
.Path
;
23 import java
.nio
.file
.PathMatcher
;
24 import java
.nio
.file
.Paths
;
25 import java
.nio
.file
.SimpleFileVisitor
;
26 import java
.nio
.file
.StandardOpenOption
;
27 import java
.nio
.file
.attribute
.BasicFileAttributes
;
28 import java
.util
.ArrayList
;
29 import java
.util
.HashMap
;
30 import java
.util
.List
;
32 import java
.util
.Objects
;
33 import java
.util
.Properties
;
34 import java
.util
.TreeMap
;
35 import java
.util
.jar
.Attributes
;
36 import java
.util
.jar
.JarEntry
;
37 import java
.util
.jar
.JarInputStream
;
38 import java
.util
.jar
.JarOutputStream
;
39 import java
.util
.jar
.Manifest
;
40 import java
.util
.zip
.Deflater
;
42 import org
.argeo
.slc
.DefaultCategoryNameVersion
;
43 import org
.argeo
.slc
.DefaultNameVersion
;
44 import org
.argeo
.slc
.ManifestConstants
;
45 import org
.argeo
.slc
.NameVersion
;
46 import org
.argeo
.slc
.factory
.m2
.Artifact
;
47 import org
.argeo
.slc
.factory
.m2
.DefaultArtifact
;
48 import org
.argeo
.slc
.factory
.m2
.MavenConventionsUtils
;
50 import aQute
.bnd
.osgi
.Analyzer
;
51 import aQute
.bnd
.osgi
.Jar
;
53 /** The central class for A2 packaging. */
54 public class A2Factory
{
55 private final static Logger logger
= System
.getLogger(A2Factory
.class.getName());
57 private final static String COMMON_BND
= "common.bnd";
58 private final static String MERGE_BND
= "merge.bnd";
60 private Path originBase
;
62 private Path a2LibBase
;
63 private Path descriptorsBase
;
65 private Properties uris
= new Properties();
67 private boolean includeSources
= true;
69 /** key is URI prefix, value list of base URLs */
70 private Map
<String
, List
<String
>> mirrors
= new HashMap
<String
, List
<String
>>();
72 public A2Factory(Path a2Base
, Path descriptorsBase
, boolean includeSources
) {
73 Objects
.requireNonNull(a2Base
);
74 Objects
.requireNonNull(descriptorsBase
);
75 this.originBase
= Paths
.get(System
.getProperty("user.home"), ".cache", "argeo/slc/origin");
77 this.a2LibBase
= a2Base
.resolve("lib");
78 this.descriptorsBase
= descriptorsBase
;
79 if (!Files
.exists(this.descriptorsBase
))
80 throw new IllegalArgumentException(this.descriptorsBase
+ " does not exist");
81 this.includeSources
= includeSources
;
83 Path urisPath
= this.descriptorsBase
.resolve("uris.properties");
84 if (Files
.exists(urisPath
)) {
85 try (InputStream in
= Files
.newInputStream(urisPath
)) {
87 } catch (IOException e
) {
88 throw new IllegalStateException("Cannot load " + urisPath
, e
);
92 // TODO make it configurable
93 List
<String
> eclipseMirrors
= new ArrayList
<>();
94 eclipseMirrors
.add("https://archive.eclipse.org/");
95 eclipseMirrors
.add("http://ftp-stud.hs-esslingen.de/Mirrors/eclipse/");
96 eclipseMirrors
.add("http://ftp.fau.de/eclipse/");
98 mirrors
.put("http://www.eclipse.org/downloads", eclipseMirrors
);
105 /** Process a whole category/group id. */
106 public void processCategory(Path categoryRelativePath
) {
108 Path targetCategoryBase
= descriptorsBase
.resolve(categoryRelativePath
);
109 DirectoryStream
<Path
> bnds
= Files
.newDirectoryStream(targetCategoryBase
,
110 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
111 && !p
.getFileName().toString().equals(MERGE_BND
));
112 for (Path p
: bnds
) {
113 processSingleM2ArtifactDistributionUnit(p
);
116 DirectoryStream
<Path
> dus
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
117 for (Path duDir
: dus
) {
118 processM2BasedDistributionUnit(duDir
);
120 } catch (IOException e
) {
121 throw new RuntimeException("Cannot process category " + categoryRelativePath
, e
);
125 /** Process a standalone Maven artifact. */
126 public void processSingleM2ArtifactDistributionUnit(Path bndFile
) {
128 // String category = bndFile.getParent().getFileName().toString();
129 Path categoryRelativePath
= descriptorsBase
.relativize(bndFile
.getParent());
130 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
132 Properties fileProps
= new Properties();
133 try (InputStream in
= Files
.newInputStream(bndFile
)) {
136 String repoStr
= fileProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
137 ? fileProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
140 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
141 // use file name as symbolic name
142 String symbolicName
= bndFile
.getFileName().toString();
143 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
144 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
147 String m2Coordinates
= fileProps
.getProperty(SLC_ORIGIN_M2
.toString());
148 if (m2Coordinates
== null)
149 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile
);
150 DefaultArtifact artifact
= new DefaultArtifact(m2Coordinates
);
151 URL url
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
152 Path downloaded
= download(url
, originBase
, artifact
);
154 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, fileProps
, artifact
);
156 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
158 createJar(targetBundleDir
);
159 } catch (Exception e
) {
160 throw new RuntimeException("Cannot process " + bndFile
, e
);
164 /** Process multiple Maven artifacts. */
165 public void processM2BasedDistributionUnit(Path duDir
) {
167 // String category = duDir.getParent().getFileName().toString();
168 Path categoryRelativePath
= descriptorsBase
.relativize(duDir
.getParent());
169 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
172 Path mergeBnd
= duDir
.resolve(MERGE_BND
);
173 if (Files
.exists(mergeBnd
)) {
174 mergeM2Artifacts(mergeBnd
);
178 Path commonBnd
= duDir
.resolve(COMMON_BND
);
179 if (!Files
.exists(commonBnd
)) {
182 Properties commonProps
= new Properties();
183 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
184 commonProps
.load(in
);
187 String m2Version
= commonProps
.getProperty(SLC_ORIGIN_M2
.toString());
188 if (m2Version
== null) {
189 logger
.log(Level
.WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
190 return;// ignore, this is probably an Eclipse archive
192 if (!m2Version
.startsWith(":")) {
193 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
195 m2Version
= m2Version
.substring(1);
197 DirectoryStream
<Path
> ds
= Files
.newDirectoryStream(duDir
,
198 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
199 && !p
.getFileName().toString().equals(MERGE_BND
));
201 Properties fileProps
= new Properties();
202 try (InputStream in
= Files
.newInputStream(p
)) {
205 String m2Coordinates
= fileProps
.getProperty(SLC_ORIGIN_M2
.toString());
206 DefaultArtifact artifact
= new DefaultArtifact(m2Coordinates
);
208 // temporary rewrite, for migration
209 // String localLicense = fileProps.getProperty(BUNDLE_LICENSE.toString());
210 // if (localLicense != null || artifact.getVersion() != null) {
211 // fileProps.remove(BUNDLE_LICENSE.toString());
212 // fileProps.put(SLC_ORIGIN_M2.toString(), artifact.getGroupId() + ":" + artifact.getArtifactId());
213 // try (Writer writer = Files.newBufferedWriter(p)) {
214 // for (Object key : fileProps.keySet()) {
215 // String value = fileProps.getProperty(key.toString());
216 // writer.write(key + ": " + value + '\n');
218 // logger.log(DEBUG, () -> "Migrated " + p);
222 artifact
.setVersion(m2Version
);
224 // prepare manifest entries
225 Properties mergeProps
= new Properties();
226 mergeProps
.putAll(commonProps
);
228 fileEntries
: for (Object key
: fileProps
.keySet()) {
229 if (ManifestConstants
.SLC_ORIGIN_M2
.toString().equals(key
))
230 continue fileEntries
;
231 String value
= fileProps
.getProperty(key
.toString());
232 Object previousValue
= mergeProps
.put(key
.toString(), value
);
233 if (previousValue
!= null) {
234 logger
.log(Level
.WARNING
,
235 commonBnd
+ ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
238 mergeProps
.put(ManifestConstants
.SLC_ORIGIN_M2
.toString(), artifact
.toM2Coordinates());
239 if (!mergeProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
240 // use file name as symbolic name
241 String symbolicName
= p
.getFileName().toString();
242 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
243 mergeProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
246 String repoStr
= mergeProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
247 ? mergeProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
251 URL url
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
252 Path downloaded
= download(url
, originBase
, artifact
);
254 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, mergeProps
, artifact
);
255 // logger.log(Level.DEBUG, () -> "Processed " + downloaded);
258 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
260 createJar(targetBundleDir
);
262 } catch (IOException e
) {
263 throw new RuntimeException("Cannot process " + duDir
, e
);
268 /** Merge multiple Maven artifacts. */
269 protected void mergeM2Artifacts(Path mergeBnd
) throws IOException
{
270 Path duDir
= mergeBnd
.getParent();
271 String category
= duDir
.getParent().getFileName().toString();
272 Path targetCategoryBase
= a2Base
.resolve(category
);
274 Properties mergeProps
= new Properties();
275 try (InputStream in
= Files
.newInputStream(mergeBnd
)) {
280 String m2Version
= mergeProps
.getProperty(SLC_ORIGIN_M2
.toString());
281 if (m2Version
== null) {
282 logger
.log(Level
.WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
283 return;// ignore, this is probably an Eclipse archive
285 if (!m2Version
.startsWith(":")) {
286 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
288 m2Version
= m2Version
.substring(1);
289 mergeProps
.put(ManifestConstants
.BUNDLE_VERSION
.toString(), m2Version
);
291 String artifactsStr
= mergeProps
.getProperty(ManifestConstants
.SLC_ORIGIN_M2_MERGE
.toString());
292 String repoStr
= mergeProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
293 ? mergeProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
296 String bundleSymbolicName
= mergeProps
.getProperty(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
297 if (bundleSymbolicName
== null)
298 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd
);
299 DefaultCategoryNameVersion nameVersion
= new DefaultArtifact(
300 category
+ ":" + bundleSymbolicName
+ ":" + m2Version
);
301 Path targetBundleDir
= targetCategoryBase
.resolve(bundleSymbolicName
+ "." + nameVersion
.getBranch());
303 String
[] artifacts
= artifactsStr
.split(",");
304 artifacts
: for (String str
: artifacts
) {
305 String m2Coordinates
= str
.trim();
306 if ("".equals(m2Coordinates
))
308 DefaultArtifact artifact
= new DefaultArtifact(m2Coordinates
.trim());
309 if (artifact
.getVersion() == null)
310 artifact
.setVersion(m2Version
);
311 URL url
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
312 Path downloaded
= download(url
, originBase
, artifact
);
314 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(downloaded
), false)) {
315 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
316 if (entry
.isDirectory())
318 else if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
320 else if (entry
.getName().startsWith("META-INF/versions/"))
322 else if (entry
.getName().startsWith("META-INF/maven/"))
324 else if (entry
.getName().equals("module-info.class"))
326 else if (entry
.getName().equals("META-INF/NOTICE"))
328 else if (entry
.getName().equals("META-INF/NOTICE.txt"))
330 else if (entry
.getName().equals("META-INF/LICENSE"))
332 else if (entry
.getName().equals("META-INF/LICENSE.md"))
334 else if (entry
.getName().equals("META-INF/LICENSE-notice.md"))
336 Path target
= targetBundleDir
.resolve(entry
.getName());
337 Files
.createDirectories(target
.getParent());
338 if (!Files
.exists(target
)) {
339 Files
.copy(jarIn
, target
);
341 if (entry
.getName().startsWith("META-INF/services/")) {
342 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
343 out
.write("\n".getBytes());
344 jarIn
.transferTo(out
);
345 if (logger
.isLoggable(DEBUG
))
346 logger
.log(DEBUG
, artifact
.getArtifactId() + " - Appended " + entry
.getName());
348 } else if (entry
.getName().startsWith("org/apache/batik/")) {
349 logger
.log(Level
.WARNING
, "Skip " + entry
.getName());
352 throw new IllegalStateException("File " + target
+ " from " + artifact
+ " already exists");
355 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
359 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
362 // additional service files
363 Path servicesDir
= duDir
.resolve("services");
364 if (Files
.exists(servicesDir
)) {
365 for (Path p
: Files
.newDirectoryStream(servicesDir
)) {
366 Path target
= targetBundleDir
.resolve("META-INF/services/").resolve(p
.getFileName());
367 try (InputStream in
= Files
.newInputStream(p
);
368 OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
);) {
369 out
.write("\n".getBytes());
371 if (logger
.isLoggable(DEBUG
))
372 logger
.log(DEBUG
, "Appended " + p
);
377 Map
<String
, String
> entries
= new TreeMap
<>();
378 try (Analyzer bndAnalyzer
= new Analyzer()) {
379 bndAnalyzer
.setProperties(mergeProps
);
380 Jar jar
= new Jar(targetBundleDir
.toFile());
381 bndAnalyzer
.setJar(jar
);
382 Manifest manifest
= bndAnalyzer
.calcManifest();
384 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
385 Object value
= manifest
.getMainAttributes().get(key
);
387 switch (key
.toString()) {
389 case "Bnd-LastModified":
393 if ("Require-Capability".equals(key
.toString())
394 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
395 continue keys
;// hack for very old classes
396 entries
.put(key
.toString(), value
.toString());
397 // logger.log(DEBUG, () -> key + "=" + value);
400 } catch (Exception e
) {
401 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
404 Manifest manifest
= new Manifest();
405 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
406 Files
.createDirectories(manifestPath
.getParent());
407 for (String key
: entries
.keySet()) {
408 String value
= entries
.get(key
);
409 manifest
.getMainAttributes().putValue(key
, value
);
412 // // Use Maven version as Bundle-Version
413 // String bundleVersion = manifest.getMainAttributes().getValue(ManifestConstants.BUNDLE_VERSION.toString());
414 // if (bundleVersion == null || bundleVersion.trim().equals("0")) {
415 // // TODO check why it is sometimes set to "0"
416 // manifest.getMainAttributes().putValue(ManifestConstants.BUNDLE_VERSION.toString(), m2Version);
418 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
422 createJar(targetBundleDir
);
426 /** Generate MANIFEST using BND. */
427 protected Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
,
428 DefaultArtifact artifact
) {
431 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
432 boolean doNotModify
= Boolean
.parseBoolean(fileProps
433 .getOrDefault(ManifestConstants
.SLC_ORIGIN_MANIFEST_NOT_MODIFIED
.toString(), "false").toString());
435 // we always force the symbolic name
438 fileEntries
: for (Object key
: fileProps
.keySet()) {
439 if (ManifestConstants
.SLC_ORIGIN_M2
.toString().equals(key
))
440 continue fileEntries
;
441 String value
= fileProps
.getProperty(key
.toString());
442 additionalEntries
.put(key
.toString(), value
);
445 if (artifact
!= null) {
446 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
447 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
449 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
450 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
454 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
455 fileProps
.put(EXPORT_PACKAGE
.toString(),
456 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
458 // if (!fileProps.contains(IMPORT_PACKAGE.toString())) {
459 // fileProps.put(IMPORT_PACKAGE.toString(), "*");
462 try (Analyzer bndAnalyzer
= new Analyzer()) {
463 bndAnalyzer
.setProperties(fileProps
);
464 Jar jar
= new Jar(downloaded
.toFile());
465 bndAnalyzer
.setJar(jar
);
466 Manifest manifest
= bndAnalyzer
.calcManifest();
468 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
469 Object value
= manifest
.getMainAttributes().get(key
);
471 switch (key
.toString()) {
473 case "Bnd-LastModified":
477 if ("Require-Capability".equals(key
.toString())
478 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
479 continue keys
;// hack for very old classes
480 additionalEntries
.put(key
.toString(), value
.toString());
481 // logger.log(DEBUG, () -> key + "=" + value);
486 // try (Builder bndBuilder = new Builder()) {
487 // Jar jar = new Jar(downloaded.toFile());
488 // bndBuilder.addClasspath(jar);
489 // Path targetBundleDir = targetCategoryBase.resolve(artifact.getName() + "." + artifact.getBranch());
491 // Jar target = new Jar(targetBundleDir.toFile());
492 // bndBuilder.setJar(target);
493 // return targetBundleDir;
496 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
);
497 logger
.log(Level
.DEBUG
, () -> "Processed " + downloaded
);
498 return targetBundleDir
;
499 } catch (Exception e
) {
500 throw new RuntimeException("Cannot BND process " + downloaded
, e
);
505 /** Download and integrates sources for a single Maven artifact. */
506 protected void downloadAndProcessM2Sources(String repoStr
, DefaultArtifact artifact
, Path targetBundleDir
)
510 DefaultArtifact sourcesArtifact
= new DefaultArtifact(artifact
.toM2Coordinates(), "sources");
511 URL sourcesUrl
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
512 Path sourcesDownloaded
= download(sourcesUrl
, originBase
, artifact
, true);
513 processM2SourceJar(sourcesDownloaded
, targetBundleDir
);
514 logger
.log(Level
.TRACE
, () -> "Processed source " + sourcesDownloaded
);
518 /** Integrate sources from a downloaded jar file. */
519 protected void processM2SourceJar(Path file
, Path targetBundleDir
) throws IOException
{
520 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
521 Path targetSourceDir
= targetBundleDir
.resolve("OSGI-OPT/src");
523 // TODO make it less dangerous?
524 if (Files
.exists(targetSourceDir
)) {
525 // deleteDirectory(targetSourceDir);
527 Files
.createDirectories(targetSourceDir
);
532 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
533 if (entry
.isDirectory())
535 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
537 if (entry
.getName().startsWith("module-info.java"))// skip META-INF entries
539 if (entry
.getName().startsWith("/")) // absolute paths
541 Path target
= targetSourceDir
.resolve(entry
.getName());
542 Files
.createDirectories(target
.getParent());
543 if (!Files
.exists(target
)) {
544 Files
.copy(jarIn
, target
);
545 logger
.log(Level
.TRACE
, () -> "Copied source " + target
);
547 logger
.log(Level
.WARNING
, () -> target
+ " already exists, skipping...");
554 /** Download a Maven artifact. */
555 protected Path
download(URL url
, Path dir
, Artifact artifact
) throws IOException
{
556 return download(url
, dir
, artifact
, false);
559 /** Download a Maven artifact. */
560 protected Path
download(URL url
, Path dir
, Artifact artifact
, boolean sources
) throws IOException
{
561 return download(url
, dir
, artifact
.getGroupId() + '/' + artifact
.getArtifactId() + "-" + artifact
.getVersion()
562 + (sources ?
"-sources" : "") + ".jar");
569 /** Process an archive in Eclipse format. */
570 public void processEclipseArchive(Path relativePath
) {
572 Path categoryRelativePath
= relativePath
.getParent();
573 // String category = categoryRelativePath.getFileName().toString();
574 Path targetCategoryBase
= a2Base
.resolve(categoryRelativePath
);
575 Files
.createDirectories(targetCategoryBase
);
576 // first delete all directories from previous builds
577 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
))) {
578 deleteDirectory(dir
);
581 Files
.createDirectories(originBase
);
583 Path duDir
= descriptorsBase
.resolve(relativePath
);
584 Path commonBnd
= duDir
.resolve(COMMON_BND
);
585 Properties commonProps
= new Properties();
586 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
587 commonProps
.load(in
);
589 String url
= commonProps
.getProperty(ManifestConstants
.SLC_ORIGIN_URI
.toString());
591 url
= uris
.getProperty(relativePath
.getFileName().toString());
593 throw new IllegalStateException("No url available for " + duDir
);
594 commonProps
.put(ManifestConstants
.SLC_ORIGIN_URI
.toString(), url
);
596 Path downloaded
= tryDownload(url
, originBase
);
598 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
601 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
602 Properties includes
= new Properties();
603 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
606 for (Object pattern
: includes
.keySet()) {
607 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
608 includeMatchers
.add(pathMatcher
);
611 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
612 Path excludeFile
= duDir
.resolve("excludes.properties");
613 if (Files
.exists(excludeFile
)) {
614 Properties excludes
= new Properties();
615 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
618 for (Object pattern
: excludes
.keySet()) {
619 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
620 excludeMatchers
.add(pathMatcher
);
624 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
627 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
628 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
629 if (includeMatcher
.matches(file
)) {
630 for (PathMatcher excludeMatcher
: excludeMatchers
) {
631 if (excludeMatcher
.matches(file
)) {
632 logger
.log(Level
.WARNING
, "Skipping excluded " + file
);
633 return FileVisitResult
.CONTINUE
;
636 if (includeSources
&& file
.getFileName().toString().contains(".source_")) {
637 processEclipseSourceJar(file
, targetCategoryBase
);
638 logger
.log(Level
.DEBUG
, () -> "Processed source " + file
);
641 processBundleJar(file
, targetCategoryBase
, new HashMap(commonProps
));
642 logger
.log(Level
.DEBUG
, () -> "Processed " + file
);
644 break includeMatchers
;
647 return FileVisitResult
.CONTINUE
;
651 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
652 for (Path dir
: dirs
) {
655 } catch (IOException e
) {
656 throw new RuntimeException("Cannot process " + relativePath
, e
);
661 /** Process sources in Eclipse format. */
662 protected void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
664 Path targetBundleDir
;
665 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
666 Manifest manifest
= jarIn
.getManifest();
668 String
[] relatedBundle
= manifest
.getMainAttributes().getValue("Eclipse-SourceBundle").split(";");
669 String version
= relatedBundle
[1].substring("version=\"".length());
670 version
= version
.substring(0, version
.length() - 1);
671 NameVersion nameVersion
= new DefaultNameVersion(relatedBundle
[0], version
);
672 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
674 Path targetSourceDir
= targetBundleDir
.resolve("OSGI-OPT/src");
676 // TODO make it less dangerous?
677 if (Files
.exists(targetSourceDir
)) {
678 // deleteDirectory(targetSourceDir);
680 Files
.createDirectories(targetSourceDir
);
685 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
686 if (entry
.isDirectory())
688 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
690 Path target
= targetSourceDir
.resolve(entry
.getName());
691 Files
.createDirectories(target
.getParent());
692 Files
.copy(jarIn
, target
);
693 logger
.log(Level
.TRACE
, () -> "Copied source " + target
);
697 // Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
698 // Files.createDirectories(manifestPath.getParent());
699 // try (OutputStream out = Files.newOutputStream(manifestPath)) {
700 // manifest.write(out);
703 } catch (IOException e
) {
704 throw new IllegalStateException("Cannot process " + file
, e
);
712 /** Normalise a bundle. */
713 protected Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
) throws IOException
{
714 DefaultNameVersion nameVersion
;
715 Path targetBundleDir
;
716 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
717 Manifest sourceManifest
= jarIn
.getManifest();
718 Manifest manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
720 // remove problematic entries in MANIFEST
721 manifest
.getEntries().clear();
722 // Set<String> entriesToDelete = new HashSet<>();
723 // for (String key : manifest.getEntries().keySet()) {
724 //// logger.log(DEBUG, "## " + key);
725 // Attributes attrs = manifest.getAttributes(key);
726 // for (Object attrName : attrs.keySet()) {
727 //// logger.log(DEBUG, attrName + "=" + attrs.get(attrName));
728 // if ("Specification-Version".equals(attrName.toString())
729 // || "Implementation-Version".equals(attrName.toString())) {
730 // entriesToDelete.add(key);
735 // for (String key : entriesToDelete) {
736 // manifest.getEntries().remove(key);
739 String ourSymbolicName
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
740 String ourVersion
= entries
.get(BUNDLE_VERSION
.toString());
742 if (ourSymbolicName
!= null && ourVersion
!= null) {
743 nameVersion
= new DefaultNameVersion(ourSymbolicName
, ourVersion
);
745 nameVersion
= nameVersionFromManifest(manifest
);
746 if (ourVersion
!= null && !nameVersion
.getVersion().equals(ourVersion
)) {
747 logger
.log(Level
.WARNING
,
748 "Original version is " + nameVersion
.getVersion() + " while new version is " + ourVersion
);
749 entries
.put(BUNDLE_VERSION
.toString(), ourVersion
);
751 if (ourSymbolicName
!= null) {
752 // we always force our symbolic name
753 nameVersion
.setName(ourSymbolicName
);
756 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
758 // force Java 9 module name
759 entries
.put(ManifestConstants
.AUTOMATIC_MODULE_NAME
.toString(), nameVersion
.getName());
761 // TODO make it less dangerous?
762 // if (Files.exists(targetBundleDir)) {
763 // deleteDirectory(targetBundleDir);
766 boolean isNative
= false;
769 if (targetBundleDir
.startsWith(a2LibBase
)) {
771 Path libRelativePath
= a2LibBase
.relativize(targetBundleDir
);
772 os
= libRelativePath
.getName(0).toString();
773 arch
= libRelativePath
.getName(1).toString();
778 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
779 if (entry
.isDirectory())
781 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
783 if (entry
.getName().endsWith("module-info.class")) // skip Java 9 module info
785 if (entry
.getName().startsWith("META-INF/versions/")) // skip multi-version
787 // skip file system providers as they cause issues with native image
788 if (entry
.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider"))
790 if (entry
.getName().startsWith("OSGI-OPT/src/")) // skip embedded sources
792 Path target
= targetBundleDir
.resolve(entry
.getName());
793 Files
.createDirectories(target
.getParent());
794 Files
.copy(jarIn
, target
);
797 if (isNative
&& (entry
.getName().endsWith(".so") || entry
.getName().endsWith(".dll")
798 || entry
.getName().endsWith(".jnilib"))) {
799 Path categoryDir
= targetBundleDir
.getParent();
800 // String[] segments = categoryDir.getFileName().toString().split("\\.");
801 // String arch = segments[segments.length - 1];
802 // String os = segments[segments.length - 2];
803 boolean copyDll
= false;
804 Path targetDll
= categoryDir
.resolve(target
.getFileName());
805 if (nameVersion
.getName().equals("com.sun.jna")) {
806 if (arch
.equals("x86_64"))
808 if (os
.equals("macosx"))
810 if (target
.getParent().getFileName().toString().equals(os
+ "-" + arch
)) {
817 if (Files
.exists(targetDll
))
818 Files
.delete(targetDll
);
819 Files
.copy(target
, targetDll
);
821 Files
.delete(target
);
823 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
827 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
828 Files
.createDirectories(manifestPath
.getParent());
829 for (String key
: entries
.keySet()) {
830 String value
= entries
.get(key
);
831 Object previousValue
= manifest
.getMainAttributes().putValue(key
, value
);
832 if (previousValue
!= null && !previousValue
.equals(value
)) {
833 if (ManifestConstants
.IMPORT_PACKAGE
.toString().equals(key
)
834 || ManifestConstants
.EXPORT_PACKAGE
.toString().equals(key
))
835 logger
.log(Level
.TRACE
, file
.getFileName() + ": " + key
+ " was modified");
837 logger
.log(Level
.WARNING
, file
.getFileName() + ": " + key
+ " was " + previousValue
838 + ", overridden with " + value
);
841 // hack to remove unresolvable
842 if (key
.equals("Provide-Capability") || key
.equals("Require-Capability"))
843 if (nameVersion
.getName().equals("osgi.core") || nameVersion
.getName().equals("osgi.cmpn")) {
844 manifest
.getMainAttributes().remove(key
);
847 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
851 return targetBundleDir
;
858 /** Recursively deletes a directory. */
859 private static void deleteDirectory(Path path
) throws IOException
{
860 if (!Files
.exists(path
))
862 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
864 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
867 Files
.delete(directory
);
868 return FileVisitResult
.CONTINUE
;
872 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
874 return FileVisitResult
.CONTINUE
;
879 /** Extract name/version from a MANIFEST. */
880 protected DefaultNameVersion
nameVersionFromManifest(Manifest manifest
) {
881 Attributes attrs
= manifest
.getMainAttributes();
883 String symbolicName
= attrs
.getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
884 if (symbolicName
== null)
886 // make sure there is no directive
887 symbolicName
= symbolicName
.split(";")[0];
889 String version
= attrs
.getValue(ManifestConstants
.BUNDLE_VERSION
.toString());
890 return new DefaultNameVersion(symbolicName
, version
);
893 /** Try to download from an URI. */
894 protected Path
tryDownload(String uri
, Path dir
) throws IOException
{
896 List
<String
> urlBases
= null;
897 String uriPrefix
= null;
898 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
899 if (uri
.startsWith(uriPref
)) {
900 if (mirrors
.get(uriPref
).size() > 0) {
901 urlBases
= mirrors
.get(uriPref
);
907 if (urlBases
== null)
909 return download(new URL(uri
), dir
);
910 } catch (FileNotFoundException e
) {
911 throw new FileNotFoundException("Cannot find " + uri
);
915 for (String urlBase
: urlBases
) {
916 String relativePath
= uri
.substring(uriPrefix
.length());
917 URL url
= new URL(urlBase
+ relativePath
);
919 return download(url
, dir
);
920 } catch (FileNotFoundException e
) {
921 logger
.log(Level
.WARNING
, "Cannot download " + url
+ ", trying another mirror");
924 throw new FileNotFoundException("Cannot find " + uri
);
927 // protected String simplifyName(URL u) {
928 // String name = u.getPath().substring(u.getPath().lastIndexOf('/') + 1);
932 /** Effectively download. */
933 protected Path
download(URL url
, Path dir
) throws IOException
{
934 return download(url
, dir
, (String
) null);
937 /** Effectively download. */
938 protected Path
download(URL url
, Path dir
, String name
) throws IOException
{
942 name
= url
.getPath().substring(url
.getPath().lastIndexOf('/') + 1);
945 dest
= dir
.resolve(name
);
946 if (Files
.exists(dest
)) {
947 logger
.log(Level
.TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
950 Files
.createDirectories(dest
.getParent());
953 try (InputStream in
= url
.openStream()) {
954 Files
.copy(in
, dest
);
955 logger
.log(Level
.DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
960 /** Create a JAR file from a directory. */
961 protected Path
createJar(Path bundleDir
) throws IOException
{
962 // Remove from source the resources already in the jar file
963 // Path srcDir = bundleDir.resolve("OSGI-OPT/src");
964 // Files.walkFileTree(srcDir, new SimpleFileVisitor<Path>() {
967 // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
968 // // always keep .java file
969 // if (file.getFileName().toString().endsWith(".java"))
970 // return super.visitFile(file, attrs);
972 // Path relPath = srcDir.relativize(file);
973 // Path bundlePath = bundleDir.resolve(relPath);
974 // if (Files.exists(bundlePath)) {
975 // Files.delete(file);
976 // logger.log(DEBUG, () -> "Removed " + file + " from sources.");
978 // return super.visitFile(file, attrs);
984 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
985 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
987 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
988 manifest
= new Manifest(in
);
990 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
991 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
992 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
995 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
996 if (file
.getFileName().toString().equals("MANIFEST.MF"))
997 return super.visitFile(file
, attrs
);
998 JarEntry entry
= new JarEntry(bundleDir
.relativize(file
).toString());
999 jarOut
.putNextEntry(entry
);
1000 Files
.copy(file
, jarOut
);
1001 return super.visitFile(file
, attrs
);
1006 deleteDirectory(bundleDir
);
1010 /** For development purproses. */
1011 public static void main(String
[] args
) {
1012 Path factoryBase
= Paths
.get("../../output/a2").toAbsolutePath().normalize();
1013 Path descriptorsBase
= Paths
.get("../tp").toAbsolutePath().normalize();
1014 A2Factory factory
= new A2Factory(factoryBase
, descriptorsBase
, true);
1016 // factory.processSingleM2ArtifactDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache").resolve("org.apache.xml.resolver.bnd"));
1017 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache/apache-sshd"));
1018 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.jetty/jetty"));
1019 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.osgi"));
1020 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.eclipse.rcp"));
1021 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp"));
1022 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.apache"));
1023 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.sdk"));
1024 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.formats"));
1025 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.gis"));
1029 factory
.processCategory(Paths
.get("org.argeo.tp.sdk"));
1032 factory
.processCategory(Paths
.get("osgi/api/org.argeo.tp.osgi"));
1033 factory
.processEclipseArchive(Paths
.get("osgi/equinox/org.argeo.tp.osgi", "eclipse-equinox"));
1035 factory
.processEclipseArchive(Paths
.get("org.argeo.tp.eclipse", "eclipse-equinox"));
1037 factory
.processEclipseArchive(Paths
.get("swt/rap/org.argeo.tp.swt", "eclipse-rap"));
1038 factory
.processEclipseArchive(Paths
.get("swt/rap/org.argeo.tp.swt.workbench", "eclipse-rap"));
1040 factory
.processEclipseArchive(Paths
.get("swt/rcp/org.argeo.tp.swt", "eclipse-rcp"));
1042 factory
.processEclipseArchive(Paths
.get("lib/linux/x86_64/swt/rcp/org.argeo.tp.swt", "eclipse-rcp"));
1043 factory
.processEclipseArchive(Paths
.get("lib/linux/aarch64/swt/rcp/org.argeo.tp.swt", "eclipse-rcp"));
1044 factory
.processEclipseArchive(Paths
.get("lib/win32/x86_64/swt/rcp/org.argeo.tp.swt", "eclipse-rcp"));
1045 factory
.processEclipseArchive(Paths
.get("lib/macosx/x86_64/swt/rcp/org.argeo.tp.swt", "eclipse-rcp"));
1047 factory
.processEclipseArchive(Paths
.get("swt/rcp/org.argeo.tp.swt", "eclipse-nebula"));
1048 // factory.processEclipseArchive(Paths.get("swt/rcp/org.argeo.tp.swt",
1049 // "eclipse-equinox"));
1050 factory
.processEclipseArchive(Paths
.get("swt/rcp/org.argeo.tp.swt.workbench", "eclipse-rcp"));
1051 factory
.processCategory(Paths
.get("swt/rcp/org.argeo.tp.swt.workbench"));
1054 factory
.processCategory(Paths
.get("org.argeo.tp"));
1055 factory
.processCategory(Paths
.get("org.argeo.tp.apache"));
1056 factory
.processCategory(Paths
.get("org.argeo.tp.jetty"));
1057 factory
.processCategory(Paths
.get("org.argeo.tp.jcr"));
1058 factory
.processCategory(Paths
.get("org.argeo.tp.formats"));
1059 factory
.processCategory(Paths
.get("org.argeo.tp.poi"));
1060 factory
.processCategory(Paths
.get("org.argeo.tp.gis"));