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
;
40 import org
.argeo
.slc
.DefaultCategoryNameVersion
;
41 import org
.argeo
.slc
.DefaultNameVersion
;
42 import org
.argeo
.slc
.ManifestConstants
;
43 import org
.argeo
.slc
.NameVersion
;
44 import org
.argeo
.slc
.factory
.m2
.Artifact
;
45 import org
.argeo
.slc
.factory
.m2
.DefaultArtifact
;
46 import org
.argeo
.slc
.factory
.m2
.MavenConventionsUtils
;
48 import aQute
.bnd
.osgi
.Analyzer
;
49 import aQute
.bnd
.osgi
.Jar
;
51 /** The central class for A2 packaging. */
52 public class A2Factory
{
53 private final static Logger logger
= System
.getLogger(A2Factory
.class.getName());
55 private final static String COMMON_BND
= "common.bnd";
56 private final static String MERGE_BND
= "merge.bnd";
58 private Path originBase
;
61 /** key is URI prefix, value list of base URLs */
62 private Map
<String
, List
<String
>> mirrors
= new HashMap
<String
, List
<String
>>();
64 public A2Factory(Path a2Base
) {
65 this.originBase
= Paths
.get(System
.getProperty("user.home"), ".cache", "argeo/slc/origin");
68 // TODO make it configurable
69 List
<String
> eclipseMirrors
= new ArrayList
<>();
70 eclipseMirrors
.add("https://archive.eclipse.org/");
71 eclipseMirrors
.add("http://ftp-stud.hs-esslingen.de/Mirrors/eclipse/");
72 eclipseMirrors
.add("http://ftp.fau.de/eclipse/");
74 mirrors
.put("http://www.eclipse.org/downloads", eclipseMirrors
);
81 /** Process a whole category/group id. */
82 public void processCategory(Path targetCategoryBase
) {
84 DirectoryStream
<Path
> bnds
= Files
.newDirectoryStream(targetCategoryBase
,
85 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
86 && !p
.getFileName().toString().equals(MERGE_BND
));
88 processSingleM2ArtifactDistributionUnit(p
);
91 DirectoryStream
<Path
> dus
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
92 for (Path duDir
: dus
) {
93 processM2BasedDistributionUnit(duDir
);
95 } catch (IOException e
) {
96 throw new RuntimeException("Cannot process category " + targetCategoryBase
, e
);
100 /** Process a standalone Maven artifact. */
101 public void processSingleM2ArtifactDistributionUnit(Path bndFile
) {
103 String category
= bndFile
.getParent().getFileName().toString();
104 Path targetCategoryBase
= a2Base
.resolve(category
);
105 Properties fileProps
= new Properties();
106 try (InputStream in
= Files
.newInputStream(bndFile
)) {
109 String repoStr
= fileProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
110 ? fileProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
113 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())
114 && !fileProps
.containsKey(ManifestConstants
.SLC_ORIGIN_MANIFEST_NOT_MODIFIED
.toString())) {
115 // use file name as symbolic name
116 String symbolicName
= bndFile
.getFileName().toString();
117 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
118 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
121 String m2Coordinates
= fileProps
.getProperty(SLC_ORIGIN_M2
.toString());
122 if (m2Coordinates
== null)
123 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile
);
124 DefaultArtifact artifact
= new DefaultArtifact(m2Coordinates
);
125 URL url
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
126 Path downloaded
= download(url
, originBase
, artifact
);
128 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, fileProps
, artifact
);
130 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
132 createJar(targetBundleDir
);
133 } catch (Exception e
) {
134 throw new RuntimeException("Cannot process " + bndFile
, e
);
138 /** Process multiple Maven artifacts. */
139 public void processM2BasedDistributionUnit(Path duDir
) {
141 String category
= duDir
.getParent().getFileName().toString();
142 Path targetCategoryBase
= a2Base
.resolve(category
);
145 Path mergeBnd
= duDir
.resolve(MERGE_BND
);
146 if (Files
.exists(mergeBnd
)) {
147 mergeM2Artifacts(mergeBnd
);
151 Path commonBnd
= duDir
.resolve(COMMON_BND
);
152 if (!Files
.exists(commonBnd
)) {
155 Properties commonProps
= new Properties();
156 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
157 commonProps
.load(in
);
160 String m2Version
= commonProps
.getProperty(SLC_ORIGIN_M2
.toString());
161 if (m2Version
== null) {
162 logger
.log(Level
.WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
163 return;// ignore, this is probably an Eclipse archive
165 if (!m2Version
.startsWith(":")) {
166 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
168 m2Version
= m2Version
.substring(1);
170 DirectoryStream
<Path
> ds
= Files
.newDirectoryStream(duDir
,
171 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
172 && !p
.getFileName().toString().equals(MERGE_BND
));
174 Properties fileProps
= new Properties();
175 try (InputStream in
= Files
.newInputStream(p
)) {
178 String m2Coordinates
= fileProps
.getProperty(SLC_ORIGIN_M2
.toString());
179 DefaultArtifact artifact
= new DefaultArtifact(m2Coordinates
);
181 // temporary rewrite, for migration
182 // String localLicense = fileProps.getProperty(BUNDLE_LICENSE.toString());
183 // if (localLicense != null || artifact.getVersion() != null) {
184 // fileProps.remove(BUNDLE_LICENSE.toString());
185 // fileProps.put(SLC_ORIGIN_M2.toString(), artifact.getGroupId() + ":" + artifact.getArtifactId());
186 // try (Writer writer = Files.newBufferedWriter(p)) {
187 // for (Object key : fileProps.keySet()) {
188 // String value = fileProps.getProperty(key.toString());
189 // writer.write(key + ": " + value + '\n');
191 // logger.log(DEBUG, () -> "Migrated " + p);
195 artifact
.setVersion(m2Version
);
197 // prepare manifest entries
198 Properties mergeProps
= new Properties();
199 mergeProps
.putAll(commonProps
);
201 fileEntries
: for (Object key
: fileProps
.keySet()) {
202 if (ManifestConstants
.SLC_ORIGIN_M2
.toString().equals(key
))
203 continue fileEntries
;
204 String value
= fileProps
.getProperty(key
.toString());
205 Object previousValue
= mergeProps
.put(key
.toString(), value
);
206 if (previousValue
!= null) {
207 logger
.log(Level
.WARNING
,
208 commonBnd
+ ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
211 mergeProps
.put(ManifestConstants
.SLC_ORIGIN_M2
.toString(), artifact
.toM2Coordinates());
212 if (!mergeProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())
213 && !mergeProps
.containsKey(ManifestConstants
.SLC_ORIGIN_MANIFEST_NOT_MODIFIED
.toString())) {
214 // use file name as symbolic name
215 String symbolicName
= p
.getFileName().toString();
216 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
217 mergeProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
220 String repoStr
= mergeProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
221 ? mergeProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
225 URL url
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
226 Path downloaded
= download(url
, originBase
, artifact
);
228 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, mergeProps
, artifact
);
229 // logger.log(Level.DEBUG, () -> "Processed " + downloaded);
232 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
234 createJar(targetBundleDir
);
236 } catch (IOException e
) {
237 throw new RuntimeException("Cannot process " + duDir
, e
);
242 /** Merge multiple Maven artifacts. */
243 protected void mergeM2Artifacts(Path mergeBnd
) throws IOException
{
244 Path duDir
= mergeBnd
.getParent();
245 String category
= duDir
.getParent().getFileName().toString();
246 Path targetCategoryBase
= a2Base
.resolve(category
);
248 Properties mergeProps
= new Properties();
249 try (InputStream in
= Files
.newInputStream(mergeBnd
)) {
252 String m2Version
= mergeProps
.getProperty(SLC_ORIGIN_M2
.toString());
253 if (m2Version
== null) {
254 logger
.log(Level
.WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
255 return;// ignore, this is probably an Eclipse archive
257 if (!m2Version
.startsWith(":")) {
258 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
260 m2Version
= m2Version
.substring(1);
262 String artifactsStr
= mergeProps
.getProperty(ManifestConstants
.SLC_ORIGIN_M2_MERGE
.toString());
263 String repoStr
= mergeProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
264 ? mergeProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
267 String bundleSymbolicName
= mergeProps
.getProperty(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
268 if (bundleSymbolicName
== null)
269 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd
);
270 DefaultCategoryNameVersion nameVersion
= new DefaultArtifact(
271 category
+ ":" + bundleSymbolicName
+ ":" + m2Version
);
272 Path targetBundleDir
= targetCategoryBase
.resolve(bundleSymbolicName
+ "." + nameVersion
.getBranch());
274 String
[] artifacts
= artifactsStr
.split(",");
275 artifacts
: for (String str
: artifacts
) {
276 String m2Coordinates
= str
.trim();
277 if ("".equals(m2Coordinates
))
279 DefaultArtifact artifact
= new DefaultArtifact(m2Coordinates
.trim());
280 if (artifact
.getVersion() == null)
281 artifact
.setVersion(m2Version
);
282 URL url
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
283 Path downloaded
= download(url
, originBase
, artifact
);
285 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(downloaded
), false)) {
286 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
287 if (entry
.isDirectory())
289 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
291 if (entry
.getName().startsWith("META-INF/versions/"))
293 if (entry
.getName().startsWith("META-INF/maven/"))
295 if (entry
.getName().equals("module-info.class"))
297 if (entry
.getName().equals("META-INF/NOTICE"))
299 if (entry
.getName().equals("META-INF/LICENSE"))
301 Path target
= targetBundleDir
.resolve(entry
.getName());
302 Files
.createDirectories(target
.getParent());
303 if (!Files
.exists(target
)) {
304 Files
.copy(jarIn
, target
);
306 if (entry
.getName().startsWith("META-INF/services/")) {
307 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
308 out
.write("\n".getBytes());
309 jarIn
.transferTo(out
);
310 if (logger
.isLoggable(DEBUG
))
311 logger
.log(DEBUG
, "Appended " + entry
.getName());
313 } else if (entry
.getName().startsWith("org/apache/batik/")) {
314 logger
.log(Level
.WARNING
, "Skip " + entry
.getName());
317 throw new IllegalStateException("File " + target
+ " from " + artifact
+ " already exists");
320 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
324 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
327 // additional service files
328 Path servicesDir
= duDir
.resolve("services");
329 if (Files
.exists(servicesDir
)) {
330 for (Path p
: Files
.newDirectoryStream(servicesDir
)) {
331 Path target
= targetBundleDir
.resolve("META-INF/services/").resolve(p
.getFileName());
332 try (InputStream in
= Files
.newInputStream(p
);
333 OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
);) {
334 out
.write("\n".getBytes());
336 if (logger
.isLoggable(DEBUG
))
337 logger
.log(DEBUG
, "Appended " + p
);
342 Map
<String
, String
> entries
= new TreeMap
<>();
343 try (Analyzer bndAnalyzer
= new Analyzer()) {
344 bndAnalyzer
.setProperties(mergeProps
);
345 Jar jar
= new Jar(targetBundleDir
.toFile());
346 bndAnalyzer
.setJar(jar
);
347 Manifest manifest
= bndAnalyzer
.calcManifest();
349 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
350 Object value
= manifest
.getMainAttributes().get(key
);
352 switch (key
.toString()) {
354 case "Bnd-LastModified":
358 if ("Require-Capability".equals(key
.toString())
359 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
360 continue keys
;// hack for very old classes
361 entries
.put(key
.toString(), value
.toString());
362 //logger.log(DEBUG, () -> key + "=" + value);
365 } catch (Exception e
) {
366 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
369 Manifest manifest
= new Manifest();
370 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
371 Files
.createDirectories(manifestPath
.getParent());
372 for (String key
: entries
.keySet()) {
373 String value
= entries
.get(key
);
374 manifest
.getMainAttributes().putValue(key
, value
);
377 // Use Maven version as Bundle-Version
378 String bundleVersion
= manifest
.getMainAttributes().getValue(ManifestConstants
.BUNDLE_VERSION
.toString());
379 if (bundleVersion
== null || bundleVersion
.trim().equals("0")) {
380 // TODO check why it is sometimes set to "0"
381 manifest
.getMainAttributes().putValue(ManifestConstants
.BUNDLE_VERSION
.toString(), m2Version
);
383 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
387 createJar(targetBundleDir
);
391 /** Generate MANIFEST using BND. */
392 protected Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
,
393 DefaultArtifact artifact
) {
396 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
397 boolean doNotModify
= Boolean
.parseBoolean(fileProps
398 .getOrDefault(ManifestConstants
.SLC_ORIGIN_MANIFEST_NOT_MODIFIED
.toString(), "false").toString());
400 // we always force the symbolic name
403 fileEntries
: for (Object key
: fileProps
.keySet()) {
404 if (ManifestConstants
.SLC_ORIGIN_M2
.toString().equals(key
))
405 continue fileEntries
;
406 String value
= fileProps
.getProperty(key
.toString());
407 additionalEntries
.put(key
.toString(), value
);
410 if (artifact
!= null) {
411 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
412 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
414 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
415 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
419 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
420 fileProps
.put(EXPORT_PACKAGE
.toString(),
421 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
423 // if (!fileProps.contains(IMPORT_PACKAGE.toString())) {
424 // fileProps.put(IMPORT_PACKAGE.toString(), "*");
427 try (Analyzer bndAnalyzer
= new Analyzer()) {
428 bndAnalyzer
.setProperties(fileProps
);
429 Jar jar
= new Jar(downloaded
.toFile());
430 bndAnalyzer
.setJar(jar
);
431 Manifest manifest
= bndAnalyzer
.calcManifest();
433 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
434 Object value
= manifest
.getMainAttributes().get(key
);
436 switch (key
.toString()) {
438 case "Bnd-LastModified":
442 if ("Require-Capability".equals(key
.toString())
443 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
444 continue keys
;// hack for very old classes
445 additionalEntries
.put(key
.toString(), value
.toString());
446 //logger.log(DEBUG, () -> key + "=" + value);
451 // try (Builder bndBuilder = new Builder()) {
452 // Jar jar = new Jar(downloaded.toFile());
453 // bndBuilder.addClasspath(jar);
454 // Path targetBundleDir = targetCategoryBase.resolve(artifact.getName() + "." + artifact.getBranch());
456 // Jar target = new Jar(targetBundleDir.toFile());
457 // bndBuilder.setJar(target);
458 // return targetBundleDir;
461 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
);
462 logger
.log(Level
.DEBUG
, () -> "Processed " + downloaded
);
463 return targetBundleDir
;
464 } catch (Exception e
) {
465 throw new RuntimeException("Cannot BND process " + downloaded
, e
);
470 /** Download and integrates sources for a single Maven artifact. */
471 protected void downloadAndProcessM2Sources(String repoStr
, DefaultArtifact artifact
, Path targetBundleDir
)
473 DefaultArtifact sourcesArtifact
= new DefaultArtifact(artifact
.toM2Coordinates(), "sources");
474 URL sourcesUrl
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
475 Path sourcesDownloaded
= download(sourcesUrl
, originBase
, artifact
, true);
476 processM2SourceJar(sourcesDownloaded
, targetBundleDir
);
477 logger
.log(Level
.DEBUG
, () -> "Processed source " + sourcesDownloaded
);
481 /** Integrate sources from a downloaded jar file. */
482 protected void processM2SourceJar(Path file
, Path targetBundleDir
) throws IOException
{
483 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
484 Path targetSourceDir
= targetBundleDir
.resolve("OSGI-OPT/src");
486 // TODO make it less dangerous?
487 if (Files
.exists(targetSourceDir
)) {
488 // deleteDirectory(targetSourceDir);
490 Files
.createDirectories(targetSourceDir
);
495 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
496 if (entry
.isDirectory())
498 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
500 if (entry
.getName().startsWith("module-info.java"))// skip META-INF entries
502 if (entry
.getName().startsWith("/")) // absolute paths
504 Path target
= targetSourceDir
.resolve(entry
.getName());
505 Files
.createDirectories(target
.getParent());
506 if (!Files
.exists(target
)) {
507 Files
.copy(jarIn
, target
);
508 logger
.log(Level
.TRACE
, () -> "Copied source " + target
);
510 logger
.log(Level
.WARNING
, () -> target
+ " already exists, skipping...");
517 /** Download a Maven artifact. */
518 protected Path
download(URL url
, Path dir
, Artifact artifact
) throws IOException
{
519 return download(url
, dir
, artifact
, false);
522 /** Download a Maven artifact. */
523 protected Path
download(URL url
, Path dir
, Artifact artifact
, boolean sources
) throws IOException
{
524 return download(url
, dir
, artifact
.getGroupId() + '/' + artifact
.getArtifactId() + "-" + artifact
.getVersion()
525 + (sources ?
"-sources" : "") + ".jar");
532 /** Process an archive in Eclipse format. */
533 public void processEclipseArchive(Path duDir
) {
535 String category
= duDir
.getParent().getFileName().toString();
536 Path targetCategoryBase
= a2Base
.resolve(category
);
537 Files
.createDirectories(targetCategoryBase
);
538 // first delete all directories from previous builds
539 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
))) {
540 deleteDirectory(dir
);
543 Files
.createDirectories(originBase
);
545 Path commonBnd
= duDir
.resolve(COMMON_BND
);
546 Properties commonProps
= new Properties();
547 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
548 commonProps
.load(in
);
550 String url
= commonProps
.getProperty(ManifestConstants
.SLC_ORIGIN_URI
.toString());
551 Path downloaded
= tryDownload(url
, originBase
);
553 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
556 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
557 Properties includes
= new Properties();
558 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
561 for (Object pattern
: includes
.keySet()) {
562 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
563 includeMatchers
.add(pathMatcher
);
566 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
567 Path excludeFile
= duDir
.resolve("excludes.properties");
568 if (Files
.exists(excludeFile
)) {
569 Properties excludes
= new Properties();
570 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
573 for (Object pattern
: excludes
.keySet()) {
574 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
575 excludeMatchers
.add(pathMatcher
);
579 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
582 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
583 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
584 if (includeMatcher
.matches(file
)) {
585 for (PathMatcher excludeMatcher
: excludeMatchers
) {
586 if (excludeMatcher
.matches(file
)) {
587 logger
.log(Level
.WARNING
, "Skipping excluded " + file
);
588 return FileVisitResult
.CONTINUE
;
591 if (file
.getFileName().toString().contains(".source_")) {
592 processEclipseSourceJar(file
, targetCategoryBase
);
593 logger
.log(Level
.DEBUG
, () -> "Processed source " + file
);
596 processBundleJar(file
, targetCategoryBase
, new HashMap
<>());
597 logger
.log(Level
.DEBUG
, () -> "Processed " + file
);
599 break includeMatchers
;
602 return FileVisitResult
.CONTINUE
;
606 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
607 for (Path dir
: dirs
) {
610 } catch (IOException e
) {
611 throw new RuntimeException("Cannot process " + duDir
, e
);
616 /** Process sources in Eclipse format. */
617 protected void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
619 Path targetBundleDir
;
620 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
621 Manifest manifest
= jarIn
.getManifest();
623 String
[] relatedBundle
= manifest
.getMainAttributes().getValue("Eclipse-SourceBundle").split(";");
624 String version
= relatedBundle
[1].substring("version=\"".length());
625 version
= version
.substring(0, version
.length() - 1);
626 NameVersion nameVersion
= new DefaultNameVersion(relatedBundle
[0], version
);
627 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
629 Path targetSourceDir
= targetBundleDir
.resolve("OSGI-OPT/src");
631 // TODO make it less dangerous?
632 if (Files
.exists(targetSourceDir
)) {
633 // deleteDirectory(targetSourceDir);
635 Files
.createDirectories(targetSourceDir
);
640 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
641 if (entry
.isDirectory())
643 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
645 Path target
= targetSourceDir
.resolve(entry
.getName());
646 Files
.createDirectories(target
.getParent());
647 Files
.copy(jarIn
, target
);
648 logger
.log(Level
.TRACE
, () -> "Copied source " + target
);
652 // Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
653 // Files.createDirectories(manifestPath.getParent());
654 // try (OutputStream out = Files.newOutputStream(manifestPath)) {
655 // manifest.write(out);
658 } catch (IOException e
) {
659 throw new IllegalStateException("Cannot process " + file
, e
);
667 /** Normalise a bundle. */
668 protected Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
) throws IOException
{
669 DefaultNameVersion nameVersion
;
670 Path targetBundleDir
;
671 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
672 Manifest sourceManifest
= jarIn
.getManifest();
673 Manifest manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
675 // remove problematic entries in MANIFEST
676 manifest
.getEntries().clear();
677 // Set<String> entriesToDelete = new HashSet<>();
678 // for (String key : manifest.getEntries().keySet()) {
679 //// logger.log(DEBUG, "## " + key);
680 // Attributes attrs = manifest.getAttributes(key);
681 // for (Object attrName : attrs.keySet()) {
682 //// logger.log(DEBUG, attrName + "=" + attrs.get(attrName));
683 // if ("Specification-Version".equals(attrName.toString())
684 // || "Implementation-Version".equals(attrName.toString())) {
685 // entriesToDelete.add(key);
690 // for (String key : entriesToDelete) {
691 // manifest.getEntries().remove(key);
694 String symbolicNameFromEntries
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
695 String versionFromEntries
= entries
.get(BUNDLE_VERSION
.toString());
697 if (symbolicNameFromEntries
!= null && versionFromEntries
!= null) {
698 nameVersion
= new DefaultNameVersion(symbolicNameFromEntries
, versionFromEntries
);
700 nameVersion
= nameVersionFromManifest(manifest
);
701 if (versionFromEntries
!= null && !nameVersion
.getVersion().equals(versionFromEntries
)) {
702 logger
.log(Level
.WARNING
, "Original version is " + nameVersion
.getVersion()
703 + " while new version is " + versionFromEntries
);
705 if (symbolicNameFromEntries
!= null) {
706 // we always force our symbolic name
707 nameVersion
.setName(symbolicNameFromEntries
);
710 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
712 // TODO make it less dangerous?
713 // if (Files.exists(targetBundleDir)) {
714 // deleteDirectory(targetBundleDir);
719 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
720 if (entry
.isDirectory())
722 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
724 Path target
= targetBundleDir
.resolve(entry
.getName());
725 Files
.createDirectories(target
.getParent());
726 Files
.copy(jarIn
, target
);
727 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
731 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
732 Files
.createDirectories(manifestPath
.getParent());
733 for (String key
: entries
.keySet()) {
734 String value
= entries
.get(key
);
735 Object previousValue
= manifest
.getMainAttributes().putValue(key
, value
);
736 if (previousValue
!= null && !previousValue
.equals(value
)) {
737 if (ManifestConstants
.IMPORT_PACKAGE
.toString().equals(key
)
738 || ManifestConstants
.EXPORT_PACKAGE
.toString().equals(key
))
739 logger
.log(Level
.WARNING
, file
.getFileName() + ": " + key
+ " was modified");
742 logger
.log(Level
.WARNING
, file
.getFileName() + ": " + key
+ " was " + previousValue
743 + ", overridden with " + value
);
746 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
750 return targetBundleDir
;
757 /** Recursively deletes a directory. */
758 private static void deleteDirectory(Path path
) throws IOException
{
759 if (!Files
.exists(path
))
761 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
763 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
766 Files
.delete(directory
);
767 return FileVisitResult
.CONTINUE
;
771 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
773 return FileVisitResult
.CONTINUE
;
778 /** Extract name/version from a MANIFEST. */
779 protected DefaultNameVersion
nameVersionFromManifest(Manifest manifest
) {
780 Attributes attrs
= manifest
.getMainAttributes();
782 String symbolicName
= attrs
.getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
783 if (symbolicName
== null)
785 // make sure there is no directive
786 symbolicName
= symbolicName
.split(";")[0];
788 String version
= attrs
.getValue(ManifestConstants
.BUNDLE_VERSION
.toString());
789 return new DefaultNameVersion(symbolicName
, version
);
792 /** Try to download from an URI. */
793 protected Path
tryDownload(String uri
, Path dir
) throws IOException
{
795 List
<String
> urlBases
= null;
796 String uriPrefix
= null;
797 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
798 if (uri
.startsWith(uriPref
)) {
799 if (mirrors
.get(uriPref
).size() > 0) {
800 urlBases
= mirrors
.get(uriPref
);
806 if (urlBases
== null)
808 return download(new URL(uri
), dir
);
809 } catch (FileNotFoundException e
) {
810 throw new FileNotFoundException("Cannot find " + uri
);
814 for (String urlBase
: urlBases
) {
815 String relativePath
= uri
.substring(uriPrefix
.length());
816 URL url
= new URL(urlBase
+ relativePath
);
818 return download(url
, dir
);
819 } catch (FileNotFoundException e
) {
820 logger
.log(Level
.WARNING
, "Cannot download " + url
+ ", trying another mirror");
823 throw new FileNotFoundException("Cannot find " + uri
);
826 // protected String simplifyName(URL u) {
827 // String name = u.getPath().substring(u.getPath().lastIndexOf('/') + 1);
831 /** Effectively download. */
832 protected Path
download(URL url
, Path dir
) throws IOException
{
833 return download(url
, dir
, (String
) null);
836 /** Effectively download. */
837 protected Path
download(URL url
, Path dir
, String name
) throws IOException
{
841 name
= url
.getPath().substring(url
.getPath().lastIndexOf('/') + 1);
844 dest
= dir
.resolve(name
);
845 if (Files
.exists(dest
)) {
846 logger
.log(Level
.TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
849 Files
.createDirectories(dest
.getParent());
852 try (InputStream in
= url
.openStream()) {
853 Files
.copy(in
, dest
);
854 logger
.log(Level
.DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
859 /** Create a JAR file from a directory. */
860 protected Path
createJar(Path bundleDir
) throws IOException
{
861 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
862 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
864 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
865 manifest
= new Manifest(in
);
867 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
868 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
871 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
872 if (file
.getFileName().toString().equals("MANIFEST.MF"))
873 return super.visitFile(file
, attrs
);
874 JarEntry entry
= new JarEntry(bundleDir
.relativize(file
).toString());
875 jarOut
.putNextEntry(entry
);
876 Files
.copy(file
, jarOut
);
877 return super.visitFile(file
, attrs
);
882 deleteDirectory(bundleDir
);
886 /** For development purproses. */
887 public static void main(String
[] args
) {
888 Path factoryBase
= Paths
.get("../../output/a2").toAbsolutePath().normalize();
889 A2Factory factory
= new A2Factory(factoryBase
);
891 Path descriptorsBase
= Paths
.get("../tp").toAbsolutePath().normalize();
893 // factory.processSingleM2ArtifactDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache").resolve("org.apache.xml.resolver.bnd"));
894 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache/apache-sshd"));
895 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.jetty/jetty"));
896 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.jetty/jetty-websocket"));
897 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.eclipse.rcp"));
898 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp"));
899 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.apache"));
900 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.formats"));
901 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.gis"));
905 factory
.processEclipseArchive(
906 descriptorsBase
.resolve("org.argeo.tp.eclipse.equinox").resolve("eclipse-equinox"));
907 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.rwt").resolve("eclipse-rwt"));
908 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.rap").resolve("eclipse-rap"));
909 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.swt").resolve("eclipse-swt"));
910 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.swt").resolve("eclipse-nebula"));
911 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.swt").resolve("eclipse-equinox"));
912 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.rcp").resolve("eclipse-rcp"));
913 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.eclipse.rcp"));
916 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.sdk"));
917 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp"));
918 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.apache"));
919 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.jetty"));
920 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.jcr"));
921 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.formats"));
922 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.poi"));
923 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.gis"));