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
.DefaultArtifact
;
45 import org
.argeo
.slc
.factory
.m2
.MavenConventionsUtils
;
47 import aQute
.bnd
.osgi
.Analyzer
;
48 import aQute
.bnd
.osgi
.Jar
;
50 /** The central class for A2 packaging. */
51 public class A2Factory
{
52 private final static Logger logger
= System
.getLogger(A2Factory
.class.getName());
54 private final static String COMMON_BND
= "common.bnd";
55 private final static String MERGE_BND
= "merge.bnd";
57 private Path originBase
;
60 /** key is URI prefix, value list of base URLs */
61 private Map
<String
, List
<String
>> mirrors
= new HashMap
<String
, List
<String
>>();
63 public A2Factory(Path a2Base
) {
64 this.originBase
= Paths
.get(System
.getProperty("user.home"), ".cache", "argeo/slc/origin");
67 // TODO make it configurable
68 List
<String
> eclipseMirrors
= new ArrayList
<>();
69 eclipseMirrors
.add("https://archive.eclipse.org/");
70 eclipseMirrors
.add("http://ftp-stud.hs-esslingen.de/Mirrors/eclipse/");
71 eclipseMirrors
.add("http://ftp.fau.de/eclipse/");
73 mirrors
.put("http://www.eclipse.org/downloads", eclipseMirrors
);
76 public void processCategory(Path targetCategoryBase
) {
78 DirectoryStream
<Path
> bnds
= Files
.newDirectoryStream(targetCategoryBase
,
79 (p
) -> p
.getFileName().toString().endsWith(".bnd") && !p
.getFileName().toString().equals(COMMON_BND
)
80 && !p
.getFileName().toString().equals(MERGE_BND
));
82 processSingleM2ArtifactDistributionUnit(p
);
85 DirectoryStream
<Path
> dus
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
86 for (Path duDir
: dus
) {
87 processM2BasedDistributionUnit(duDir
);
89 } catch (IOException e
) {
90 throw new RuntimeException("Cannot process category " + targetCategoryBase
, e
);
94 public void processSingleM2ArtifactDistributionUnit(Path bndFile
) {
96 String category
= bndFile
.getParent().getFileName().toString();
97 Path targetCategoryBase
= a2Base
.resolve(category
);
98 Properties fileProps
= new Properties();
99 try (InputStream in
= Files
.newInputStream(bndFile
)) {
102 String repoStr
= fileProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
103 ? fileProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
106 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())
107 && !fileProps
.containsKey(ManifestConstants
.SLC_ORIGIN_MANIFEST_NOT_MODIFIED
.toString())) {
108 // use file name as symbolic name
109 String symbolicName
= bndFile
.getFileName().toString();
110 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
111 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
114 String m2Coordinates
= fileProps
.getProperty(SLC_ORIGIN_M2
.toString());
115 if (m2Coordinates
== null)
116 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile
);
117 DefaultArtifact artifact
= new DefaultArtifact(m2Coordinates
);
118 URL url
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
119 Path downloaded
= download(url
, originBase
, artifact
.toM2Coordinates() + ".jar");
121 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, fileProps
, artifact
);
123 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
125 createJar(targetBundleDir
);
126 } catch (Exception e
) {
127 throw new RuntimeException("Cannot process " + bndFile
, e
);
131 public void processM2BasedDistributionUnit(Path duDir
) {
133 String category
= duDir
.getParent().getFileName().toString();
134 Path targetCategoryBase
= a2Base
.resolve(category
);
137 Path mergeBnd
= duDir
.resolve(MERGE_BND
);
138 if (Files
.exists(mergeBnd
)) {
139 mergeM2Artifacts(mergeBnd
);
143 Path commonBnd
= duDir
.resolve(COMMON_BND
);
144 Properties commonProps
= new Properties();
145 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
146 commonProps
.load(in
);
149 String m2Version
= commonProps
.getProperty(SLC_ORIGIN_M2
.toString());
150 if (m2Version
== null) {
151 logger
.log(Level
.WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
152 return;// ignore, this is probably an Eclipse archive
154 if (!m2Version
.startsWith(":")) {
155 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
157 m2Version
= m2Version
.substring(1);
159 DirectoryStream
<Path
> ds
= Files
.newDirectoryStream(duDir
,
160 (p
) -> p
.getFileName().toString().endsWith(".bnd")
161 && !p
.getFileName().toString().equals(COMMON_BND
));
163 Properties fileProps
= new Properties();
164 try (InputStream in
= Files
.newInputStream(p
)) {
167 String m2Coordinates
= fileProps
.getProperty(SLC_ORIGIN_M2
.toString());
168 DefaultArtifact artifact
= new DefaultArtifact(m2Coordinates
);
170 // temporary rewrite, for migration
171 // String localLicense = fileProps.getProperty(BUNDLE_LICENSE.toString());
172 // if (localLicense != null || artifact.getVersion() != null) {
173 // fileProps.remove(BUNDLE_LICENSE.toString());
174 // fileProps.put(SLC_ORIGIN_M2.toString(), artifact.getGroupId() + ":" + artifact.getArtifactId());
175 // try (Writer writer = Files.newBufferedWriter(p)) {
176 // for (Object key : fileProps.keySet()) {
177 // String value = fileProps.getProperty(key.toString());
178 // writer.write(key + ": " + value + '\n');
180 // logger.log(DEBUG, () -> "Migrated " + p);
184 artifact
.setVersion(m2Version
);
186 // prepare manifest entries
187 Properties mergeProps
= new Properties();
188 mergeProps
.putAll(commonProps
);
190 fileEntries
: for (Object key
: fileProps
.keySet()) {
191 if (ManifestConstants
.SLC_ORIGIN_M2
.toString().equals(key
))
192 continue fileEntries
;
193 String value
= fileProps
.getProperty(key
.toString());
194 Object previousValue
= mergeProps
.put(key
.toString(), value
);
195 if (previousValue
!= null) {
196 logger
.log(Level
.WARNING
,
197 commonBnd
+ ": " + key
+ " was " + previousValue
+ ", overridden with " + value
);
200 mergeProps
.put(ManifestConstants
.SLC_ORIGIN_M2
.toString(), artifact
.toM2Coordinates());
201 if (!mergeProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())
202 && !mergeProps
.containsKey(ManifestConstants
.SLC_ORIGIN_MANIFEST_NOT_MODIFIED
.toString())) {
203 // use file name as symbolic name
204 String symbolicName
= p
.getFileName().toString();
205 symbolicName
= symbolicName
.substring(0, symbolicName
.length() - ".bnd".length());
206 mergeProps
.put(BUNDLE_SYMBOLICNAME
.toString(), symbolicName
);
209 String repoStr
= mergeProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
210 ? mergeProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
214 URL url
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
215 Path downloaded
= download(url
, originBase
, artifact
.toM2Coordinates() + ".jar");
217 Path targetBundleDir
= processBndJar(downloaded
, targetCategoryBase
, mergeProps
, artifact
);
218 // logger.log(Level.DEBUG, () -> "Processed " + downloaded);
221 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
223 createJar(targetBundleDir
);
225 } catch (IOException e
) {
226 throw new RuntimeException("Cannot process " + duDir
, e
);
231 protected void mergeM2Artifacts(Path mergeBnd
) throws IOException
{
232 Path duDir
= mergeBnd
.getParent();
233 String category
= duDir
.getParent().getFileName().toString();
234 Path targetCategoryBase
= a2Base
.resolve(category
);
236 Properties mergeProps
= new Properties();
237 try (InputStream in
= Files
.newInputStream(mergeBnd
)) {
240 String m2Version
= mergeProps
.getProperty(SLC_ORIGIN_M2
.toString());
241 if (m2Version
== null) {
242 logger
.log(Level
.WARNING
, "Ignoring " + duDir
+ " as it is not an M2-based distribution unit");
243 return;// ignore, this is probably an Eclipse archive
245 if (!m2Version
.startsWith(":")) {
246 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version
);
248 m2Version
= m2Version
.substring(1);
250 String artifactsStr
= mergeProps
.getProperty(ManifestConstants
.SLC_ORIGIN_M2_MERGE
.toString());
251 String repoStr
= mergeProps
.containsKey(SLC_ORIGIN_M2_REPO
.toString())
252 ? mergeProps
.getProperty(SLC_ORIGIN_M2_REPO
.toString())
255 String bundleSymbolicName
= mergeProps
.getProperty(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
256 DefaultCategoryNameVersion nameVersion
= new DefaultArtifact(
257 category
+ ":" + bundleSymbolicName
+ ":" + m2Version
);
258 Path targetBundleDir
= targetCategoryBase
.resolve(bundleSymbolicName
+ "." + nameVersion
.getBranch());
260 String
[] artifacts
= artifactsStr
.split(",");
261 artifacts
: for (String str
: artifacts
) {
262 String m2Coordinates
= str
.trim();
263 if ("".equals(m2Coordinates
))
265 DefaultArtifact artifact
= new DefaultArtifact(m2Coordinates
.trim());
266 if (artifact
.getVersion() == null)
267 artifact
.setVersion(m2Version
);
268 URL url
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, artifact
);
269 Path downloaded
= download(url
, originBase
, artifact
.toM2Coordinates() + ".jar");
271 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(downloaded
), false)) {
272 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
273 if (entry
.isDirectory())
275 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
277 if (entry
.getName().startsWith("META-INF/versions/"))
279 if (entry
.getName().equals("module-info.class"))
281 Path target
= targetBundleDir
.resolve(entry
.getName());
282 Files
.createDirectories(target
.getParent());
283 if (!Files
.exists(target
)) {
284 Files
.copy(jarIn
, target
);
286 if (entry
.getName().startsWith("META-INF/services/")) {
287 try (OutputStream out
= Files
.newOutputStream(target
, StandardOpenOption
.APPEND
)) {
288 out
.write("\n".getBytes());
289 jarIn
.transferTo(out
);
290 System
.out
.println("Appended "+entry
.getName());
293 throw new IllegalStateException("File " + target
+ " already exists");
296 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
300 downloadAndProcessM2Sources(repoStr
, artifact
, targetBundleDir
);
303 Map
<String
, String
> entries
= new TreeMap
<>();
304 try (Analyzer bndAnalyzer
= new Analyzer()) {
305 bndAnalyzer
.setProperties(mergeProps
);
306 Jar jar
= new Jar(targetBundleDir
.toFile());
307 bndAnalyzer
.setJar(jar
);
308 Manifest manifest
= bndAnalyzer
.calcManifest();
310 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
311 Object value
= manifest
.getMainAttributes().get(key
);
313 switch (key
.toString()) {
315 case "Bnd-LastModified":
319 if ("Require-Capability".equals(key
.toString())
320 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
321 continue keys
;// hack for very old classes
322 entries
.put(key
.toString(), value
.toString());
323 logger
.log(DEBUG
, () -> key
+ "=" + value
);
326 } catch (Exception e
) {
327 throw new RuntimeException("Cannot process " + mergeBnd
, e
);
330 Manifest manifest
= new Manifest();
331 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
332 Files
.createDirectories(manifestPath
.getParent());
333 for (String key
: entries
.keySet()) {
334 String value
= entries
.get(key
);
335 manifest
.getMainAttributes().putValue(key
, value
);
337 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
341 createJar(targetBundleDir
);
345 protected void downloadAndProcessM2Sources(String repoStr
, DefaultArtifact artifact
, Path targetBundleDir
)
347 DefaultArtifact sourcesArtifact
= new DefaultArtifact(artifact
.toM2Coordinates(), "sources");
348 URL sourcesUrl
= MavenConventionsUtils
.mavenRepoUrl(repoStr
, sourcesArtifact
);
349 Path sourcesDownloaded
= download(sourcesUrl
, originBase
, artifact
.toM2Coordinates() + ".sources.jar");
350 processM2SourceJar(sourcesDownloaded
, targetBundleDir
);
351 logger
.log(Level
.DEBUG
, () -> "Processed source " + sourcesDownloaded
);
355 protected Path
processBndJar(Path downloaded
, Path targetCategoryBase
, Properties fileProps
,
356 DefaultArtifact artifact
) {
359 Map
<String
, String
> additionalEntries
= new TreeMap
<>();
360 boolean doNotModify
= Boolean
.parseBoolean(fileProps
361 .getOrDefault(ManifestConstants
.SLC_ORIGIN_MANIFEST_NOT_MODIFIED
.toString(), "false").toString());
363 // we always force the symbolic name
366 fileEntries
: for (Object key
: fileProps
.keySet()) {
367 if (ManifestConstants
.SLC_ORIGIN_M2
.toString().equals(key
))
368 continue fileEntries
;
369 String value
= fileProps
.getProperty(key
.toString());
370 additionalEntries
.put(key
.toString(), value
);
373 if (artifact
!= null) {
374 if (!fileProps
.containsKey(BUNDLE_SYMBOLICNAME
.toString())) {
375 fileProps
.put(BUNDLE_SYMBOLICNAME
.toString(), artifact
.getName());
377 if (!fileProps
.containsKey(BUNDLE_VERSION
.toString())) {
378 fileProps
.put(BUNDLE_VERSION
.toString(), artifact
.getVersion());
382 if (!fileProps
.containsKey(EXPORT_PACKAGE
.toString())) {
383 fileProps
.put(EXPORT_PACKAGE
.toString(),
384 "*;version=\"" + fileProps
.getProperty(BUNDLE_VERSION
.toString()) + "\"");
386 // if (!fileProps.contains(IMPORT_PACKAGE.toString())) {
387 // fileProps.put(IMPORT_PACKAGE.toString(), "*");
390 try (Analyzer bndAnalyzer
= new Analyzer()) {
391 bndAnalyzer
.setProperties(fileProps
);
392 Jar jar
= new Jar(downloaded
.toFile());
393 bndAnalyzer
.setJar(jar
);
394 Manifest manifest
= bndAnalyzer
.calcManifest();
396 keys
: for (Object key
: manifest
.getMainAttributes().keySet()) {
397 Object value
= manifest
.getMainAttributes().get(key
);
399 switch (key
.toString()) {
401 case "Bnd-LastModified":
405 if ("Require-Capability".equals(key
.toString())
406 && value
.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
407 continue keys
;// hack for very old classes
408 additionalEntries
.put(key
.toString(), value
.toString());
409 logger
.log(DEBUG
, () -> key
+ "=" + value
);
414 // try (Builder bndBuilder = new Builder()) {
415 // Jar jar = new Jar(downloaded.toFile());
416 // bndBuilder.addClasspath(jar);
417 // Path targetBundleDir = targetCategoryBase.resolve(artifact.getName() + "." + artifact.getBranch());
419 // Jar target = new Jar(targetBundleDir.toFile());
420 // bndBuilder.setJar(target);
421 // return targetBundleDir;
424 Path targetBundleDir
= processBundleJar(downloaded
, targetCategoryBase
, additionalEntries
);
425 logger
.log(Level
.DEBUG
, () -> "Processed " + downloaded
);
426 return targetBundleDir
;
427 } catch (Exception e
) {
428 throw new RuntimeException("Cannot BND process " + downloaded
, e
);
433 protected void processM2SourceJar(Path file
, Path targetBundleDir
) throws IOException
{
434 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
435 Path targetSourceDir
= targetBundleDir
.resolve("OSGI-OPT/src");
437 // TODO make it less dangerous?
438 if (Files
.exists(targetSourceDir
)) {
439 // deleteDirectory(targetSourceDir);
441 Files
.createDirectories(targetSourceDir
);
446 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
447 if (entry
.isDirectory())
449 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
451 if (entry
.getName().startsWith("module-info.java"))// skip META-INF entries
453 Path target
= targetSourceDir
.resolve(entry
.getName());
454 Files
.createDirectories(target
.getParent());
455 Files
.copy(jarIn
, target
);
456 logger
.log(Level
.TRACE
, () -> "Copied source " + target
);
462 public void processEclipseArchive(Path duDir
) {
464 String category
= duDir
.getParent().getFileName().toString();
465 Path targetCategoryBase
= a2Base
.resolve(category
);
466 Files
.createDirectories(targetCategoryBase
);
467 // first delete all directories from previous builds
468 for (Path dir
: Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
))) {
469 deleteDirectory(dir
);
472 Files
.createDirectories(originBase
);
474 Path commonBnd
= duDir
.resolve(COMMON_BND
);
475 Properties commonProps
= new Properties();
476 try (InputStream in
= Files
.newInputStream(commonBnd
)) {
477 commonProps
.load(in
);
479 Properties includes
= new Properties();
480 try (InputStream in
= Files
.newInputStream(duDir
.resolve("includes.properties"))) {
483 String url
= commonProps
.getProperty(ManifestConstants
.SLC_ORIGIN_URI
.toString());
484 Path downloaded
= tryDownload(url
, originBase
);
486 FileSystem zipFs
= FileSystems
.newFileSystem(downloaded
, (ClassLoader
) null);
488 List
<PathMatcher
> pathMatchers
= new ArrayList
<>();
489 for (Object pattern
: includes
.keySet()) {
490 PathMatcher pathMatcher
= zipFs
.getPathMatcher("glob:/" + pattern
);
491 pathMatchers
.add(pathMatcher
);
494 Files
.walkFileTree(zipFs
.getRootDirectories().iterator().next(), new SimpleFileVisitor
<Path
>() {
497 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
498 pathMatchers
: for (PathMatcher pathMatcher
: pathMatchers
) {
499 if (pathMatcher
.matches(file
)) {
500 if (file
.getFileName().toString().contains(".source_")) {
501 processEclipseSourceJar(file
, targetCategoryBase
);
502 logger
.log(Level
.DEBUG
, () -> "Processed source " + file
);
505 processBundleJar(file
, targetCategoryBase
, new HashMap
<>());
506 logger
.log(Level
.DEBUG
, () -> "Processed " + file
);
511 return FileVisitResult
.CONTINUE
;
515 DirectoryStream
<Path
> dirs
= Files
.newDirectoryStream(targetCategoryBase
, (p
) -> Files
.isDirectory(p
));
516 for (Path dir
: dirs
) {
519 } catch (IOException e
) {
520 throw new RuntimeException("Cannot process " + duDir
, e
);
525 protected Path
processBundleJar(Path file
, Path targetBase
, Map
<String
, String
> entries
) throws IOException
{
526 DefaultNameVersion nameVersion
;
527 Path targetBundleDir
;
528 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
529 Manifest manifest
= new Manifest(jarIn
.getManifest());
531 // remove problematic entries in MANIFEST
532 manifest
.getEntries().clear();
533 // Set<String> entriesToDelete = new HashSet<>();
534 // for (String key : manifest.getEntries().keySet()) {
535 //// logger.log(DEBUG, "## " + key);
536 // Attributes attrs = manifest.getAttributes(key);
537 // for (Object attrName : attrs.keySet()) {
538 //// logger.log(DEBUG, attrName + "=" + attrs.get(attrName));
539 // if ("Specification-Version".equals(attrName.toString())
540 // || "Implementation-Version".equals(attrName.toString())) {
541 // entriesToDelete.add(key);
546 // for (String key : entriesToDelete) {
547 // manifest.getEntries().remove(key);
550 String symbolicNameFromEntries
= entries
.get(BUNDLE_SYMBOLICNAME
.toString());
551 String versionFromEntries
= entries
.get(BUNDLE_VERSION
.toString());
553 if (symbolicNameFromEntries
!= null && versionFromEntries
!= null) {
554 nameVersion
= new DefaultNameVersion(symbolicNameFromEntries
, versionFromEntries
);
556 nameVersion
= nameVersionFromManifest(manifest
);
557 if (versionFromEntries
!= null && !nameVersion
.getVersion().equals(versionFromEntries
)) {
558 logger
.log(Level
.WARNING
, "Original version is " + nameVersion
.getVersion()
559 + " while new version is " + versionFromEntries
);
561 if (symbolicNameFromEntries
!= null) {
562 // we always force our symbolic name
563 nameVersion
.setName(symbolicNameFromEntries
);
566 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
568 // TODO make it less dangerous?
569 // if (Files.exists(targetBundleDir)) {
570 // deleteDirectory(targetBundleDir);
575 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
576 if (entry
.isDirectory())
578 if (entry
.getName().endsWith(".RSA") || entry
.getName().endsWith(".SF"))
580 Path target
= targetBundleDir
.resolve(entry
.getName());
581 Files
.createDirectories(target
.getParent());
582 Files
.copy(jarIn
, target
);
583 logger
.log(Level
.TRACE
, () -> "Copied " + target
);
587 Path manifestPath
= targetBundleDir
.resolve("META-INF/MANIFEST.MF");
588 Files
.createDirectories(manifestPath
.getParent());
589 for (String key
: entries
.keySet()) {
590 String value
= entries
.get(key
);
591 Object previousValue
= manifest
.getMainAttributes().putValue(key
, value
);
592 if (previousValue
!= null && !previousValue
.equals(value
)) {
593 if (ManifestConstants
.IMPORT_PACKAGE
.toString().equals(key
)
594 || ManifestConstants
.EXPORT_PACKAGE
.toString().equals(key
))
595 logger
.log(Level
.WARNING
, file
.getFileName() + ": " + key
+ " was modified");
598 logger
.log(Level
.WARNING
, file
.getFileName() + ": " + key
+ " was " + previousValue
599 + ", overridden with " + value
);
602 try (OutputStream out
= Files
.newOutputStream(manifestPath
)) {
606 return targetBundleDir
;
609 protected void processEclipseSourceJar(Path file
, Path targetBase
) throws IOException
{
611 Path targetBundleDir
;
612 try (JarInputStream jarIn
= new JarInputStream(Files
.newInputStream(file
), false)) {
613 Manifest manifest
= jarIn
.getManifest();
615 String
[] relatedBundle
= manifest
.getMainAttributes().getValue("Eclipse-SourceBundle").split(";");
616 String version
= relatedBundle
[1].substring("version=\"".length());
617 version
= version
.substring(0, version
.length() - 1);
618 NameVersion nameVersion
= new DefaultNameVersion(relatedBundle
[0], version
);
619 targetBundleDir
= targetBase
.resolve(nameVersion
.getName() + "." + nameVersion
.getBranch());
621 Path targetSourceDir
= targetBundleDir
.resolve("OSGI-OPT/src");
623 // TODO make it less dangerous?
624 if (Files
.exists(targetSourceDir
)) {
625 // deleteDirectory(targetSourceDir);
627 Files
.createDirectories(targetSourceDir
);
632 entries
: while ((entry
= jarIn
.getNextJarEntry()) != null) {
633 if (entry
.isDirectory())
635 if (entry
.getName().startsWith("META-INF"))// skip META-INF entries
637 Path target
= targetSourceDir
.resolve(entry
.getName());
638 Files
.createDirectories(target
.getParent());
639 Files
.copy(jarIn
, target
);
640 logger
.log(Level
.TRACE
, () -> "Copied source " + target
);
644 // Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
645 // Files.createDirectories(manifestPath.getParent());
646 // try (OutputStream out = Files.newOutputStream(manifestPath)) {
647 // manifest.write(out);
650 } catch (IOException e
) {
651 throw new IllegalStateException("Cannot process " + file
, e
);
656 static void deleteDirectory(Path path
) throws IOException
{
657 if (!Files
.exists(path
))
659 Files
.walkFileTree(path
, new SimpleFileVisitor
<Path
>() {
661 public FileVisitResult
postVisitDirectory(Path directory
, IOException e
) throws IOException
{
664 Files
.delete(directory
);
665 return FileVisitResult
.CONTINUE
;
669 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
671 return FileVisitResult
.CONTINUE
;
676 protected DefaultNameVersion
nameVersionFromManifest(Manifest manifest
) {
677 Attributes attrs
= manifest
.getMainAttributes();
679 String symbolicName
= attrs
.getValue(ManifestConstants
.BUNDLE_SYMBOLICNAME
.toString());
680 if (symbolicName
== null)
682 // make sure there is no directive
683 symbolicName
= symbolicName
.split(";")[0];
685 String version
= attrs
.getValue(ManifestConstants
.BUNDLE_VERSION
.toString());
686 return new DefaultNameVersion(symbolicName
, version
);
689 protected Path
tryDownload(String uri
, Path dir
) throws IOException
{
691 List
<String
> urlBases
= null;
692 String uriPrefix
= null;
693 uriPrefixes
: for (String uriPref
: mirrors
.keySet()) {
694 if (uri
.startsWith(uriPref
)) {
695 if (mirrors
.get(uriPref
).size() > 0) {
696 urlBases
= mirrors
.get(uriPref
);
702 if (urlBases
== null)
704 return download(new URL(uri
), dir
, null);
705 } catch (FileNotFoundException e
) {
706 throw new FileNotFoundException("Cannot find " + uri
);
710 for (String urlBase
: urlBases
) {
711 String relativePath
= uri
.substring(uriPrefix
.length());
712 URL url
= new URL(urlBase
+ relativePath
);
714 return download(url
, dir
, null);
715 } catch (FileNotFoundException e
) {
716 logger
.log(Level
.WARNING
, "Cannot download " + url
+ ", trying another mirror");
719 throw new FileNotFoundException("Cannot find " + uri
);
722 // protected String simplifyName(URL u) {
723 // String name = u.getPath().substring(u.getPath().lastIndexOf('/') + 1);
727 protected Path
download(URL url
, Path dir
, String name
) throws IOException
{
731 name
= url
.getPath().substring(url
.getPath().lastIndexOf('/') + 1);
734 dest
= dir
.resolve(name
);
735 if (Files
.exists(dest
)) {
736 logger
.log(Level
.TRACE
, () -> "File " + dest
+ " already exists for " + url
+ ", not downloading again");
740 try (InputStream in
= url
.openStream()) {
741 Files
.copy(in
, dest
);
742 logger
.log(Level
.DEBUG
, () -> "Downloaded " + dest
+ " from " + url
);
747 protected Path
createJar(Path bundleDir
) throws IOException
{
748 Path jarPath
= bundleDir
.getParent().resolve(bundleDir
.getFileName() + ".jar");
749 Path manifestPath
= bundleDir
.resolve("META-INF/MANIFEST.MF");
751 try (InputStream in
= Files
.newInputStream(manifestPath
)) {
752 manifest
= new Manifest(in
);
754 try (JarOutputStream jarOut
= new JarOutputStream(Files
.newOutputStream(jarPath
), manifest
)) {
755 Files
.walkFileTree(bundleDir
, new SimpleFileVisitor
<Path
>() {
758 public FileVisitResult
visitFile(Path file
, BasicFileAttributes attrs
) throws IOException
{
759 if (file
.getFileName().toString().equals("MANIFEST.MF"))
760 return super.visitFile(file
, attrs
);
761 JarEntry entry
= new JarEntry(bundleDir
.relativize(file
).toString());
762 jarOut
.putNextEntry(entry
);
763 Files
.copy(file
, jarOut
);
764 return super.visitFile(file
, attrs
);
769 deleteDirectory(bundleDir
);
773 public static void main(String
[] args
) {
774 Path factoryBase
= Paths
.get("../../output/a2").toAbsolutePath().normalize();
775 A2Factory factory
= new A2Factory(factoryBase
);
777 Path descriptorsBase
= Paths
.get("../tp").toAbsolutePath().normalize();
779 // factory.processSingleM2ArtifactDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache").resolve("org.apache.xml.resolver.bnd"));
780 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache/apache-sshd"));
781 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.jetty/jetty"));
782 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.jetty/jetty-websocket"));
783 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.eclipse.rcp"));
784 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp"));
785 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.apache"));
786 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.formats"));
787 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.gis"));
791 factory
.processEclipseArchive(
792 descriptorsBase
.resolve("org.argeo.tp.eclipse.equinox").resolve("eclipse-equinox"));
793 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.rap").resolve("eclipse-rap"));
794 factory
.processEclipseArchive(descriptorsBase
.resolve("org.argeo.tp.eclipse.rcp").resolve("eclipse-rcp"));
799 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.sdk"));
800 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp"));
801 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.apache"));
802 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.jetty"));
803 factory
.processCategory(descriptorsBase
.resolve("org.argeo.tp.jcr"));