]> git.argeo.org Git - gpl/argeo-slc.git/blob - org.argeo.slc.factory/src/org/argeo/slc/factory/A2Factory.java
Introduce SLC Tool
[gpl/argeo-slc.git] / org.argeo.slc.factory / src / org / argeo / slc / factory / A2Factory.java
1 package org.argeo.slc.factory;
2
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;
9
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;
16 import java.net.URL;
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;
31 import java.util.Map;
32 import java.util.Objects;
33 import java.util.Properties;
34 import java.util.TreeMap;
35 import java.util.jar.Attributes;
36 import java.util.jar.JarEntry;
37 import java.util.jar.JarInputStream;
38 import java.util.jar.JarOutputStream;
39 import java.util.jar.Manifest;
40 import java.util.zip.Deflater;
41
42 import org.argeo.slc.DefaultCategoryNameVersion;
43 import org.argeo.slc.DefaultNameVersion;
44 import org.argeo.slc.ManifestConstants;
45 import org.argeo.slc.NameVersion;
46 import org.argeo.slc.factory.m2.Artifact;
47 import org.argeo.slc.factory.m2.DefaultArtifact;
48 import org.argeo.slc.factory.m2.MavenConventionsUtils;
49
50 import aQute.bnd.osgi.Analyzer;
51 import aQute.bnd.osgi.Jar;
52
53 /** The central class for A2 packaging. */
54 public class A2Factory {
55 private final static Logger logger = System.getLogger(A2Factory.class.getName());
56
57 private final static String COMMON_BND = "common.bnd";
58 private final static String MERGE_BND = "merge.bnd";
59
60 private Path originBase;
61 private Path a2Base;
62 private Path a2LibBase;
63 private Path descriptorsBase;
64
65 private Properties uris = new Properties();
66
67 private boolean includeSources = true;
68
69 /** key is URI prefix, value list of base URLs */
70 private Map<String, List<String>> mirrors = new HashMap<String, List<String>>();
71
72 public A2Factory(Path a2Base, Path descriptorsBase, boolean includeSources) {
73 Objects.requireNonNull(a2Base);
74 Objects.requireNonNull(descriptorsBase);
75 this.originBase = Paths.get(System.getProperty("user.home"), ".cache", "argeo/slc/origin");
76 this.a2Base = a2Base;
77 this.a2LibBase = a2Base.resolve("lib");
78 this.descriptorsBase = descriptorsBase;
79 if (!Files.exists(this.descriptorsBase))
80 throw new IllegalArgumentException(this.descriptorsBase + " does not exist");
81 this.includeSources = includeSources;
82
83 Path urisPath = this.descriptorsBase.resolve("uris.properties");
84 if (Files.exists(urisPath)) {
85 try (InputStream in = Files.newInputStream(urisPath)) {
86 uris.load(in);
87 } catch (IOException e) {
88 throw new IllegalStateException("Cannot load " + urisPath, e);
89 }
90 }
91
92 // TODO make it configurable
93 List<String> eclipseMirrors = new ArrayList<>();
94 eclipseMirrors.add("https://archive.eclipse.org/");
95 eclipseMirrors.add("http://ftp-stud.hs-esslingen.de/Mirrors/eclipse/");
96 eclipseMirrors.add("http://ftp.fau.de/eclipse/");
97
98 mirrors.put("http://www.eclipse.org/downloads", eclipseMirrors);
99 }
100
101 /*
102 * MAVEN ORIGIN
103 */
104
105 /** Process a whole category/group id. */
106 public void processCategory(Path categoryRelativePath) {
107 try {
108 Path targetCategoryBase = descriptorsBase.resolve(categoryRelativePath);
109 DirectoryStream<Path> bnds = Files.newDirectoryStream(targetCategoryBase,
110 (p) -> p.getFileName().toString().endsWith(".bnd") && !p.getFileName().toString().equals(COMMON_BND)
111 && !p.getFileName().toString().equals(MERGE_BND));
112 for (Path p : bnds) {
113 processSingleM2ArtifactDistributionUnit(p);
114 }
115
116 DirectoryStream<Path> dus = Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p));
117 for (Path duDir : dus) {
118 processM2BasedDistributionUnit(duDir);
119 }
120 } catch (IOException e) {
121 throw new RuntimeException("Cannot process category " + categoryRelativePath, e);
122 }
123 }
124
125 /** Process a standalone Maven artifact. */
126 public void processSingleM2ArtifactDistributionUnit(Path bndFile) {
127 try {
128 // String category = bndFile.getParent().getFileName().toString();
129 Path categoryRelativePath = descriptorsBase.relativize(bndFile.getParent());
130 Path targetCategoryBase = a2Base.resolve(categoryRelativePath);
131
132 Properties fileProps = new Properties();
133 try (InputStream in = Files.newInputStream(bndFile)) {
134 fileProps.load(in);
135 }
136 String repoStr = fileProps.containsKey(SLC_ORIGIN_M2_REPO.toString())
137 ? fileProps.getProperty(SLC_ORIGIN_M2_REPO.toString())
138 : null;
139
140 if (!fileProps.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
141 // use file name as symbolic name
142 String symbolicName = bndFile.getFileName().toString();
143 symbolicName = symbolicName.substring(0, symbolicName.length() - ".bnd".length());
144 fileProps.put(BUNDLE_SYMBOLICNAME.toString(), symbolicName);
145 }
146
147 String m2Coordinates = fileProps.getProperty(SLC_ORIGIN_M2.toString());
148 if (m2Coordinates == null)
149 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile);
150 DefaultArtifact artifact = new DefaultArtifact(m2Coordinates);
151 URL url = MavenConventionsUtils.mavenRepoUrl(repoStr, artifact);
152 Path downloaded = download(url, originBase, artifact);
153
154 Path targetBundleDir = processBndJar(downloaded, targetCategoryBase, fileProps, artifact);
155
156 downloadAndProcessM2Sources(repoStr, artifact, targetBundleDir);
157
158 createJar(targetBundleDir);
159 } catch (Exception e) {
160 throw new RuntimeException("Cannot process " + bndFile, e);
161 }
162 }
163
164 /** Process multiple Maven artifacts. */
165 public void processM2BasedDistributionUnit(Path duDir) {
166 try {
167 // String category = duDir.getParent().getFileName().toString();
168 Path categoryRelativePath = descriptorsBase.relativize(duDir.getParent());
169 Path targetCategoryBase = a2Base.resolve(categoryRelativePath);
170
171 // merge
172 Path mergeBnd = duDir.resolve(MERGE_BND);
173 if (Files.exists(mergeBnd)) {
174 mergeM2Artifacts(mergeBnd);
175 // return;
176 }
177
178 Path commonBnd = duDir.resolve(COMMON_BND);
179 if (!Files.exists(commonBnd)) {
180 return;
181 }
182 Properties commonProps = new Properties();
183 try (InputStream in = Files.newInputStream(commonBnd)) {
184 commonProps.load(in);
185 }
186
187 String m2Version = commonProps.getProperty(SLC_ORIGIN_M2.toString());
188 if (m2Version == null) {
189 logger.log(Level.WARNING, "Ignoring " + duDir + " as it is not an M2-based distribution unit");
190 return;// ignore, this is probably an Eclipse archive
191 }
192 if (!m2Version.startsWith(":")) {
193 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version);
194 }
195 m2Version = m2Version.substring(1);
196
197 DirectoryStream<Path> ds = Files.newDirectoryStream(duDir,
198 (p) -> p.getFileName().toString().endsWith(".bnd") && !p.getFileName().toString().equals(COMMON_BND)
199 && !p.getFileName().toString().equals(MERGE_BND));
200 for (Path p : ds) {
201 Properties fileProps = new Properties();
202 try (InputStream in = Files.newInputStream(p)) {
203 fileProps.load(in);
204 }
205 String m2Coordinates = fileProps.getProperty(SLC_ORIGIN_M2.toString());
206 DefaultArtifact artifact = new DefaultArtifact(m2Coordinates);
207
208 // temporary rewrite, for migration
209 // String localLicense = fileProps.getProperty(BUNDLE_LICENSE.toString());
210 // if (localLicense != null || artifact.getVersion() != null) {
211 // fileProps.remove(BUNDLE_LICENSE.toString());
212 // fileProps.put(SLC_ORIGIN_M2.toString(), artifact.getGroupId() + ":" + artifact.getArtifactId());
213 // try (Writer writer = Files.newBufferedWriter(p)) {
214 // for (Object key : fileProps.keySet()) {
215 // String value = fileProps.getProperty(key.toString());
216 // writer.write(key + ": " + value + '\n');
217 // }
218 // logger.log(DEBUG, () -> "Migrated " + p);
219 // }
220 // }
221
222 artifact.setVersion(m2Version);
223
224 // prepare manifest entries
225 Properties mergeProps = new Properties();
226 mergeProps.putAll(commonProps);
227
228 fileEntries: for (Object key : fileProps.keySet()) {
229 if (ManifestConstants.SLC_ORIGIN_M2.toString().equals(key))
230 continue fileEntries;
231 String value = fileProps.getProperty(key.toString());
232 Object previousValue = mergeProps.put(key.toString(), value);
233 if (previousValue != null) {
234 logger.log(Level.WARNING,
235 commonBnd + ": " + key + " was " + previousValue + ", overridden with " + value);
236 }
237 }
238 mergeProps.put(ManifestConstants.SLC_ORIGIN_M2.toString(), artifact.toM2Coordinates());
239 if (!mergeProps.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
240 // use file name as symbolic name
241 String symbolicName = p.getFileName().toString();
242 symbolicName = symbolicName.substring(0, symbolicName.length() - ".bnd".length());
243 mergeProps.put(BUNDLE_SYMBOLICNAME.toString(), symbolicName);
244 }
245
246 String repoStr = mergeProps.containsKey(SLC_ORIGIN_M2_REPO.toString())
247 ? mergeProps.getProperty(SLC_ORIGIN_M2_REPO.toString())
248 : null;
249
250 // download
251 URL url = MavenConventionsUtils.mavenRepoUrl(repoStr, artifact);
252 Path downloaded = download(url, originBase, artifact);
253
254 Path targetBundleDir = processBndJar(downloaded, targetCategoryBase, mergeProps, artifact);
255 // logger.log(Level.DEBUG, () -> "Processed " + downloaded);
256
257 // sources
258 downloadAndProcessM2Sources(repoStr, artifact, targetBundleDir);
259
260 createJar(targetBundleDir);
261 }
262 } catch (IOException e) {
263 throw new RuntimeException("Cannot process " + duDir, e);
264 }
265
266 }
267
268 /** Merge multiple Maven artifacts. */
269 protected void mergeM2Artifacts(Path mergeBnd) throws IOException {
270 Path duDir = mergeBnd.getParent();
271 String category = duDir.getParent().getFileName().toString();
272 Path targetCategoryBase = a2Base.resolve(category);
273
274 Properties mergeProps = new Properties();
275 try (InputStream in = Files.newInputStream(mergeBnd)) {
276 mergeProps.load(in);
277 }
278
279 // Version
280 String m2Version = mergeProps.getProperty(SLC_ORIGIN_M2.toString());
281 if (m2Version == null) {
282 logger.log(Level.WARNING, "Ignoring " + duDir + " as it is not an M2-based distribution unit");
283 return;// ignore, this is probably an Eclipse archive
284 }
285 if (!m2Version.startsWith(":")) {
286 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version);
287 }
288 m2Version = m2Version.substring(1);
289 mergeProps.put(ManifestConstants.BUNDLE_VERSION.toString(), m2Version);
290
291 String artifactsStr = mergeProps.getProperty(ManifestConstants.SLC_ORIGIN_M2_MERGE.toString());
292 String repoStr = mergeProps.containsKey(SLC_ORIGIN_M2_REPO.toString())
293 ? mergeProps.getProperty(SLC_ORIGIN_M2_REPO.toString())
294 : null;
295
296 String bundleSymbolicName = mergeProps.getProperty(ManifestConstants.BUNDLE_SYMBOLICNAME.toString());
297 if (bundleSymbolicName == null)
298 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd);
299 DefaultCategoryNameVersion nameVersion = new DefaultArtifact(
300 category + ":" + bundleSymbolicName + ":" + m2Version);
301 Path targetBundleDir = targetCategoryBase.resolve(bundleSymbolicName + "." + nameVersion.getBranch());
302
303 String[] artifacts = artifactsStr.split(",");
304 artifacts: for (String str : artifacts) {
305 String m2Coordinates = str.trim();
306 if ("".equals(m2Coordinates))
307 continue artifacts;
308 DefaultArtifact artifact = new DefaultArtifact(m2Coordinates.trim());
309 if (artifact.getVersion() == null)
310 artifact.setVersion(m2Version);
311 URL url = MavenConventionsUtils.mavenRepoUrl(repoStr, artifact);
312 Path downloaded = download(url, originBase, artifact);
313 JarEntry entry;
314 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(downloaded), false)) {
315 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
316 if (entry.isDirectory())
317 continue entries;
318 else if (entry.getName().endsWith(".RSA") || entry.getName().endsWith(".SF"))
319 continue entries;
320 else if (entry.getName().startsWith("META-INF/versions/"))
321 continue entries;
322 else if (entry.getName().startsWith("META-INF/maven/"))
323 continue entries;
324 else if (entry.getName().equals("module-info.class"))
325 continue entries;
326 else if (entry.getName().equals("META-INF/NOTICE"))
327 continue entries;
328 else if (entry.getName().equals("META-INF/NOTICE.txt"))
329 continue entries;
330 else if (entry.getName().equals("META-INF/LICENSE"))
331 continue entries;
332 else if (entry.getName().equals("META-INF/LICENSE.md"))
333 continue entries;
334 else if (entry.getName().equals("META-INF/LICENSE-notice.md"))
335 continue entries;
336 Path target = targetBundleDir.resolve(entry.getName());
337 Files.createDirectories(target.getParent());
338 if (!Files.exists(target)) {
339 Files.copy(jarIn, target);
340 } else {
341 if (entry.getName().startsWith("META-INF/services/")) {
342 try (OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND)) {
343 out.write("\n".getBytes());
344 jarIn.transferTo(out);
345 if (logger.isLoggable(DEBUG))
346 logger.log(DEBUG, artifact.getArtifactId() + " - Appended " + entry.getName());
347 }
348 } else if (entry.getName().startsWith("org/apache/batik/")) {
349 logger.log(Level.WARNING, "Skip " + entry.getName());
350 continue entries;
351 } else {
352 throw new IllegalStateException("File " + target + " from " + artifact + " already exists");
353 }
354 }
355 logger.log(Level.TRACE, () -> "Copied " + target);
356 }
357
358 }
359 downloadAndProcessM2Sources(repoStr, artifact, targetBundleDir);
360 }
361
362 // additional service files
363 Path servicesDir = duDir.resolve("services");
364 if (Files.exists(servicesDir)) {
365 for (Path p : Files.newDirectoryStream(servicesDir)) {
366 Path target = targetBundleDir.resolve("META-INF/services/").resolve(p.getFileName());
367 try (InputStream in = Files.newInputStream(p);
368 OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND);) {
369 out.write("\n".getBytes());
370 in.transferTo(out);
371 if (logger.isLoggable(DEBUG))
372 logger.log(DEBUG, "Appended " + p);
373 }
374 }
375 }
376
377 Map<String, String> entries = new TreeMap<>();
378 try (Analyzer bndAnalyzer = new Analyzer()) {
379 bndAnalyzer.setProperties(mergeProps);
380 Jar jar = new Jar(targetBundleDir.toFile());
381 bndAnalyzer.setJar(jar);
382 Manifest manifest = bndAnalyzer.calcManifest();
383
384 keys: for (Object key : manifest.getMainAttributes().keySet()) {
385 Object value = manifest.getMainAttributes().get(key);
386
387 switch (key.toString()) {
388 case "Tool":
389 case "Bnd-LastModified":
390 case "Created-By":
391 continue keys;
392 }
393 if ("Require-Capability".equals(key.toString())
394 && value.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
395 continue keys;// hack for very old classes
396 entries.put(key.toString(), value.toString());
397 // logger.log(DEBUG, () -> key + "=" + value);
398
399 }
400 } catch (Exception e) {
401 throw new RuntimeException("Cannot process " + mergeBnd, e);
402 }
403
404 Manifest manifest = new Manifest();
405 Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
406 Files.createDirectories(manifestPath.getParent());
407 for (String key : entries.keySet()) {
408 String value = entries.get(key);
409 manifest.getMainAttributes().putValue(key, value);
410 }
411
412 // // Use Maven version as Bundle-Version
413 // String bundleVersion = manifest.getMainAttributes().getValue(ManifestConstants.BUNDLE_VERSION.toString());
414 // if (bundleVersion == null || bundleVersion.trim().equals("0")) {
415 // // TODO check why it is sometimes set to "0"
416 // manifest.getMainAttributes().putValue(ManifestConstants.BUNDLE_VERSION.toString(), m2Version);
417 // }
418 try (OutputStream out = Files.newOutputStream(manifestPath)) {
419 manifest.write(out);
420 }
421
422 createJar(targetBundleDir);
423
424 }
425
426 /** Generate MANIFEST using BND. */
427 protected Path processBndJar(Path downloaded, Path targetCategoryBase, Properties fileProps,
428 DefaultArtifact artifact) {
429
430 try {
431 Map<String, String> additionalEntries = new TreeMap<>();
432 boolean doNotModify = Boolean.parseBoolean(fileProps
433 .getOrDefault(ManifestConstants.SLC_ORIGIN_MANIFEST_NOT_MODIFIED.toString(), "false").toString());
434
435 // we always force the symbolic name
436
437 if (doNotModify) {
438 fileEntries: for (Object key : fileProps.keySet()) {
439 if (ManifestConstants.SLC_ORIGIN_M2.toString().equals(key))
440 continue fileEntries;
441 String value = fileProps.getProperty(key.toString());
442 additionalEntries.put(key.toString(), value);
443 }
444 } else {
445 if (artifact != null) {
446 if (!fileProps.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
447 fileProps.put(BUNDLE_SYMBOLICNAME.toString(), artifact.getName());
448 }
449 if (!fileProps.containsKey(BUNDLE_VERSION.toString())) {
450 fileProps.put(BUNDLE_VERSION.toString(), artifact.getVersion());
451 }
452 }
453
454 if (!fileProps.containsKey(EXPORT_PACKAGE.toString())) {
455 fileProps.put(EXPORT_PACKAGE.toString(),
456 "*;version=\"" + fileProps.getProperty(BUNDLE_VERSION.toString()) + "\"");
457 }
458 // if (!fileProps.contains(IMPORT_PACKAGE.toString())) {
459 // fileProps.put(IMPORT_PACKAGE.toString(), "*");
460 // }
461
462 try (Analyzer bndAnalyzer = new Analyzer()) {
463 bndAnalyzer.setProperties(fileProps);
464 Jar jar = new Jar(downloaded.toFile());
465 bndAnalyzer.setJar(jar);
466 Manifest manifest = bndAnalyzer.calcManifest();
467
468 keys: for (Object key : manifest.getMainAttributes().keySet()) {
469 Object value = manifest.getMainAttributes().get(key);
470
471 switch (key.toString()) {
472 case "Tool":
473 case "Bnd-LastModified":
474 case "Created-By":
475 continue keys;
476 }
477 if ("Require-Capability".equals(key.toString())
478 && value.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
479 continue keys;// hack for very old classes
480 additionalEntries.put(key.toString(), value.toString());
481 // logger.log(DEBUG, () -> key + "=" + value);
482
483 }
484 }
485
486 // try (Builder bndBuilder = new Builder()) {
487 // Jar jar = new Jar(downloaded.toFile());
488 // bndBuilder.addClasspath(jar);
489 // Path targetBundleDir = targetCategoryBase.resolve(artifact.getName() + "." + artifact.getBranch());
490 //
491 // Jar target = new Jar(targetBundleDir.toFile());
492 // bndBuilder.setJar(target);
493 // return targetBundleDir;
494 // }
495 }
496 Path targetBundleDir = processBundleJar(downloaded, targetCategoryBase, additionalEntries);
497 logger.log(Level.DEBUG, () -> "Processed " + downloaded);
498 return targetBundleDir;
499 } catch (Exception e) {
500 throw new RuntimeException("Cannot BND process " + downloaded, e);
501 }
502
503 }
504
505 /** Download and integrates sources for a single Maven artifact. */
506 protected void downloadAndProcessM2Sources(String repoStr, DefaultArtifact artifact, Path targetBundleDir)
507 throws IOException {
508 if (!includeSources)
509 return;
510 DefaultArtifact sourcesArtifact = new DefaultArtifact(artifact.toM2Coordinates(), "sources");
511 URL sourcesUrl = MavenConventionsUtils.mavenRepoUrl(repoStr, sourcesArtifact);
512 Path sourcesDownloaded = download(sourcesUrl, originBase, artifact, true);
513 processM2SourceJar(sourcesDownloaded, targetBundleDir);
514 logger.log(Level.TRACE, () -> "Processed source " + sourcesDownloaded);
515
516 }
517
518 /** Integrate sources from a downloaded jar file. */
519 protected void processM2SourceJar(Path file, Path targetBundleDir) throws IOException {
520 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
521 Path targetSourceDir = targetBundleDir.resolve("OSGI-OPT/src");
522
523 // TODO make it less dangerous?
524 if (Files.exists(targetSourceDir)) {
525 // deleteDirectory(targetSourceDir);
526 } else {
527 Files.createDirectories(targetSourceDir);
528 }
529
530 // copy entries
531 JarEntry entry;
532 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
533 if (entry.isDirectory())
534 continue entries;
535 if (entry.getName().startsWith("META-INF"))// skip META-INF entries
536 continue entries;
537 if (entry.getName().startsWith("module-info.java"))// skip META-INF entries
538 continue entries;
539 if (entry.getName().startsWith("/")) // absolute paths
540 continue entries;
541 Path target = targetSourceDir.resolve(entry.getName());
542 Files.createDirectories(target.getParent());
543 if (!Files.exists(target)) {
544 Files.copy(jarIn, target);
545 logger.log(Level.TRACE, () -> "Copied source " + target);
546 } else {
547 logger.log(Level.WARNING, () -> target + " already exists, skipping...");
548 }
549 }
550 }
551
552 }
553
554 /** Download a Maven artifact. */
555 protected Path download(URL url, Path dir, Artifact artifact) throws IOException {
556 return download(url, dir, artifact, false);
557 }
558
559 /** Download a Maven artifact. */
560 protected Path download(URL url, Path dir, Artifact artifact, boolean sources) throws IOException {
561 return download(url, dir, artifact.getGroupId() + '/' + artifact.getArtifactId() + "-" + artifact.getVersion()
562 + (sources ? "-sources" : "") + ".jar");
563 }
564
565 /*
566 * ECLIPSE ORIGIN
567 */
568
569 /** Process an archive in Eclipse format. */
570 public void processEclipseArchive(Path relativePath) {
571 try {
572 Path categoryRelativePath = relativePath.getParent();
573 // String category = categoryRelativePath.getFileName().toString();
574 Path targetCategoryBase = a2Base.resolve(categoryRelativePath);
575 Files.createDirectories(targetCategoryBase);
576 // first delete all directories from previous builds
577 for (Path dir : Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p))) {
578 deleteDirectory(dir);
579 }
580
581 Files.createDirectories(originBase);
582
583 Path duDir = descriptorsBase.resolve(relativePath);
584 Path commonBnd = duDir.resolve(COMMON_BND);
585 Properties commonProps = new Properties();
586 try (InputStream in = Files.newInputStream(commonBnd)) {
587 commonProps.load(in);
588 }
589 String url = commonProps.getProperty(ManifestConstants.SLC_ORIGIN_URI.toString());
590 if (url == null) {
591 url = uris.getProperty(relativePath.getFileName().toString());
592 if (url == null)
593 throw new IllegalStateException("No url available for " + duDir);
594 commonProps.put(ManifestConstants.SLC_ORIGIN_URI.toString(), url);
595 }
596 Path downloaded = tryDownload(url, originBase);
597
598 FileSystem zipFs = FileSystems.newFileSystem(downloaded, (ClassLoader) null);
599
600 // filters
601 List<PathMatcher> includeMatchers = new ArrayList<>();
602 Properties includes = new Properties();
603 try (InputStream in = Files.newInputStream(duDir.resolve("includes.properties"))) {
604 includes.load(in);
605 }
606 for (Object pattern : includes.keySet()) {
607 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
608 includeMatchers.add(pathMatcher);
609 }
610
611 List<PathMatcher> excludeMatchers = new ArrayList<>();
612 Path excludeFile = duDir.resolve("excludes.properties");
613 if (Files.exists(excludeFile)) {
614 Properties excludes = new Properties();
615 try (InputStream in = Files.newInputStream(excludeFile)) {
616 excludes.load(in);
617 }
618 for (Object pattern : excludes.keySet()) {
619 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
620 excludeMatchers.add(pathMatcher);
621 }
622 }
623
624 Files.walkFileTree(zipFs.getRootDirectories().iterator().next(), new SimpleFileVisitor<Path>() {
625
626 @Override
627 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
628 includeMatchers: for (PathMatcher includeMatcher : includeMatchers) {
629 if (includeMatcher.matches(file)) {
630 for (PathMatcher excludeMatcher : excludeMatchers) {
631 if (excludeMatcher.matches(file)) {
632 logger.log(Level.WARNING, "Skipping excluded " + file);
633 return FileVisitResult.CONTINUE;
634 }
635 }
636 if (includeSources && file.getFileName().toString().contains(".source_")) {
637 processEclipseSourceJar(file, targetCategoryBase);
638 logger.log(Level.DEBUG, () -> "Processed source " + file);
639
640 } else {
641 processBundleJar(file, targetCategoryBase, new HashMap(commonProps));
642 logger.log(Level.DEBUG, () -> "Processed " + file);
643 }
644 break includeMatchers;
645 }
646 }
647 return FileVisitResult.CONTINUE;
648 }
649 });
650
651 DirectoryStream<Path> dirs = Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p));
652 for (Path dir : dirs) {
653 createJar(dir);
654 }
655 } catch (IOException e) {
656 throw new RuntimeException("Cannot process " + relativePath, e);
657 }
658
659 }
660
661 /** Process sources in Eclipse format. */
662 protected void processEclipseSourceJar(Path file, Path targetBase) throws IOException {
663 try {
664 Path targetBundleDir;
665 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
666 Manifest manifest = jarIn.getManifest();
667
668 String[] relatedBundle = manifest.getMainAttributes().getValue("Eclipse-SourceBundle").split(";");
669 String version = relatedBundle[1].substring("version=\"".length());
670 version = version.substring(0, version.length() - 1);
671 NameVersion nameVersion = new DefaultNameVersion(relatedBundle[0], version);
672 targetBundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
673
674 Path targetSourceDir = targetBundleDir.resolve("OSGI-OPT/src");
675
676 // TODO make it less dangerous?
677 if (Files.exists(targetSourceDir)) {
678 // deleteDirectory(targetSourceDir);
679 } else {
680 Files.createDirectories(targetSourceDir);
681 }
682
683 // copy entries
684 JarEntry entry;
685 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
686 if (entry.isDirectory())
687 continue entries;
688 if (entry.getName().startsWith("META-INF"))// skip META-INF entries
689 continue entries;
690 Path target = targetSourceDir.resolve(entry.getName());
691 Files.createDirectories(target.getParent());
692 Files.copy(jarIn, target);
693 logger.log(Level.TRACE, () -> "Copied source " + target);
694 }
695
696 // copy MANIFEST
697 // Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
698 // Files.createDirectories(manifestPath.getParent());
699 // try (OutputStream out = Files.newOutputStream(manifestPath)) {
700 // manifest.write(out);
701 // }
702 }
703 } catch (IOException e) {
704 throw new IllegalStateException("Cannot process " + file, e);
705 }
706
707 }
708
709 /*
710 * COMMON PROCESSING
711 */
712 /** Normalise a bundle. */
713 protected Path processBundleJar(Path file, Path targetBase, Map<String, String> entries) throws IOException {
714 DefaultNameVersion nameVersion;
715 Path targetBundleDir;
716 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
717 Manifest sourceManifest = jarIn.getManifest();
718 Manifest manifest = sourceManifest != null ? new Manifest(sourceManifest) : new Manifest();
719
720 // remove problematic entries in MANIFEST
721 manifest.getEntries().clear();
722 // Set<String> entriesToDelete = new HashSet<>();
723 // for (String key : manifest.getEntries().keySet()) {
724 //// logger.log(DEBUG, "## " + key);
725 // Attributes attrs = manifest.getAttributes(key);
726 // for (Object attrName : attrs.keySet()) {
727 //// logger.log(DEBUG, attrName + "=" + attrs.get(attrName));
728 // if ("Specification-Version".equals(attrName.toString())
729 // || "Implementation-Version".equals(attrName.toString())) {
730 // entriesToDelete.add(key);
731 //
732 // }
733 // }
734 // }
735 // for (String key : entriesToDelete) {
736 // manifest.getEntries().remove(key);
737 // }
738
739 String ourSymbolicName = entries.get(BUNDLE_SYMBOLICNAME.toString());
740 String ourVersion = entries.get(BUNDLE_VERSION.toString());
741
742 if (ourSymbolicName != null && ourVersion != null) {
743 nameVersion = new DefaultNameVersion(ourSymbolicName, ourVersion);
744 } else {
745 nameVersion = nameVersionFromManifest(manifest);
746 if (ourVersion != null && !nameVersion.getVersion().equals(ourVersion)) {
747 logger.log(Level.WARNING,
748 "Original version is " + nameVersion.getVersion() + " while new version is " + ourVersion);
749 entries.put(BUNDLE_VERSION.toString(), ourVersion);
750 }
751 if (ourSymbolicName != null) {
752 // we always force our symbolic name
753 nameVersion.setName(ourSymbolicName);
754 }
755 }
756 targetBundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
757
758 // force Java 9 module name
759 entries.put(ManifestConstants.AUTOMATIC_MODULE_NAME.toString(), nameVersion.getName());
760
761 // TODO make it less dangerous?
762 // if (Files.exists(targetBundleDir)) {
763 // deleteDirectory(targetBundleDir);
764 // }
765
766 boolean isNative = false;
767 String os = null;
768 String arch = null;
769 if (targetBundleDir.startsWith(a2LibBase)) {
770 isNative = true;
771 Path libRelativePath = a2LibBase.relativize(targetBundleDir);
772 os = libRelativePath.getName(0).toString();
773 arch = libRelativePath.getName(1).toString();
774 }
775
776 // copy entries
777 JarEntry entry;
778 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
779 if (entry.isDirectory())
780 continue entries;
781 if (entry.getName().endsWith(".RSA") || entry.getName().endsWith(".SF"))
782 continue entries;
783 if (entry.getName().endsWith("module-info.class")) // skip Java 9 module info
784 continue entries;
785 if (entry.getName().startsWith("META-INF/versions/")) // skip multi-version
786 continue entries;
787 // skip file system providers as they cause issues with native image
788 if (entry.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider"))
789 continue entries;
790 if (entry.getName().startsWith("OSGI-OPT/src/")) // skip embedded sources
791 continue entries;
792 Path target = targetBundleDir.resolve(entry.getName());
793 Files.createDirectories(target.getParent());
794 Files.copy(jarIn, target);
795
796 // native libraries
797 if (isNative && (entry.getName().endsWith(".so") || entry.getName().endsWith(".dll")
798 || entry.getName().endsWith(".jnilib"))) {
799 Path categoryDir = targetBundleDir.getParent();
800 // String[] segments = categoryDir.getFileName().toString().split("\\.");
801 // String arch = segments[segments.length - 1];
802 // String os = segments[segments.length - 2];
803 boolean copyDll = false;
804 Path targetDll = categoryDir.resolve(target.getFileName());
805 if (nameVersion.getName().equals("com.sun.jna")) {
806 if (arch.equals("x86_64"))
807 arch = "x86-64";
808 if (os.equals("macosx"))
809 os = "darwin";
810 if (target.getParent().getFileName().toString().equals(os + "-" + arch)) {
811 copyDll = true;
812 }
813 } else {
814 copyDll = true;
815 }
816 if (copyDll) {
817 if (Files.exists(targetDll))
818 Files.delete(targetDll);
819 Files.copy(target, targetDll);
820 }
821 Files.delete(target);
822 }
823 logger.log(Level.TRACE, () -> "Copied " + target);
824 }
825
826 // copy MANIFEST
827 Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
828 Files.createDirectories(manifestPath.getParent());
829 for (String key : entries.keySet()) {
830 String value = entries.get(key);
831 Object previousValue = manifest.getMainAttributes().putValue(key, value);
832 if (previousValue != null && !previousValue.equals(value)) {
833 if (ManifestConstants.IMPORT_PACKAGE.toString().equals(key)
834 || ManifestConstants.EXPORT_PACKAGE.toString().equals(key))
835 logger.log(Level.TRACE, file.getFileName() + ": " + key + " was modified");
836 else
837 logger.log(Level.WARNING, file.getFileName() + ": " + key + " was " + previousValue
838 + ", overridden with " + value);
839 }
840
841 // hack to remove unresolvable
842 if (key.equals("Provide-Capability") || key.equals("Require-Capability"))
843 if (nameVersion.getName().equals("osgi.core") || nameVersion.getName().equals("osgi.cmpn")) {
844 manifest.getMainAttributes().remove(key);
845 }
846 }
847 try (OutputStream out = Files.newOutputStream(manifestPath)) {
848 manifest.write(out);
849 }
850 }
851 return targetBundleDir;
852 }
853
854 /*
855 * UTILITIES
856 */
857
858 /** Recursively deletes a directory. */
859 private static void deleteDirectory(Path path) throws IOException {
860 if (!Files.exists(path))
861 return;
862 Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
863 @Override
864 public FileVisitResult postVisitDirectory(Path directory, IOException e) throws IOException {
865 if (e != null)
866 throw e;
867 Files.delete(directory);
868 return FileVisitResult.CONTINUE;
869 }
870
871 @Override
872 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
873 Files.delete(file);
874 return FileVisitResult.CONTINUE;
875 }
876 });
877 }
878
879 /** Extract name/version from a MANIFEST. */
880 protected DefaultNameVersion nameVersionFromManifest(Manifest manifest) {
881 Attributes attrs = manifest.getMainAttributes();
882 // symbolic name
883 String symbolicName = attrs.getValue(ManifestConstants.BUNDLE_SYMBOLICNAME.toString());
884 if (symbolicName == null)
885 return null;
886 // make sure there is no directive
887 symbolicName = symbolicName.split(";")[0];
888
889 String version = attrs.getValue(ManifestConstants.BUNDLE_VERSION.toString());
890 return new DefaultNameVersion(symbolicName, version);
891 }
892
893 /** Try to download from an URI. */
894 protected Path tryDownload(String uri, Path dir) throws IOException {
895 // find mirror
896 List<String> urlBases = null;
897 String uriPrefix = null;
898 uriPrefixes: for (String uriPref : mirrors.keySet()) {
899 if (uri.startsWith(uriPref)) {
900 if (mirrors.get(uriPref).size() > 0) {
901 urlBases = mirrors.get(uriPref);
902 uriPrefix = uriPref;
903 break uriPrefixes;
904 }
905 }
906 }
907 if (urlBases == null)
908 try {
909 return download(new URL(uri), dir);
910 } catch (FileNotFoundException e) {
911 throw new FileNotFoundException("Cannot find " + uri);
912 }
913
914 // try to download
915 for (String urlBase : urlBases) {
916 String relativePath = uri.substring(uriPrefix.length());
917 URL url = new URL(urlBase + relativePath);
918 try {
919 return download(url, dir);
920 } catch (FileNotFoundException e) {
921 logger.log(Level.WARNING, "Cannot download " + url + ", trying another mirror");
922 }
923 }
924 throw new FileNotFoundException("Cannot find " + uri);
925 }
926
927 // protected String simplifyName(URL u) {
928 // String name = u.getPath().substring(u.getPath().lastIndexOf('/') + 1);
929 //
930 // }
931
932 /** Effectively download. */
933 protected Path download(URL url, Path dir) throws IOException {
934 return download(url, dir, (String) null);
935 }
936
937 /** Effectively download. */
938 protected Path download(URL url, Path dir, String name) throws IOException {
939
940 Path dest;
941 if (name == null) {
942 name = url.getPath().substring(url.getPath().lastIndexOf('/') + 1);
943 }
944
945 dest = dir.resolve(name);
946 if (Files.exists(dest)) {
947 logger.log(Level.TRACE, () -> "File " + dest + " already exists for " + url + ", not downloading again");
948 return dest;
949 } else {
950 Files.createDirectories(dest.getParent());
951 }
952
953 try (InputStream in = url.openStream()) {
954 Files.copy(in, dest);
955 logger.log(Level.DEBUG, () -> "Downloaded " + dest + " from " + url);
956 }
957 return dest;
958 }
959
960 /** Create a JAR file from a directory. */
961 protected Path createJar(Path bundleDir) throws IOException {
962 // Remove from source the resources already in the jar file
963 // Path srcDir = bundleDir.resolve("OSGI-OPT/src");
964 // Files.walkFileTree(srcDir, new SimpleFileVisitor<Path>() {
965 //
966 // @Override
967 // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
968 // // always keep .java file
969 // if (file.getFileName().toString().endsWith(".java"))
970 // return super.visitFile(file, attrs);
971 //
972 // Path relPath = srcDir.relativize(file);
973 // Path bundlePath = bundleDir.resolve(relPath);
974 // if (Files.exists(bundlePath)) {
975 // Files.delete(file);
976 // logger.log(DEBUG, () -> "Removed " + file + " from sources.");
977 // }
978 // return super.visitFile(file, attrs);
979 // }
980 //
981 // });
982
983 // Create the jar
984 Path jarPath = bundleDir.getParent().resolve(bundleDir.getFileName() + ".jar");
985 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
986 Manifest manifest;
987 try (InputStream in = Files.newInputStream(manifestPath)) {
988 manifest = new Manifest(in);
989 }
990 try (JarOutputStream jarOut = new JarOutputStream(Files.newOutputStream(jarPath), manifest)) {
991 jarOut.setLevel(Deflater.DEFAULT_COMPRESSION);
992 Files.walkFileTree(bundleDir, new SimpleFileVisitor<Path>() {
993
994 @Override
995 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
996 if (file.getFileName().toString().equals("MANIFEST.MF"))
997 return super.visitFile(file, attrs);
998 JarEntry entry = new JarEntry(bundleDir.relativize(file).toString());
999 jarOut.putNextEntry(entry);
1000 Files.copy(file, jarOut);
1001 return super.visitFile(file, attrs);
1002 }
1003
1004 });
1005 }
1006 deleteDirectory(bundleDir);
1007 return jarPath;
1008 }
1009
1010 /** For development purproses. */
1011 public static void main(String[] args) {
1012 Path factoryBase = Paths.get("../../output/a2").toAbsolutePath().normalize();
1013 Path descriptorsBase = Paths.get("../tp").toAbsolutePath().normalize();
1014 A2Factory factory = new A2Factory(factoryBase, descriptorsBase, true);
1015
1016 // factory.processSingleM2ArtifactDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache").resolve("org.apache.xml.resolver.bnd"));
1017 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache/apache-sshd"));
1018 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.jetty/jetty"));
1019 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.osgi"));
1020 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.eclipse.rcp"));
1021 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp"));
1022 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.apache"));
1023 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.sdk"));
1024 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.formats"));
1025 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.gis"));
1026
1027 // SDK
1028 factory.processCategory(Paths.get("org.argeo.tp.sdk"));
1029
1030 // Eclipse
1031 factory.processCategory(Paths.get("osgi/api/org.argeo.tp.osgi"));
1032 factory.processEclipseArchive(Paths.get("osgi/equinox/org.argeo.tp.osgi", "eclipse-equinox"));
1033
1034 factory.processEclipseArchive(Paths.get("org.argeo.tp.eclipse", "eclipse-equinox"));
1035
1036 factory.processEclipseArchive(Paths.get("swt/rap/org.argeo.tp.swt", "eclipse-rap"));
1037 factory.processEclipseArchive(Paths.get("swt/rap/org.argeo.tp.swt.workbench", "eclipse-rap"));
1038
1039 factory.processEclipseArchive(Paths.get("swt/rcp/org.argeo.tp.swt", "eclipse-rcp"));
1040
1041 factory.processEclipseArchive(Paths.get("lib/linux/x86_64/swt/rcp/org.argeo.tp.swt", "eclipse-rcp"));
1042 factory.processEclipseArchive(Paths.get("lib/linux/aarch64/swt/rcp/org.argeo.tp.swt", "eclipse-rcp"));
1043 factory.processEclipseArchive(Paths.get("lib/win32/x86_64/swt/rcp/org.argeo.tp.swt", "eclipse-rcp"));
1044 factory.processEclipseArchive(Paths.get("lib/macosx/x86_64/swt/rcp/org.argeo.tp.swt", "eclipse-rcp"));
1045 System.exit(1);
1046 factory.processEclipseArchive(Paths.get("swt/rcp/org.argeo.tp.swt", "eclipse-nebula"));
1047 // factory.processEclipseArchive(Paths.get("swt/rcp/org.argeo.tp.swt",
1048 // "eclipse-equinox"));
1049 factory.processEclipseArchive(Paths.get("swt/rcp/org.argeo.tp.swt.workbench", "eclipse-rcp"));
1050 factory.processCategory(Paths.get("swt/rcp/org.argeo.tp.swt.workbench"));
1051
1052 // Maven
1053 factory.processCategory(Paths.get("org.argeo.tp"));
1054 factory.processCategory(Paths.get("org.argeo.tp.apache"));
1055 factory.processCategory(Paths.get("org.argeo.tp.jetty"));
1056 factory.processCategory(Paths.get("org.argeo.tp.jcr"));
1057 factory.processCategory(Paths.get("org.argeo.tp.formats"));
1058 factory.processCategory(Paths.get("org.argeo.tp.poi"));
1059 factory.processCategory(Paths.get("org.argeo.tp.gis"));
1060 }
1061 }