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
.Properties
;
33 import java
.util
.TreeMap
;
34 import java
.util
.jar
.Attributes
;
35 import java
.util
.jar
.JarEntry
;
36 import java
.util
.jar
.JarInputStream
;
37 import java
.util
.jar
.JarOutputStream
;
38 import java
.util
.jar
.Manifest
;
39 import java
.util
.zip
.Deflater
;
41 import org
.argeo
.slc
.DefaultCategoryNameVersion
;
42 import org
.argeo
.slc
.DefaultNameVersion
;
43 import org
.argeo
.slc
.ManifestConstants
;
44 import org
.argeo
.slc
.NameVersion
;
45 import org
.argeo
.slc
.factory
.m2
.Artifact
;
46 import org
.argeo
.slc
.factory
.m2
.DefaultArtifact
;
47 import org
.argeo
.slc
.factory
.m2
.MavenConventionsUtils
;
49 import aQute
.bnd
.osgi
.Analyzer
;
50 import aQute
.bnd
.osgi
.Jar
;
52 /** The central class for A2 packaging. */
53 public class A2Factory
{
54 private final static Logger logger
= System
.getLogger(A2Factory
.class.getName());
56 private final static String COMMON_BND
= "common.bnd";
57 private final static String MERGE_BND
= "merge.bnd";
59 private Path originBase
;
62 /** key is URI prefix, value list of base URLs */
63 private Map
<String
, List
<String
>> mirrors
= new HashMap
<String
, List
<String
>>();
65 public A2Factory(Path a2Base
) {
66 this.originBase
= Paths
.get(System
.getProperty("user.home"), ".cache", "argeo/slc/origin");
69 // TODO make it configurable
70 List
<String
> eclipseMirrors
= new ArrayList
<>();
71 eclipseMirrors
.add("https://archive.eclipse.org/");
72 eclipseMirrors
.add("http://ftp-stud.hs-esslingen.de/Mirrors/eclipse/");
73 eclipseMirrors
.add("http://ftp.fau.de/eclipse/");
75 mirrors
.put("http://www.eclipse.org/downloads", eclipseMirrors
);
82 /** Process a whole category/group id. */
83 public void processCategory(Path targetCategoryBase
) {
85 DirectoryStream
<Path
> bnds
= Files
.newDirectoryStream(targetCategoryBase
,
86 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
87 && !p
.getFileName().toString().equals(MERGE_BND
));
89 processSingleM2ArtifactDistributionUnit(p
);
92 DirectoryStream
<Path
> dus
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
93 for (Path duDir
: dus
) {
94 processM2BasedDistributionUnit(duDir
);
96 } catch (IOException e
) {
97 throw new RuntimeException("Cannot process category " + targetCategoryBase
, e
);
101 /** Process a standalone Maven artifact. */
102 public void processSingleM2ArtifactDistributionUnit(Path bndFile
) {
104 String category
= bndFile
.getParent().getFileName().toString();
105 Path targetCategoryBase
= a2Base
.resolve(category
);
106 Properties fileProps
= new Properties();
107 try (InputStream in
= Files
.newInputStream(bndFile
)) {
110 String repoStr
= fileProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
111 ? fileProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
114 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())
115 && !fileProps
.containsKey(ManifestConstants
.SLC_ORIGIN_MANIFEST_NOT_MODIFIED
.toString())) {
116 // use file name as symbolic name
117 String symbolicName
= bndFile
.getFileName().toString();
118 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
119 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
122 String m2Coordinates
= fileProps
.getProperty(SLC_ORIGIN_M2
.toString());
123 if (m2Coordinates
== null)
124 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile
);
125 DefaultArtifact artifact
= new DefaultArtifact(m2Coordinates
);
126 URL url
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
127 Path downloaded
= download(url
, originBase
, artifact
);
129 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, fileProps
, artifact
);
131 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
133 createJar(targetBundleDir
);
134 } catch (Exception e
) {
135 throw new RuntimeException("Cannot process " + bndFile
, e
);
139 /** Process multiple Maven artifacts. */
140 public void processM2BasedDistributionUnit(Path duDir
) {
142 String category
= duDir
.getParent().getFileName().toString();
143 Path targetCategoryBase
= a2Base
.resolve(category
);
146 Path mergeBnd
= duDir
.resolve(MERGE_BND
);
147 if (Files
.exists(mergeBnd
)) {
148 mergeM2Artifacts(mergeBnd
);
152 Path commonBnd
= duDir
.resolve(COMMON_BND
);
153 if (!Files
.exists(commonBnd
)) {
156 Properties commonProps
= new Properties();
157 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
158 commonProps
.load(in
);
161 String m2Version
= commonProps
.getProperty(SLC_ORIGIN_M2
.toString());
162 if (m2Version
== null) {
163 logger
.log(Level
.WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
164 return;// ignore, this is probably an Eclipse archive
166 if (!m2Version
.startsWith(":")) {
167 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
169 m2Version
= m2Version
.substring(1);
171 DirectoryStream
<Path
> ds
= Files
.newDirectoryStream(duDir
,
172 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
173 && !p
.getFileName().toString().equals(MERGE_BND
));
175 Properties fileProps
= new Properties();
176 try (InputStream in
= Files
.newInputStream(p
)) {
179 String m2Coordinates
= fileProps
.getProperty(SLC_ORIGIN_M2
.toString());
180 DefaultArtifact artifact
= new DefaultArtifact(m2Coordinates
);
182 // temporary rewrite, for migration
183 // String localLicense = fileProps.getProperty(BUNDLE_LICENSE.toString());
184 // if (localLicense != null || artifact.getVersion() != null) {
185 // fileProps.remove(BUNDLE_LICENSE.toString());
186 // fileProps.put(SLC_ORIGIN_M2.toString(), artifact.getGroupId() + ":" + artifact.getArtifactId());
187 // try (Writer writer = Files.newBufferedWriter(p)) {
188 // for (Object key : fileProps.keySet()) {
189 // String value = fileProps.getProperty(key.toString());
190 // writer.write(key + ": " + value + '\n');
192 // logger.log(DEBUG, () -> "Migrated " + p);
196 artifact
.setVersion(m2Version
);
198 // prepare manifest entries
199 Properties mergeProps
= new Properties();
200 mergeProps
.putAll(commonProps
);
202 fileEntries
: for (Object key
: fileProps
.keySet()) {
203 if (ManifestConstants
.SLC_ORIGIN_M2
.toString().equals(key
))
204 continue fileEntries
;
205 String value
= fileProps
.getProperty(key
.toString());
206 Object previousValue
= mergeProps
.put(key
.toString(), value
);
207 if (previousValue
!= null) {
208 logger
.log(Level
.WARNING
,
209 commonBnd
+ ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
212 mergeProps
.put(ManifestConstants
.SLC_ORIGIN_M2
.toString(), artifact
.toM2Coordinates());
213 if (!mergeProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())
214 && !mergeProps
.containsKey(ManifestConstants
.SLC_ORIGIN_MANIFEST_NOT_MODIFIED
.toString())) {
215 // use file name as symbolic name
216 String symbolicName
= p
.getFileName().toString();
217 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
218 mergeProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
221 String repoStr
= mergeProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
222 ? mergeProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
226 URL url
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
227 Path downloaded
= download(url
, originBase
, artifact
);
229 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, mergeProps
, artifact
);
230 // logger.log(Level.DEBUG, () -> "Processed " + downloaded);
233 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
235 createJar(targetBundleDir
);
237 } catch (IOException e
) {
238 throw new RuntimeException("Cannot process " + duDir
, e
);
243 /** Merge multiple Maven artifacts. */
244 protected void mergeM2Artifacts(Path mergeBnd
) throws IOException
{
245 Path duDir
= mergeBnd
.getParent();
246 String category
= duDir
.getParent().getFileName().toString();
247 Path targetCategoryBase
= a2Base
.resolve(category
);
249 Properties mergeProps
= new Properties();
250 try (InputStream in
= Files
.newInputStream(mergeBnd
)) {
255 String m2Version
= mergeProps
.getProperty(SLC_ORIGIN_M2
.toString());
256 if (m2Version
== null) {
257 logger
.log(Level
.WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
258 return;// ignore, this is probably an Eclipse archive
260 if (!m2Version
.startsWith(":")) {
261 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
263 m2Version
= m2Version
.substring(1);
264 mergeProps
.put(ManifestConstants
.BUNDLE_VERSION
.toString(), m2Version
);
266 String artifactsStr
= mergeProps
.getProperty(ManifestConstants
.SLC_ORIGIN_M2_MERGE
.toString());
267 String repoStr
= mergeProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
268 ? mergeProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
271 String bundleSymbolicName
= mergeProps
.getProperty(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
272 if (bundleSymbolicName
== null)
273 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd
);
274 DefaultCategoryNameVersion nameVersion
= new DefaultArtifact(
275 category
+ ":" + bundleSymbolicName
+ ":" + m2Version
);
276 Path targetBundleDir
= targetCategoryBase
.resolve(bundleSymbolicName
+ "." + nameVersion
.getBranch());
278 String
[] artifacts
= artifactsStr
.split(",");
279 artifacts
: for (String str
: artifacts
) {
280 String m2Coordinates
= str
.trim();
281 if ("".equals(m2Coordinates
))
283 DefaultArtifact artifact
= new DefaultArtifact(m2Coordinates
.trim());
284 if (artifact
.getVersion() == null)
285 artifact
.setVersion(m2Version
);
286 URL url
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
287 Path downloaded
= download(url
, originBase
, artifact
);
289 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(downloaded
), false)) {
290 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
291 if (entry
.isDirectory())
293 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
295 if (entry
.getName().startsWith("META-INF/versions/"))
297 if (entry
.getName().startsWith("META-INF/maven/"))
299 if (entry
.getName().equals("module-info.class"))
301 if (entry
.getName().equals("META-INF/NOTICE"))
303 if (entry
.getName().equals("META-INF/NOTICE.txt"))
305 if (entry
.getName().equals("META-INF/LICENSE"))
307 Path target
= targetBundleDir
.resolve(entry
.getName());
308 Files
.createDirectories(target
.getParent());
309 if (!Files
.exists(target
)) {
310 Files
.copy(jarIn
, target
);
312 if (entry
.getName().startsWith("META-INF/services/")) {
313 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
314 out
.write("\n".getBytes());
315 jarIn
.transferTo(out
);
316 if (logger
.isLoggable(DEBUG
))
317 logger
.log(DEBUG
, artifact
.getArtifactId() + " - Appended " + entry
.getName());
319 } else if (entry
.getName().startsWith("org/apache/batik/")) {
320 logger
.log(Level
.WARNING
, "Skip " + entry
.getName());
323 throw new IllegalStateException("File " + target
+ " from " + artifact
+ " already exists");
326 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
330 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
333 // additional service files
334 Path servicesDir
= duDir
.resolve("services");
335 if (Files
.exists(servicesDir
)) {
336 for (Path p
: Files
.newDirectoryStream(servicesDir
)) {
337 Path target
= targetBundleDir
.resolve("META-INF/services/").resolve(p
.getFileName());
338 try (InputStream in
= Files
.newInputStream(p
);
339 OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
);) {
340 out
.write("\n".getBytes());
342 if (logger
.isLoggable(DEBUG
))
343 logger
.log(DEBUG
, "Appended " + p
);
348 Map
<String
, String
> entries
= new TreeMap
<>();
349 try (Analyzer bndAnalyzer
= new Analyzer()) {
350 bndAnalyzer
.setProperties(mergeProps
);
351 Jar jar
= new Jar(targetBundleDir
.toFile());
352 bndAnalyzer
.setJar(jar
);
353 Manifest manifest
= bndAnalyzer
.calcManifest();
355 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
356 Object value
= manifest
.getMainAttributes().get(key
);
358 switch (key
.toString()) {
360 case "Bnd-LastModified":
364 if ("Require-Capability".equals(key
.toString())
365 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
366 continue keys
;// hack for very old classes
367 entries
.put(key
.toString(), value
.toString());
368 // logger.log(DEBUG, () -> key + "=" + value);
371 } catch (Exception e
) {
372 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
375 Manifest manifest
= new Manifest();
376 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
377 Files
.createDirectories(manifestPath
.getParent());
378 for (String key
: entries
.keySet()) {
379 String value
= entries
.get(key
);
380 manifest
.getMainAttributes().putValue(key
, value
);
383 // // Use Maven version as Bundle-Version
384 // String bundleVersion = manifest.getMainAttributes().getValue(ManifestConstants.BUNDLE_VERSION.toString());
385 // if (bundleVersion == null || bundleVersion.trim().equals("0")) {
386 // // TODO check why it is sometimes set to "0"
387 // manifest.getMainAttributes().putValue(ManifestConstants.BUNDLE_VERSION.toString(), m2Version);
389 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
393 createJar(targetBundleDir
);
397 /** Generate MANIFEST using BND. */
398 protected Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
,
399 DefaultArtifact artifact
) {
402 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
403 boolean doNotModify
= Boolean
.parseBoolean(fileProps
404 .getOrDefault(ManifestConstants
.SLC_ORIGIN_MANIFEST_NOT_MODIFIED
.toString(), "false").toString());
406 // we always force the symbolic name
409 fileEntries
: for (Object key
: fileProps
.keySet()) {
410 if (ManifestConstants
.SLC_ORIGIN_M2
.toString().equals(key
))
411 continue fileEntries
;
412 String value
= fileProps
.getProperty(key
.toString());
413 additionalEntries
.put(key
.toString(), value
);
416 if (artifact
!= null) {
417 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
418 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
420 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
421 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
425 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
426 fileProps
.put(EXPORT_PACKAGE
.toString(),
427 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
429 // if (!fileProps.contains(IMPORT_PACKAGE.toString())) {
430 // fileProps.put(IMPORT_PACKAGE.toString(), "*");
433 try (Analyzer bndAnalyzer
= new Analyzer()) {
434 bndAnalyzer
.setProperties(fileProps
);
435 Jar jar
= new Jar(downloaded
.toFile());
436 bndAnalyzer
.setJar(jar
);
437 Manifest manifest
= bndAnalyzer
.calcManifest();
439 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
440 Object value
= manifest
.getMainAttributes().get(key
);
442 switch (key
.toString()) {
444 case "Bnd-LastModified":
448 if ("Require-Capability".equals(key
.toString())
449 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
450 continue keys
;// hack for very old classes
451 additionalEntries
.put(key
.toString(), value
.toString());
452 // logger.log(DEBUG, () -> key + "=" + value);
457 // try (Builder bndBuilder = new Builder()) {
458 // Jar jar = new Jar(downloaded.toFile());
459 // bndBuilder.addClasspath(jar);
460 // Path targetBundleDir = targetCategoryBase.resolve(artifact.getName() + "." + artifact.getBranch());
462 // Jar target = new Jar(targetBundleDir.toFile());
463 // bndBuilder.setJar(target);
464 // return targetBundleDir;
467 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
);
468 logger
.log(Level
.DEBUG
, () -> "Processed " + downloaded
);
469 return targetBundleDir
;
470 } catch (Exception e
) {
471 throw new RuntimeException("Cannot BND process " + downloaded
, e
);
476 /** Download and integrates sources for a single Maven artifact. */
477 protected void downloadAndProcessM2Sources(String repoStr
, DefaultArtifact artifact
, Path targetBundleDir
)
479 DefaultArtifact sourcesArtifact
= new DefaultArtifact(artifact
.toM2Coordinates(), "sources");
480 URL sourcesUrl
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
481 Path sourcesDownloaded
= download(sourcesUrl
, originBase
, artifact
, true);
482 processM2SourceJar(sourcesDownloaded
, targetBundleDir
);
483 logger
.log(Level
.TRACE
, () -> "Processed source " + sourcesDownloaded
);
487 /** Integrate sources from a downloaded jar file. */
488 protected void processM2SourceJar(Path file
, Path targetBundleDir
) throws IOException
{
489 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
490 Path targetSourceDir
= targetBundleDir
.resolve("OSGI-OPT/src");
492 // TODO make it less dangerous?
493 if (Files
.exists(targetSourceDir
)) {
494 // deleteDirectory(targetSourceDir);
496 Files
.createDirectories(targetSourceDir
);
501 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
502 if (entry
.isDirectory())
504 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
506 if (entry
.getName().startsWith("module-info.java"))// skip META-INF entries
508 if (entry
.getName().startsWith("/")) // absolute paths
510 Path target
= targetSourceDir
.resolve(entry
.getName());
511 Files
.createDirectories(target
.getParent());
512 if (!Files
.exists(target
)) {
513 Files
.copy(jarIn
, target
);
514 logger
.log(Level
.TRACE
, () -> "Copied source " + target
);
516 logger
.log(Level
.WARNING
, () -> target
+ " already exists, skipping...");
523 /** Download a Maven artifact. */
524 protected Path
download(URL url
, Path dir
, Artifact artifact
) throws IOException
{
525 return download(url
, dir
, artifact
, false);
528 /** Download a Maven artifact. */
529 protected Path
download(URL url
, Path dir
, Artifact artifact
, boolean sources
) throws IOException
{
530 return download(url
, dir
, artifact
.getGroupId() + '/' + artifact
.getArtifactId() + "-" + artifact
.getVersion()
531 + (sources ?
"-sources" : "") + ".jar");
538 /** Process an archive in Eclipse format. */
539 public void processEclipseArchive(Path duDir
) {
541 String category
= duDir
.getParent().getFileName().toString();
542 Path targetCategoryBase
= a2Base
.resolve(category
);
543 Files
.createDirectories(targetCategoryBase
);
544 // first delete all directories from previous builds
545 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
))) {
546 deleteDirectory(dir
);
549 Files
.createDirectories(originBase
);
551 Path commonBnd
= duDir
.resolve(COMMON_BND
);
552 Properties commonProps
= new Properties();
553 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
554 commonProps
.load(in
);
556 String url
= commonProps
.getProperty(ManifestConstants
.SLC_ORIGIN_URI
.toString());
557 Path downloaded
= tryDownload(url
, originBase
);
559 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
562 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
563 Properties includes
= new Properties();
564 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
567 for (Object pattern
: includes
.keySet()) {
568 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
569 includeMatchers
.add(pathMatcher
);
572 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
573 Path excludeFile
= duDir
.resolve("excludes.properties");
574 if (Files
.exists(excludeFile
)) {
575 Properties excludes
= new Properties();
576 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
579 for (Object pattern
: excludes
.keySet()) {
580 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
581 excludeMatchers
.add(pathMatcher
);
585 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
588 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
589 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
590 if (includeMatcher
.matches(file
)) {
591 for (PathMatcher excludeMatcher
: excludeMatchers
) {
592 if (excludeMatcher
.matches(file
)) {
593 logger
.log(Level
.WARNING
, "Skipping excluded " + file
);
594 return FileVisitResult
.CONTINUE
;
597 if (file
.getFileName().toString().contains(".source_")) {
598 processEclipseSourceJar(file
, targetCategoryBase
);
599 logger
.log(Level
.DEBUG
, () -> "Processed source " + file
);
602 processBundleJar(file
, targetCategoryBase
, new HashMap
<>());
603 logger
.log(Level
.DEBUG
, () -> "Processed " + file
);
605 break includeMatchers
;
608 return FileVisitResult
.CONTINUE
;
612 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
613 for (Path dir
: dirs
) {
616 } catch (IOException e
) {
617 throw new RuntimeException("Cannot process " + duDir
, e
);
622 /** Process sources in Eclipse format. */
623 protected void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
625 Path targetBundleDir
;
626 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
627 Manifest manifest
= jarIn
.getManifest();
629 String
[] relatedBundle
= manifest
.getMainAttributes().getValue("Eclipse-SourceBundle").split(";");
630 String version
= relatedBundle
[1].substring("version=\"".length());
631 version
= version
.substring(0, version
.length() - 1);
632 NameVersion nameVersion
= new DefaultNameVersion(relatedBundle
[0], version
);
633 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
635 Path targetSourceDir
= targetBundleDir
.resolve("OSGI-OPT/src");
637 // TODO make it less dangerous?
638 if (Files
.exists(targetSourceDir
)) {
639 // deleteDirectory(targetSourceDir);
641 Files
.createDirectories(targetSourceDir
);
646 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
647 if (entry
.isDirectory())
649 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
651 Path target
= targetSourceDir
.resolve(entry
.getName());
652 Files
.createDirectories(target
.getParent());
653 Files
.copy(jarIn
, target
);
654 logger
.log(Level
.TRACE
, () -> "Copied source " + target
);
658 // Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
659 // Files.createDirectories(manifestPath.getParent());
660 // try (OutputStream out = Files.newOutputStream(manifestPath)) {
661 // manifest.write(out);
664 } catch (IOException e
) {
665 throw new IllegalStateException("Cannot process " + file
, e
);
673 /** Normalise a bundle. */
674 protected Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
) throws IOException
{
675 DefaultNameVersion nameVersion
;
676 Path targetBundleDir
;
677 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
678 Manifest sourceManifest
= jarIn
.getManifest();
679 Manifest manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
681 // remove problematic entries in MANIFEST
682 manifest
.getEntries().clear();
683 // Set<String> entriesToDelete = new HashSet<>();
684 // for (String key : manifest.getEntries().keySet()) {
685 //// logger.log(DEBUG, "## " + key);
686 // Attributes attrs = manifest.getAttributes(key);
687 // for (Object attrName : attrs.keySet()) {
688 //// logger.log(DEBUG, attrName + "=" + attrs.get(attrName));
689 // if ("Specification-Version".equals(attrName.toString())
690 // || "Implementation-Version".equals(attrName.toString())) {
691 // entriesToDelete.add(key);
696 // for (String key : entriesToDelete) {
697 // manifest.getEntries().remove(key);
700 String symbolicNameFromEntries
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
701 String versionFromEntries
= entries
.get(BUNDLE_VERSION
.toString());
703 if (symbolicNameFromEntries
!= null && versionFromEntries
!= null) {
704 nameVersion
= new DefaultNameVersion(symbolicNameFromEntries
, versionFromEntries
);
706 nameVersion
= nameVersionFromManifest(manifest
);
707 if (versionFromEntries
!= null && !nameVersion
.getVersion().equals(versionFromEntries
)) {
708 logger
.log(Level
.WARNING
, "Original version is " + nameVersion
.getVersion()
709 + " while new version is " + versionFromEntries
);
711 if (symbolicNameFromEntries
!= null) {
712 // we always force our symbolic name
713 nameVersion
.setName(symbolicNameFromEntries
);
716 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
718 // TODO make it less dangerous?
719 // if (Files.exists(targetBundleDir)) {
720 // deleteDirectory(targetBundleDir);
725 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
726 if (entry
.isDirectory())
728 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
730 Path target
= targetBundleDir
.resolve(entry
.getName());
731 Files
.createDirectories(target
.getParent());
732 Files
.copy(jarIn
, target
);
733 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
737 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
738 Files
.createDirectories(manifestPath
.getParent());
739 for (String key
: entries
.keySet()) {
740 String value
= entries
.get(key
);
741 Object previousValue
= manifest
.getMainAttributes().putValue(key
, value
);
742 if (previousValue
!= null && !previousValue
.equals(value
)) {
743 if (ManifestConstants
.IMPORT_PACKAGE
.toString().equals(key
)
744 || ManifestConstants
.EXPORT_PACKAGE
.toString().equals(key
))
745 logger
.log(Level
.WARNING
, file
.getFileName() + ": " + key
+ " was modified");
748 logger
.log(Level
.WARNING
, file
.getFileName() + ": " + key
+ " was " + previousValue
749 + ", overridden with " + value
);
752 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
756 return targetBundleDir
;
763 /** Recursively deletes a directory. */
764 private static void deleteDirectory(Path path
) throws IOException
{
765 if (!Files
.exists(path
))
767 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
769 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
772 Files
.delete(directory
);
773 return FileVisitResult
.CONTINUE
;
777 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
779 return FileVisitResult
.CONTINUE
;
784 /** Extract name/version from a MANIFEST. */
785 protected DefaultNameVersion
nameVersionFromManifest(Manifest manifest
) {
786 Attributes attrs
= manifest
.getMainAttributes();
788 String symbolicName
= attrs
.getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
789 if (symbolicName
== null)
791 // make sure there is no directive
792 symbolicName
= symbolicName
.split(";")[0];
794 String version
= attrs
.getValue(ManifestConstants
.BUNDLE_VERSION
.toString());
795 return new DefaultNameVersion(symbolicName
, version
);
798 /** Try to download from an URI. */
799 protected Path
tryDownload(String uri
, Path dir
) throws IOException
{
801 List
<String
> urlBases
= null;
802 String uriPrefix
= null;
803 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
804 if (uri
.startsWith(uriPref
)) {
805 if (mirrors
.get(uriPref
).size() > 0) {
806 urlBases
= mirrors
.get(uriPref
);
812 if (urlBases
== null)
814 return download(new URL(uri
), dir
);
815 } catch (FileNotFoundException e
) {
816 throw new FileNotFoundException("Cannot find " + uri
);
820 for (String urlBase
: urlBases
) {
821 String relativePath
= uri
.substring(uriPrefix
.length());
822 URL url
= new URL(urlBase
+ relativePath
);
824 return download(url
, dir
);
825 } catch (FileNotFoundException e
) {
826 logger
.log(Level
.WARNING
, "Cannot download " + url
+ ", trying another mirror");
829 throw new FileNotFoundException("Cannot find " + uri
);
832 // protected String simplifyName(URL u) {
833 // String name = u.getPath().substring(u.getPath().lastIndexOf('/') + 1);
837 /** Effectively download. */
838 protected Path
download(URL url
, Path dir
) throws IOException
{
839 return download(url
, dir
, (String
) null);
842 /** Effectively download. */
843 protected Path
download(URL url
, Path dir
, String name
) throws IOException
{
847 name
= url
.getPath().substring(url
.getPath().lastIndexOf('/') + 1);
850 dest
= dir
.resolve(name
);
851 if (Files
.exists(dest
)) {
852 logger
.log(Level
.TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
855 Files
.createDirectories(dest
.getParent());
858 try (InputStream in
= url
.openStream()) {
859 Files
.copy(in
, dest
);
860 logger
.log(Level
.DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
865 /** Create a JAR file from a directory. */
866 protected Path
createJar(Path bundleDir
) throws IOException
{
867 // Remove from source the resources already in the jar file
868 // Path srcDir = bundleDir.resolve("OSGI-OPT/src");
869 // Files.walkFileTree(srcDir, new SimpleFileVisitor<Path>() {
872 // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
873 // // always keep .java file
874 // if (file.getFileName().toString().endsWith(".java"))
875 // return super.visitFile(file, attrs);
877 // Path relPath = srcDir.relativize(file);
878 // Path bundlePath = bundleDir.resolve(relPath);
879 // if (Files.exists(bundlePath)) {
880 // Files.delete(file);
881 // logger.log(DEBUG, () -> "Removed " + file + " from sources.");
883 // return super.visitFile(file, attrs);
889 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
890 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
892 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
893 manifest
= new Manifest(in
);
895 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
896 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
897 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
900 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
901 if (file
.getFileName().toString().equals("MANIFEST.MF"))
902 return super.visitFile(file
, attrs
);
903 JarEntry entry
= new JarEntry(bundleDir
.relativize(file
).toString());
904 jarOut
.putNextEntry(entry
);
905 Files
.copy(file
, jarOut
);
906 return super.visitFile(file
, attrs
);
911 deleteDirectory(bundleDir
);
915 /** For development purproses. */
916 public static void main(String
[] args
) {
917 Path factoryBase
= Paths
.get("../../output/a2").toAbsolutePath().normalize();
918 A2Factory factory
= new A2Factory(factoryBase
);
920 Path descriptorsBase
= Paths
.get("../tp").toAbsolutePath().normalize();
922 // factory.processSingleM2ArtifactDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache").resolve("org.apache.xml.resolver.bnd"));
923 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache/apache-sshd"));
924 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.jetty/jetty"));
925 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.jetty"));
926 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.jetty.websocket"));
927 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.eclipse.rcp"));
928 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp"));
929 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.apache"));
930 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.formats"));
931 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.gis"));
935 factory
.processEclipseArchive(
936 descriptorsBase
.resolve("org.argeo.tp.eclipse.equinox").resolve("eclipse-equinox"));
937 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.rwt").resolve("eclipse-rwt"));
938 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.rap").resolve("eclipse-rap"));
939 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.swt").resolve("eclipse-swt"));
940 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.swt").resolve("eclipse-nebula"));
941 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.swt").resolve("eclipse-equinox"));
942 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.rcp").resolve("eclipse-rcp"));
943 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.eclipse.rcp"));
946 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.sdk"));
947 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp"));
948 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.apache"));
949 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.jetty"));
950 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.jcr"));
951 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.formats"));
952 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.poi"));
953 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.gis"));