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/LICENSE"))
305 Path target
= targetBundleDir
.resolve(entry
.getName());
306 Files
.createDirectories(target
.getParent());
307 if (!Files
.exists(target
)) {
308 Files
.copy(jarIn
, target
);
310 if (entry
.getName().startsWith("META-INF/services/")) {
311 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
312 out
.write("\n".getBytes());
313 jarIn
.transferTo(out
);
314 if (logger
.isLoggable(DEBUG
))
315 logger
.log(DEBUG
, artifact
.getArtifactId() + " - Appended " + entry
.getName());
317 } else if (entry
.getName().startsWith("org/apache/batik/")) {
318 logger
.log(Level
.WARNING
, "Skip " + entry
.getName());
321 throw new IllegalStateException("File " + target
+ " from " + artifact
+ " already exists");
324 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
328 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
331 // additional service files
332 Path servicesDir
= duDir
.resolve("services");
333 if (Files
.exists(servicesDir
)) {
334 for (Path p
: Files
.newDirectoryStream(servicesDir
)) {
335 Path target
= targetBundleDir
.resolve("META-INF/services/").resolve(p
.getFileName());
336 try (InputStream in
= Files
.newInputStream(p
);
337 OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
);) {
338 out
.write("\n".getBytes());
340 if (logger
.isLoggable(DEBUG
))
341 logger
.log(DEBUG
, "Appended " + p
);
346 Map
<String
, String
> entries
= new TreeMap
<>();
347 try (Analyzer bndAnalyzer
= new Analyzer()) {
348 bndAnalyzer
.setProperties(mergeProps
);
349 Jar jar
= new Jar(targetBundleDir
.toFile());
350 bndAnalyzer
.setJar(jar
);
351 Manifest manifest
= bndAnalyzer
.calcManifest();
353 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
354 Object value
= manifest
.getMainAttributes().get(key
);
356 switch (key
.toString()) {
358 case "Bnd-LastModified":
362 if ("Require-Capability".equals(key
.toString())
363 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
364 continue keys
;// hack for very old classes
365 entries
.put(key
.toString(), value
.toString());
366 // logger.log(DEBUG, () -> key + "=" + value);
369 } catch (Exception e
) {
370 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
373 Manifest manifest
= new Manifest();
374 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
375 Files
.createDirectories(manifestPath
.getParent());
376 for (String key
: entries
.keySet()) {
377 String value
= entries
.get(key
);
378 manifest
.getMainAttributes().putValue(key
, value
);
381 // // Use Maven version as Bundle-Version
382 // String bundleVersion = manifest.getMainAttributes().getValue(ManifestConstants.BUNDLE_VERSION.toString());
383 // if (bundleVersion == null || bundleVersion.trim().equals("0")) {
384 // // TODO check why it is sometimes set to "0"
385 // manifest.getMainAttributes().putValue(ManifestConstants.BUNDLE_VERSION.toString(), m2Version);
387 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
391 createJar(targetBundleDir
);
395 /** Generate MANIFEST using BND. */
396 protected Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
,
397 DefaultArtifact artifact
) {
400 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
401 boolean doNotModify
= Boolean
.parseBoolean(fileProps
402 .getOrDefault(ManifestConstants
.SLC_ORIGIN_MANIFEST_NOT_MODIFIED
.toString(), "false").toString());
404 // we always force the symbolic name
407 fileEntries
: for (Object key
: fileProps
.keySet()) {
408 if (ManifestConstants
.SLC_ORIGIN_M2
.toString().equals(key
))
409 continue fileEntries
;
410 String value
= fileProps
.getProperty(key
.toString());
411 additionalEntries
.put(key
.toString(), value
);
414 if (artifact
!= null) {
415 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
416 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
418 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
419 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
423 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
424 fileProps
.put(EXPORT_PACKAGE
.toString(),
425 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
427 // if (!fileProps.contains(IMPORT_PACKAGE.toString())) {
428 // fileProps.put(IMPORT_PACKAGE.toString(), "*");
431 try (Analyzer bndAnalyzer
= new Analyzer()) {
432 bndAnalyzer
.setProperties(fileProps
);
433 Jar jar
= new Jar(downloaded
.toFile());
434 bndAnalyzer
.setJar(jar
);
435 Manifest manifest
= bndAnalyzer
.calcManifest();
437 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
438 Object value
= manifest
.getMainAttributes().get(key
);
440 switch (key
.toString()) {
442 case "Bnd-LastModified":
446 if ("Require-Capability".equals(key
.toString())
447 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
448 continue keys
;// hack for very old classes
449 additionalEntries
.put(key
.toString(), value
.toString());
450 // logger.log(DEBUG, () -> key + "=" + value);
455 // try (Builder bndBuilder = new Builder()) {
456 // Jar jar = new Jar(downloaded.toFile());
457 // bndBuilder.addClasspath(jar);
458 // Path targetBundleDir = targetCategoryBase.resolve(artifact.getName() + "." + artifact.getBranch());
460 // Jar target = new Jar(targetBundleDir.toFile());
461 // bndBuilder.setJar(target);
462 // return targetBundleDir;
465 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
);
466 logger
.log(Level
.DEBUG
, () -> "Processed " + downloaded
);
467 return targetBundleDir
;
468 } catch (Exception e
) {
469 throw new RuntimeException("Cannot BND process " + downloaded
, e
);
474 /** Download and integrates sources for a single Maven artifact. */
475 protected void downloadAndProcessM2Sources(String repoStr
, DefaultArtifact artifact
, Path targetBundleDir
)
477 DefaultArtifact sourcesArtifact
= new DefaultArtifact(artifact
.toM2Coordinates(), "sources");
478 URL sourcesUrl
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
479 Path sourcesDownloaded
= download(sourcesUrl
, originBase
, artifact
, true);
480 processM2SourceJar(sourcesDownloaded
, targetBundleDir
);
481 logger
.log(Level
.TRACE
, () -> "Processed source " + sourcesDownloaded
);
485 /** Integrate sources from a downloaded jar file. */
486 protected void processM2SourceJar(Path file
, Path targetBundleDir
) throws IOException
{
487 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
488 Path targetSourceDir
= targetBundleDir
.resolve("OSGI-OPT/src");
490 // TODO make it less dangerous?
491 if (Files
.exists(targetSourceDir
)) {
492 // deleteDirectory(targetSourceDir);
494 Files
.createDirectories(targetSourceDir
);
499 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
500 if (entry
.isDirectory())
502 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
504 if (entry
.getName().startsWith("module-info.java"))// skip META-INF entries
506 if (entry
.getName().startsWith("/")) // absolute paths
508 Path target
= targetSourceDir
.resolve(entry
.getName());
509 Files
.createDirectories(target
.getParent());
510 if (!Files
.exists(target
)) {
511 Files
.copy(jarIn
, target
);
512 logger
.log(Level
.TRACE
, () -> "Copied source " + target
);
514 logger
.log(Level
.WARNING
, () -> target
+ " already exists, skipping...");
521 /** Download a Maven artifact. */
522 protected Path
download(URL url
, Path dir
, Artifact artifact
) throws IOException
{
523 return download(url
, dir
, artifact
, false);
526 /** Download a Maven artifact. */
527 protected Path
download(URL url
, Path dir
, Artifact artifact
, boolean sources
) throws IOException
{
528 return download(url
, dir
, artifact
.getGroupId() + '/' + artifact
.getArtifactId() + "-" + artifact
.getVersion()
529 + (sources ?
"-sources" : "") + ".jar");
536 /** Process an archive in Eclipse format. */
537 public void processEclipseArchive(Path duDir
) {
539 String category
= duDir
.getParent().getFileName().toString();
540 Path targetCategoryBase
= a2Base
.resolve(category
);
541 Files
.createDirectories(targetCategoryBase
);
542 // first delete all directories from previous builds
543 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
))) {
544 deleteDirectory(dir
);
547 Files
.createDirectories(originBase
);
549 Path commonBnd
= duDir
.resolve(COMMON_BND
);
550 Properties commonProps
= new Properties();
551 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
552 commonProps
.load(in
);
554 String url
= commonProps
.getProperty(ManifestConstants
.SLC_ORIGIN_URI
.toString());
555 Path downloaded
= tryDownload(url
, originBase
);
557 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
560 List
<PathMatcher
> includeMatchers
= new ArrayList
<>();
561 Properties includes
= new Properties();
562 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
565 for (Object pattern
: includes
.keySet()) {
566 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
567 includeMatchers
.add(pathMatcher
);
570 List
<PathMatcher
> excludeMatchers
= new ArrayList
<>();
571 Path excludeFile
= duDir
.resolve("excludes.properties");
572 if (Files
.exists(excludeFile
)) {
573 Properties excludes
= new Properties();
574 try (InputStream in
= Files
.newInputStream(excludeFile
)) {
577 for (Object pattern
: excludes
.keySet()) {
578 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
579 excludeMatchers
.add(pathMatcher
);
583 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
586 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
587 includeMatchers
: for (PathMatcher includeMatcher
: includeMatchers
) {
588 if (includeMatcher
.matches(file
)) {
589 for (PathMatcher excludeMatcher
: excludeMatchers
) {
590 if (excludeMatcher
.matches(file
)) {
591 logger
.log(Level
.WARNING
, "Skipping excluded " + file
);
592 return FileVisitResult
.CONTINUE
;
595 if (file
.getFileName().toString().contains(".source_")) {
596 processEclipseSourceJar(file
, targetCategoryBase
);
597 logger
.log(Level
.DEBUG
, () -> "Processed source " + file
);
600 processBundleJar(file
, targetCategoryBase
, new HashMap
<>());
601 logger
.log(Level
.DEBUG
, () -> "Processed " + file
);
603 break includeMatchers
;
606 return FileVisitResult
.CONTINUE
;
610 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
611 for (Path dir
: dirs
) {
614 } catch (IOException e
) {
615 throw new RuntimeException("Cannot process " + duDir
, e
);
620 /** Process sources in Eclipse format. */
621 protected void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
623 Path targetBundleDir
;
624 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
625 Manifest manifest
= jarIn
.getManifest();
627 String
[] relatedBundle
= manifest
.getMainAttributes().getValue("Eclipse-SourceBundle").split(";");
628 String version
= relatedBundle
[1].substring("version=\"".length());
629 version
= version
.substring(0, version
.length() - 1);
630 NameVersion nameVersion
= new DefaultNameVersion(relatedBundle
[0], version
);
631 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
633 Path targetSourceDir
= targetBundleDir
.resolve("OSGI-OPT/src");
635 // TODO make it less dangerous?
636 if (Files
.exists(targetSourceDir
)) {
637 // deleteDirectory(targetSourceDir);
639 Files
.createDirectories(targetSourceDir
);
644 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
645 if (entry
.isDirectory())
647 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
649 Path target
= targetSourceDir
.resolve(entry
.getName());
650 Files
.createDirectories(target
.getParent());
651 Files
.copy(jarIn
, target
);
652 logger
.log(Level
.TRACE
, () -> "Copied source " + target
);
656 // Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
657 // Files.createDirectories(manifestPath.getParent());
658 // try (OutputStream out = Files.newOutputStream(manifestPath)) {
659 // manifest.write(out);
662 } catch (IOException e
) {
663 throw new IllegalStateException("Cannot process " + file
, e
);
671 /** Normalise a bundle. */
672 protected Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
) throws IOException
{
673 DefaultNameVersion nameVersion
;
674 Path targetBundleDir
;
675 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
676 Manifest sourceManifest
= jarIn
.getManifest();
677 Manifest manifest
= sourceManifest
!= null ?
new Manifest(sourceManifest
) : new Manifest();
679 // remove problematic entries in MANIFEST
680 manifest
.getEntries().clear();
681 // Set<String> entriesToDelete = new HashSet<>();
682 // for (String key : manifest.getEntries().keySet()) {
683 //// logger.log(DEBUG, "## " + key);
684 // Attributes attrs = manifest.getAttributes(key);
685 // for (Object attrName : attrs.keySet()) {
686 //// logger.log(DEBUG, attrName + "=" + attrs.get(attrName));
687 // if ("Specification-Version".equals(attrName.toString())
688 // || "Implementation-Version".equals(attrName.toString())) {
689 // entriesToDelete.add(key);
694 // for (String key : entriesToDelete) {
695 // manifest.getEntries().remove(key);
698 String symbolicNameFromEntries
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
699 String versionFromEntries
= entries
.get(BUNDLE_VERSION
.toString());
701 if (symbolicNameFromEntries
!= null && versionFromEntries
!= null) {
702 nameVersion
= new DefaultNameVersion(symbolicNameFromEntries
, versionFromEntries
);
704 nameVersion
= nameVersionFromManifest(manifest
);
705 if (versionFromEntries
!= null && !nameVersion
.getVersion().equals(versionFromEntries
)) {
706 logger
.log(Level
.WARNING
, "Original version is " + nameVersion
.getVersion()
707 + " while new version is " + versionFromEntries
);
709 if (symbolicNameFromEntries
!= null) {
710 // we always force our symbolic name
711 nameVersion
.setName(symbolicNameFromEntries
);
714 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
716 // TODO make it less dangerous?
717 // if (Files.exists(targetBundleDir)) {
718 // deleteDirectory(targetBundleDir);
723 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
724 if (entry
.isDirectory())
726 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
728 Path target
= targetBundleDir
.resolve(entry
.getName());
729 Files
.createDirectories(target
.getParent());
730 Files
.copy(jarIn
, target
);
731 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
735 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
736 Files
.createDirectories(manifestPath
.getParent());
737 for (String key
: entries
.keySet()) {
738 String value
= entries
.get(key
);
739 Object previousValue
= manifest
.getMainAttributes().putValue(key
, value
);
740 if (previousValue
!= null && !previousValue
.equals(value
)) {
741 if (ManifestConstants
.IMPORT_PACKAGE
.toString().equals(key
)
742 || ManifestConstants
.EXPORT_PACKAGE
.toString().equals(key
))
743 logger
.log(Level
.WARNING
, file
.getFileName() + ": " + key
+ " was modified");
746 logger
.log(Level
.WARNING
, file
.getFileName() + ": " + key
+ " was " + previousValue
747 + ", overridden with " + value
);
750 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
754 return targetBundleDir
;
761 /** Recursively deletes a directory. */
762 private static void deleteDirectory(Path path
) throws IOException
{
763 if (!Files
.exists(path
))
765 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
767 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
770 Files
.delete(directory
);
771 return FileVisitResult
.CONTINUE
;
775 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
777 return FileVisitResult
.CONTINUE
;
782 /** Extract name/version from a MANIFEST. */
783 protected DefaultNameVersion
nameVersionFromManifest(Manifest manifest
) {
784 Attributes attrs
= manifest
.getMainAttributes();
786 String symbolicName
= attrs
.getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
787 if (symbolicName
== null)
789 // make sure there is no directive
790 symbolicName
= symbolicName
.split(";")[0];
792 String version
= attrs
.getValue(ManifestConstants
.BUNDLE_VERSION
.toString());
793 return new DefaultNameVersion(symbolicName
, version
);
796 /** Try to download from an URI. */
797 protected Path
tryDownload(String uri
, Path dir
) throws IOException
{
799 List
<String
> urlBases
= null;
800 String uriPrefix
= null;
801 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
802 if (uri
.startsWith(uriPref
)) {
803 if (mirrors
.get(uriPref
).size() > 0) {
804 urlBases
= mirrors
.get(uriPref
);
810 if (urlBases
== null)
812 return download(new URL(uri
), dir
);
813 } catch (FileNotFoundException e
) {
814 throw new FileNotFoundException("Cannot find " + uri
);
818 for (String urlBase
: urlBases
) {
819 String relativePath
= uri
.substring(uriPrefix
.length());
820 URL url
= new URL(urlBase
+ relativePath
);
822 return download(url
, dir
);
823 } catch (FileNotFoundException e
) {
824 logger
.log(Level
.WARNING
, "Cannot download " + url
+ ", trying another mirror");
827 throw new FileNotFoundException("Cannot find " + uri
);
830 // protected String simplifyName(URL u) {
831 // String name = u.getPath().substring(u.getPath().lastIndexOf('/') + 1);
835 /** Effectively download. */
836 protected Path
download(URL url
, Path dir
) throws IOException
{
837 return download(url
, dir
, (String
) null);
840 /** Effectively download. */
841 protected Path
download(URL url
, Path dir
, String name
) throws IOException
{
845 name
= url
.getPath().substring(url
.getPath().lastIndexOf('/') + 1);
848 dest
= dir
.resolve(name
);
849 if (Files
.exists(dest
)) {
850 logger
.log(Level
.TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
853 Files
.createDirectories(dest
.getParent());
856 try (InputStream in
= url
.openStream()) {
857 Files
.copy(in
, dest
);
858 logger
.log(Level
.DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
863 /** Create a JAR file from a directory. */
864 protected Path
createJar(Path bundleDir
) throws IOException
{
865 // Remove from source the resources already in the jar file
866 // Path srcDir = bundleDir.resolve("OSGI-OPT/src");
867 // Files.walkFileTree(srcDir, new SimpleFileVisitor<Path>() {
870 // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
871 // // always keep .java file
872 // if (file.getFileName().toString().endsWith(".java"))
873 // return super.visitFile(file, attrs);
875 // Path relPath = srcDir.relativize(file);
876 // Path bundlePath = bundleDir.resolve(relPath);
877 // if (Files.exists(bundlePath)) {
878 // Files.delete(file);
879 // logger.log(DEBUG, () -> "Removed " + file + " from sources.");
881 // return super.visitFile(file, attrs);
887 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
888 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
890 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
891 manifest
= new Manifest(in
);
893 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
894 jarOut
.setLevel(Deflater
.DEFAULT_COMPRESSION
);
895 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
898 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
899 if (file
.getFileName().toString().equals("MANIFEST.MF"))
900 return super.visitFile(file
, attrs
);
901 JarEntry entry
= new JarEntry(bundleDir
.relativize(file
).toString());
902 jarOut
.putNextEntry(entry
);
903 Files
.copy(file
, jarOut
);
904 return super.visitFile(file
, attrs
);
909 deleteDirectory(bundleDir
);
913 /** For development purproses. */
914 public static void main(String
[] args
) {
915 Path factoryBase
= Paths
.get("../../output/a2").toAbsolutePath().normalize();
916 A2Factory factory
= new A2Factory(factoryBase
);
918 Path descriptorsBase
= Paths
.get("../tp").toAbsolutePath().normalize();
920 // factory.processSingleM2ArtifactDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache").resolve("org.apache.xml.resolver.bnd"));
921 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache/apache-sshd"));
922 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.jetty/jetty"));
923 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.jetty/jetty-websocket"));
924 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.eclipse.rcp"));
925 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp"));
926 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.apache"));
927 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.formats"));
928 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.gis"));
932 factory
.processEclipseArchive(
933 descriptorsBase
.resolve("org.argeo.tp.eclipse.equinox").resolve("eclipse-equinox"));
934 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.rwt").resolve("eclipse-rwt"));
935 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.rap").resolve("eclipse-rap"));
936 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.swt").resolve("eclipse-swt"));
937 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.swt").resolve("eclipse-nebula"));
938 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.swt").resolve("eclipse-equinox"));
939 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.rcp").resolve("eclipse-rcp"));
940 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.eclipse.rcp"));
943 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.sdk"));
944 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp"));
945 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.apache"));
946 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.jetty"));
947 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.jcr"));
948 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.formats"));
949 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.poi"));
950 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.gis"));