]> git.argeo.org Git - cc0/argeo-build.git/blob - build/Repackage.java
Releasing
[cc0/argeo-build.git] / build / Repackage.java
1 package org.argeo.build;
2
3 import static java.lang.System.Logger.Level.DEBUG;
4 import static java.lang.System.Logger.Level.ERROR;
5 import static java.lang.System.Logger.Level.INFO;
6 import static java.lang.System.Logger.Level.TRACE;
7 import static java.lang.System.Logger.Level.WARNING;
8 import static java.nio.file.FileVisitResult.CONTINUE;
9 import static java.util.jar.Attributes.Name.MANIFEST_VERSION;
10 import static org.argeo.build.Repackage.ManifestConstants.ARGEO_ORIGIN_EMBED;
11 import static org.argeo.build.Repackage.ManifestConstants.ARGEO_ORIGIN_M2;
12 import static org.argeo.build.Repackage.ManifestConstants.ARGEO_ORIGIN_M2_MERGE;
13 import static org.argeo.build.Repackage.ManifestConstants.ARGEO_ORIGIN_M2_REPO;
14 import static org.argeo.build.Repackage.ManifestConstants.ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED;
15 import static org.argeo.build.Repackage.ManifestConstants.ARGEO_ORIGIN_URI;
16 import static org.argeo.build.Repackage.ManifestConstants.BUNDLE_LICENSE;
17 import static org.argeo.build.Repackage.ManifestConstants.BUNDLE_SYMBOLICNAME;
18 import static org.argeo.build.Repackage.ManifestConstants.BUNDLE_VERSION;
19 import static org.argeo.build.Repackage.ManifestConstants.ECLIPSE_SOURCE_BUNDLE;
20 import static org.argeo.build.Repackage.ManifestConstants.EXPORT_PACKAGE;
21 import static org.argeo.build.Repackage.ManifestConstants.IMPORT_PACKAGE;
22 import static org.argeo.build.Repackage.ManifestConstants.SPDX_LICENSE_IDENTIFIER;
23
24 import java.io.BufferedWriter;
25 import java.io.File;
26 import java.io.FileNotFoundException;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.OutputStream;
30 import java.lang.System.Logger;
31 import java.net.MalformedURLException;
32 import java.net.URL;
33 import java.nio.charset.StandardCharsets;
34 import java.nio.file.DirectoryStream;
35 import java.nio.file.FileSystem;
36 import java.nio.file.FileSystems;
37 import java.nio.file.FileVisitResult;
38 import java.nio.file.Files;
39 import java.nio.file.Path;
40 import java.nio.file.PathMatcher;
41 import java.nio.file.Paths;
42 import java.nio.file.SimpleFileVisitor;
43 import java.nio.file.StandardOpenOption;
44 import java.nio.file.attribute.BasicFileAttributes;
45 import java.util.ArrayList;
46 import java.util.HashMap;
47 import java.util.Iterator;
48 import java.util.List;
49 import java.util.Map;
50 import java.util.Objects;
51 import java.util.Properties;
52 import java.util.Set;
53 import java.util.TreeMap;
54 import java.util.TreeSet;
55 import java.util.concurrent.CompletableFuture;
56 import java.util.jar.Attributes;
57 import java.util.jar.JarEntry;
58 import java.util.jar.JarInputStream;
59 import java.util.jar.JarOutputStream;
60 import java.util.jar.Manifest;
61 import java.util.zip.Deflater;
62
63 import aQute.bnd.osgi.Analyzer;
64 import aQute.bnd.osgi.Jar;
65
66 /**
67 * Simple tool repackaging existing jar files into OSGi bundles in an A2
68 * repository.
69 */
70 public class Repackage {
71 final static Logger logger = System.getLogger(Repackage.class.getName());
72
73 /**
74 * Environment variable on whether sources should be packaged separately or
75 * integrated in the bundles.
76 */
77 final static String ENV_SOURCE_BUNDLES = "SOURCE_BUNDLES";
78
79 /** Whether repackaging should run in parallel or sequentially. */
80 final static boolean parallel = true;
81
82 // cache
83 /** Summary of all license seen during the repackaging. */
84 final static Map<String, Set<String>> licensesUsed = new TreeMap<>();
85
86 /** Main entry point. */
87 public static void main(String[] args) {
88 if (args.length < 2) {
89 System.err.println("Usage: <path to a2 output dir> <category1> <category2> ...");
90 System.exit(1);
91 }
92 Path a2Base = Paths.get(args[0]).toAbsolutePath().normalize();
93 Path descriptorsBase = Paths.get(".").toAbsolutePath().normalize();
94 Repackage factory = new Repackage(a2Base, descriptorsBase);
95
96 List<CompletableFuture<Void>> toDos = new ArrayList<>();
97 for (int i = 1; i < args.length; i++) {
98 Path p = Paths.get(args[i]);
99 if (parallel)
100 toDos.add(CompletableFuture.runAsync(() -> factory.processCategory(p)));
101 else
102 factory.processCategory(p);
103 }
104 CompletableFuture.allOf(toDos.toArray(new CompletableFuture[toDos.size()])).join();
105
106 // Summary
107 StringBuilder sb = new StringBuilder();
108 for (String licenseId : licensesUsed.keySet())
109 for (String name : licensesUsed.get(licenseId))
110 sb.append((licenseId.equals("") ? "Proprietary" : licenseId) + "\t\t" + name + "\n");
111 logger.log(INFO, "# License summary:\n" + sb);
112 }
113
114 /** Name of the file centralising information for multiple M2 artifacts. */
115 final static String COMMON_BND = "common.bnd";
116 /** Name of the file centralising information for mergin M2 artifacts. */
117 final static String MERGE_BND = "merge.bnd";
118 /**
119 * Subdirectory of the jar file where origin informations (changes, legal
120 * notices etc. are stored)
121 */
122 final static String A2_ORIGIN = "A2-ORIGIN";
123
124 /** Directory where to download archives */
125 Path originBase;
126 /** Directory where to download Maven artifacts */
127 Path mavenBase;
128
129 /** A2 repository base for binary bundles */
130 Path a2Base;
131 /** A2 repository base for source bundles */
132 Path a2SrcBase;
133 /** A2 base for native components */
134 Path a2LibBase;
135 /** Location of the descriptors driving the packaging */
136 Path descriptorsBase;
137 /** URIs of archives to download */
138 Properties uris = new Properties();
139 /** Mirrors for archive download. Key is URI prefix, value list of base URLs */
140 Map<String, List<String>> mirrors = new HashMap<String, List<String>>();
141
142 /** Whether sources should be packaged separately */
143 final boolean sourceBundles;
144
145 /** Constructor initialises the various variables */
146 public Repackage(Path a2Base, Path descriptorsBase) {
147 sourceBundles = Boolean.parseBoolean(System.getenv(ENV_SOURCE_BUNDLES));
148 if (sourceBundles)
149 logger.log(INFO, "Sources will be packaged separately");
150
151 Objects.requireNonNull(a2Base);
152 Objects.requireNonNull(descriptorsBase);
153 this.originBase = Paths.get(System.getProperty("user.home"), ".cache", "argeo/build/origin");
154 this.mavenBase = Paths.get(System.getProperty("user.home"), ".m2", "repository");
155
156 // TODO define and use a build base
157 this.a2Base = a2Base;
158 this.a2SrcBase = a2Base.getParent().resolve(a2Base.getFileName() + ".src");
159 this.a2LibBase = a2Base.resolve("lib");
160 this.descriptorsBase = descriptorsBase;
161 if (!Files.exists(this.descriptorsBase))
162 throw new IllegalArgumentException(this.descriptorsBase + " does not exist");
163
164 // URIs mapping
165 Path urisPath = this.descriptorsBase.resolve("uris.properties");
166 if (Files.exists(urisPath)) {
167 try (InputStream in = Files.newInputStream(urisPath)) {
168 uris.load(in);
169 } catch (IOException e) {
170 throw new IllegalStateException("Cannot load " + urisPath, e);
171 }
172 }
173
174 // Eclipse mirrors
175 Path eclipseMirrorsPath = this.descriptorsBase.resolve("eclipse.mirrors.txt");
176 List<String> eclipseMirrors = new ArrayList<>();
177 if (Files.exists(eclipseMirrorsPath)) {
178 try {
179 eclipseMirrors = Files.readAllLines(eclipseMirrorsPath, StandardCharsets.UTF_8);
180 } catch (IOException e) {
181 throw new IllegalStateException("Cannot load " + eclipseMirrorsPath, e);
182 }
183 for (Iterator<String> it = eclipseMirrors.iterator(); it.hasNext();) {
184 String value = it.next();
185 if (value.strip().equals(""))
186 it.remove();
187 }
188 }
189 mirrors.put("http://www.eclipse.org/downloads", eclipseMirrors);
190 }
191
192 /*
193 * MAVEN ORIGIN
194 */
195 /** Process a whole category/group id. */
196 void processCategory(Path categoryRelativePath) {
197 try {
198 Path targetCategoryBase = descriptorsBase.resolve(categoryRelativePath);
199 DirectoryStream<Path> bnds = Files.newDirectoryStream(targetCategoryBase,
200 (p) -> p.getFileName().toString().endsWith(".bnd") && !p.getFileName().toString().equals(COMMON_BND)
201 && !p.getFileName().toString().equals(MERGE_BND));
202 for (Path p : bnds) {
203 processSingleM2ArtifactDistributionUnit(p);
204 }
205
206 DirectoryStream<Path> dus = Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p));
207 for (Path duDir : dus) {
208 if (duDir.getFileName().toString().startsWith("eclipse-")) {
209 processEclipseArchive(duDir);
210 } else {
211 processM2BasedDistributionUnit(duDir);
212 }
213 }
214 } catch (IOException e) {
215 throw new RuntimeException("Cannot process category " + categoryRelativePath, e);
216 }
217 }
218
219 /** Process a standalone Maven artifact. */
220 void processSingleM2ArtifactDistributionUnit(Path bndFile) {
221 try {
222 Path categoryRelativePath = descriptorsBase.relativize(bndFile.getParent());
223 Path targetCategoryBase = a2Base.resolve(categoryRelativePath);
224
225 Properties fileProps = new Properties();
226 try (InputStream in = Files.newInputStream(bndFile)) {
227 fileProps.load(in);
228 }
229 String repoStr = fileProps.containsKey(ARGEO_ORIGIN_M2_REPO.toString())
230 ? fileProps.getProperty(ARGEO_ORIGIN_M2_REPO.toString())
231 : null;
232
233 if (!fileProps.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
234 // use file name as symbolic name
235 String symbolicName = bndFile.getFileName().toString();
236 symbolicName = symbolicName.substring(0, symbolicName.length() - ".bnd".length());
237 fileProps.put(BUNDLE_SYMBOLICNAME.toString(), symbolicName);
238 }
239
240 String m2Coordinates = fileProps.getProperty(ARGEO_ORIGIN_M2.toString());
241 if (m2Coordinates == null)
242 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile);
243 M2Artifact artifact = new M2Artifact(m2Coordinates);
244 URL url = M2ConventionsUtils.mavenRepoUrl(repoStr, artifact);
245 Path downloaded = downloadMaven(url, artifact);
246
247 A2Origin origin = new A2Origin();
248 Path targetBundleDir = processBndJar(downloaded, targetCategoryBase, fileProps, artifact, origin);
249
250 downloadAndProcessM2Sources(repoStr, artifact, targetBundleDir, false);
251
252 createJar(targetBundleDir, origin);
253 } catch (Exception e) {
254 throw new RuntimeException("Cannot process " + bndFile, e);
255 }
256 }
257
258 /**
259 * Process multiple Maven artifacts coming from a same project and therefore
260 * with information in common (typically the version), generating single bundles
261 * or merging them if necessary.
262 */
263 void processM2BasedDistributionUnit(Path duDir) {
264 try {
265 Path categoryRelativePath = descriptorsBase.relativize(duDir.getParent());
266 Path targetCategoryBase = a2Base.resolve(categoryRelativePath);
267
268 Path mergeBnd = duDir.resolve(MERGE_BND);
269 if (Files.exists(mergeBnd)) // merge
270 mergeM2Artifacts(mergeBnd);
271
272 Path commonBnd = duDir.resolve(COMMON_BND);
273 if (!Files.exists(commonBnd))
274 return;
275
276 Properties commonProps = new Properties();
277 try (InputStream in = Files.newInputStream(commonBnd)) {
278 commonProps.load(in);
279 }
280
281 String m2Version = commonProps.getProperty(ARGEO_ORIGIN_M2.toString());
282 if (m2Version == null) {
283 logger.log(WARNING, "Ignoring " + duDir + " as it is not an M2-based distribution unit");
284 return;// ignore, this is probably an Eclipse archive
285 }
286 if (!m2Version.startsWith(":")) {
287 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version);
288 }
289 m2Version = m2Version.substring(1);
290
291 DirectoryStream<Path> ds = Files.newDirectoryStream(duDir,
292 (p) -> p.getFileName().toString().endsWith(".bnd") && !p.getFileName().toString().equals(COMMON_BND)
293 && !p.getFileName().toString().equals(MERGE_BND));
294 for (Path p : ds) {
295 Properties fileProps = new Properties();
296 try (InputStream in = Files.newInputStream(p)) {
297 fileProps.load(in);
298 }
299 String m2Coordinates = fileProps.getProperty(ARGEO_ORIGIN_M2.toString());
300 M2Artifact artifact = new M2Artifact(m2Coordinates);
301 artifact.setVersion(m2Version);
302
303 // prepare manifest entries
304 Properties mergeProps = new Properties();
305 mergeProps.putAll(commonProps);
306
307 fileEntries: for (Object key : fileProps.keySet()) {
308 if (ARGEO_ORIGIN_M2.toString().equals(key))
309 continue fileEntries;
310 String value = fileProps.getProperty(key.toString());
311 Object previousValue = mergeProps.put(key.toString(), value);
312 if (previousValue != null) {
313 logger.log(WARNING,
314 commonBnd + ": " + key + " was " + previousValue + ", overridden with " + value);
315 }
316 }
317 mergeProps.put(ARGEO_ORIGIN_M2.toString(), artifact.toM2Coordinates());
318 if (!mergeProps.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
319 // use file name as symbolic name
320 String symbolicName = p.getFileName().toString();
321 symbolicName = symbolicName.substring(0, symbolicName.length() - ".bnd".length());
322 mergeProps.put(BUNDLE_SYMBOLICNAME.toString(), symbolicName);
323 }
324
325 String repoStr = mergeProps.containsKey(ARGEO_ORIGIN_M2_REPO.toString())
326 ? mergeProps.getProperty(ARGEO_ORIGIN_M2_REPO.toString())
327 : null;
328
329 // download
330 URL url = M2ConventionsUtils.mavenRepoUrl(repoStr, artifact);
331 Path downloaded = downloadMaven(url, artifact);
332
333 A2Origin origin = new A2Origin();
334 Path targetBundleDir = processBndJar(downloaded, targetCategoryBase, mergeProps, artifact, origin);
335 downloadAndProcessM2Sources(repoStr, artifact, targetBundleDir, false);
336 createJar(targetBundleDir, origin);
337 }
338 } catch (IOException e) {
339 throw new RuntimeException("Cannot process " + duDir, e);
340 }
341 }
342
343 /** Merge multiple Maven artifacts. */
344 void mergeM2Artifacts(Path mergeBnd) throws IOException {
345 Path duDir = mergeBnd.getParent();
346 String category = duDir.getParent().getFileName().toString();
347 Path targetCategoryBase = a2Base.resolve(category);
348
349 Properties mergeProps = new Properties();
350 try (InputStream in = Files.newInputStream(mergeBnd)) {
351 mergeProps.load(in);
352 }
353
354 String m2Version = mergeProps.getProperty(ARGEO_ORIGIN_M2.toString());
355 if (m2Version == null) {
356 logger.log(WARNING, "Ignoring " + duDir + " as it is not an M2-based distribution unit");
357 return;// ignore, this is probably an Eclipse archive
358 }
359 if (!m2Version.startsWith(":")) {
360 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version);
361 }
362 m2Version = m2Version.substring(1);
363 mergeProps.put(BUNDLE_VERSION.toString(), m2Version);
364
365 String artifactsStr = mergeProps.getProperty(ARGEO_ORIGIN_M2_MERGE.toString());
366 if (artifactsStr == null)
367 throw new IllegalArgumentException(mergeBnd + ": " + ARGEO_ORIGIN_M2_MERGE + " must be set");
368
369 String repoStr = mergeProps.containsKey(ARGEO_ORIGIN_M2_REPO.toString())
370 ? mergeProps.getProperty(ARGEO_ORIGIN_M2_REPO.toString())
371 : null;
372
373 String bundleSymbolicName = mergeProps.getProperty(BUNDLE_SYMBOLICNAME.toString());
374 if (bundleSymbolicName == null)
375 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd);
376 CategoryNameVersion nameVersion = new M2Artifact(category + ":" + bundleSymbolicName + ":" + m2Version);
377
378 A2Origin origin = new A2Origin();
379 Path bundleDir = targetCategoryBase.resolve(bundleSymbolicName + "." + nameVersion.getBranch());
380
381 String[] artifacts = artifactsStr.split(",");
382 artifacts: for (String str : artifacts) {
383 String m2Coordinates = str.trim();
384 if ("".equals(m2Coordinates))
385 continue artifacts;
386 M2Artifact artifact = new M2Artifact(m2Coordinates.trim());
387 if (artifact.getVersion() == null)
388 artifact.setVersion(m2Version);
389 URL url = M2ConventionsUtils.mavenRepoUrl(repoStr, artifact);
390 Path downloaded = downloadMaven(url, artifact);
391 JarEntry entry;
392 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(downloaded), false)) {
393 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
394 if (entry.isDirectory())
395 continue entries;
396 if (entry.getName().endsWith(".RSA") || entry.getName().endsWith(".SF")) {
397 origin.deleted.add("cryptographic signatures from " + artifact);
398 continue entries;
399 }
400 if (entry.getName().endsWith("module-info.class")) { // skip Java 9 module info
401 origin.deleted.add("Java module information (module-info.class) from " + artifact);
402 continue entries;
403 }
404 if (entry.getName().startsWith("META-INF/versions/")) { // skip multi-version
405 origin.deleted.add("additional Java versions (META-INF/versions) from " + artifact);
406 continue entries;
407 }
408 if (entry.getName().startsWith("META-INF/maven/")) {
409 origin.deleted.add("Maven information (META-INF/maven) from " + artifact);
410 continue entries;
411 }
412 if (entry.getName().startsWith(".cache/")) { // Apache SSHD
413 origin.deleted.add("cache directory (.cache) from " + artifact);
414 continue entries;
415 }
416 if (entry.getName().equals("META-INF/DEPENDENCIES")) {
417 origin.deleted.add("Dependencies (META-INF/DEPENDENCIES) from " + artifact);
418 continue entries;
419 }
420 if (entry.getName().equals("META-INF/MANIFEST.MF")) {
421 Path originalManifest = bundleDir.resolve(A2_ORIGIN).resolve(artifact.getGroupId())
422 .resolve(artifact.getArtifactId()).resolve("MANIFEST.MF");
423 Files.createDirectories(originalManifest.getParent());
424 try (OutputStream out = Files.newOutputStream(originalManifest)) {
425 Files.copy(jarIn, originalManifest);
426 }
427 origin.added.add(
428 "original MANIFEST (" + bundleDir.relativize(originalManifest) + ") from " + artifact);
429 continue entries;
430 }
431
432 if (entry.getName().endsWith("NOTICE") || entry.getName().endsWith("NOTICE.txt")
433 || entry.getName().endsWith("LICENSE") || entry.getName().endsWith("LICENSE.md")
434 || entry.getName().endsWith("LICENSE-notice.md") || entry.getName().endsWith("COPYING")
435 || entry.getName().endsWith("COPYING.LESSER")) {
436 Path artifactOriginDir = bundleDir.resolve(A2_ORIGIN).resolve(artifact.getGroupId())
437 .resolve(artifact.getArtifactId());
438 Path target = artifactOriginDir.resolve(entry.getName());
439 Files.createDirectories(target.getParent());
440 Files.copy(jarIn, target);
441 origin.moved.add(entry.getName() + " in " + artifact + " to " + bundleDir.relativize(target));
442 continue entries;
443 }
444 Path target = bundleDir.resolve(entry.getName());
445 Files.createDirectories(target.getParent());
446 if (!Files.exists(target)) {
447 Files.copy(jarIn, target);
448 } else {
449 if (entry.getName().startsWith("META-INF/services/")) {
450 try (OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND)) {
451 out.write("\n".getBytes());
452 jarIn.transferTo(out);
453 logger.log(DEBUG, artifact.getArtifactId() + " - Appended " + entry.getName());
454 }
455 origin.modified.add(entry.getName() + ", merging from " + artifact);
456 } else if (entry.getName().startsWith("org/apache/batik/")) {
457 logger.log(TRACE, "Skip " + entry.getName());
458 continue entries;
459 } else {
460 throw new IllegalStateException("File " + target + " from " + artifact + " already exists");
461 }
462 }
463 logger.log(TRACE, () -> "Copied " + target);
464 }
465 }
466 origin.added.add("binary content of " + artifact);
467
468 // process sources
469 downloadAndProcessM2Sources(repoStr, artifact, bundleDir, true);
470 }
471
472 // additional service files
473 Path servicesDir = duDir.resolve("services");
474 if (Files.exists(servicesDir)) {
475 for (Path p : Files.newDirectoryStream(servicesDir)) {
476 Path target = bundleDir.resolve("META-INF/services/").resolve(p.getFileName());
477 try (InputStream in = Files.newInputStream(p);
478 OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND);) {
479 out.write("\n".getBytes());
480 in.transferTo(out);
481 logger.log(DEBUG, "Appended " + p);
482 }
483 origin.added.add(bundleDir.relativize(target).toString());
484 }
485 }
486
487 Map<String, String> entries = new TreeMap<>();
488 try (Analyzer bndAnalyzer = new Analyzer()) {
489 bndAnalyzer.setProperties(mergeProps);
490 Jar jar = new Jar(bundleDir.toFile());
491 bndAnalyzer.setJar(jar);
492 Manifest manifest = bndAnalyzer.calcManifest();
493
494 keys: for (Object key : manifest.getMainAttributes().keySet()) {
495 Object value = manifest.getMainAttributes().get(key);
496
497 switch (key.toString()) {
498 case "Tool":
499 case "Bnd-LastModified":
500 case "Created-By":
501 continue keys;
502 }
503 if ("Require-Capability".equals(key.toString())
504 && value.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
505 continue keys;// hack for very old classes
506 entries.put(key.toString(), value.toString());
507 }
508 } catch (Exception e) {
509 throw new RuntimeException("Cannot process " + mergeBnd, e);
510 }
511
512 Manifest manifest = new Manifest();
513 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
514 Files.createDirectories(manifestPath.getParent());
515 for (String key : entries.keySet()) {
516 String value = entries.get(key);
517 manifest.getMainAttributes().putValue(key, value);
518 }
519
520 try (OutputStream out = Files.newOutputStream(manifestPath)) {
521 manifest.write(out);
522 }
523 createJar(bundleDir, origin);
524 }
525
526 /** Generate MANIFEST using BND. */
527 Path processBndJar(Path downloaded, Path targetCategoryBase, Properties fileProps, M2Artifact artifact,
528 A2Origin origin) {
529
530 try {
531 Map<String, String> additionalEntries = new TreeMap<>();
532 boolean doNotModify = Boolean.parseBoolean(
533 fileProps.getOrDefault(ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED.toString(), "false").toString());
534
535 // Note: we always force the symbolic name
536 if (doNotModify) {
537 fileEntries: for (Object key : fileProps.keySet()) {
538 if (ARGEO_ORIGIN_M2.toString().equals(key))
539 continue fileEntries;
540 String value = fileProps.getProperty(key.toString());
541 additionalEntries.put(key.toString(), value);
542 }
543 } else {
544 if (artifact != null) {
545 if (!fileProps.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
546 fileProps.put(BUNDLE_SYMBOLICNAME.toString(), artifact.getName());
547 }
548 if (!fileProps.containsKey(BUNDLE_VERSION.toString())) {
549 fileProps.put(BUNDLE_VERSION.toString(), artifact.getVersion());
550 }
551 }
552
553 if (!fileProps.containsKey(EXPORT_PACKAGE.toString())) {
554 fileProps.put(EXPORT_PACKAGE.toString(),
555 "*;version=\"" + fileProps.getProperty(BUNDLE_VERSION.toString()) + "\"");
556 }
557
558 try (Analyzer bndAnalyzer = new Analyzer()) {
559 bndAnalyzer.setProperties(fileProps);
560 Jar jar = new Jar(downloaded.toFile());
561 bndAnalyzer.setJar(jar);
562 Manifest manifest = bndAnalyzer.calcManifest();
563
564 keys: for (Object key : manifest.getMainAttributes().keySet()) {
565 Object value = manifest.getMainAttributes().get(key);
566
567 switch (key.toString()) {
568 case "Tool":
569 case "Bnd-LastModified":
570 case "Created-By":
571 continue keys;
572 }
573 if ("Require-Capability".equals(key.toString())
574 && value.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
575 continue keys;// !! hack for very old classes
576 additionalEntries.put(key.toString(), value.toString());
577 }
578 }
579 }
580 Path targetBundleDir = processBundleJar(downloaded, targetCategoryBase, additionalEntries, origin);
581 logger.log(DEBUG, () -> "Processed " + downloaded);
582 return targetBundleDir;
583 } catch (Exception e) {
584 throw new RuntimeException("Cannot BND process " + downloaded, e);
585 }
586
587 }
588
589 /** Download and integrates sources for a single Maven artifact. */
590 void downloadAndProcessM2Sources(String repoStr, M2Artifact artifact, Path targetBundleDir, boolean merging)
591 throws IOException {
592 try {
593 M2Artifact sourcesArtifact = new M2Artifact(artifact.toM2Coordinates(), "sources");
594 URL sourcesUrl = M2ConventionsUtils.mavenRepoUrl(repoStr, sourcesArtifact);
595 Path sourcesDownloaded = downloadMaven(sourcesUrl, artifact, true);
596 processM2SourceJar(sourcesDownloaded, targetBundleDir, merging ? artifact : null);
597 logger.log(TRACE, () -> "Processed source " + sourcesDownloaded);
598 } catch (Exception e) {
599 logger.log(ERROR, () -> "Cannot download source for " + artifact);
600 }
601
602 }
603
604 /** Integrate sources from a downloaded jar file. */
605 void processM2SourceJar(Path file, Path bundleDir, M2Artifact mergingFrom) throws IOException {
606 A2Origin origin = new A2Origin();
607 Path sourceDir = sourceBundles ? bundleDir.getParent().resolve(bundleDir.toString() + ".src")
608 : bundleDir.resolve("OSGI-OPT/src");
609 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
610
611 String mergingMsg = "";
612 if (mergingFrom != null)
613 mergingMsg = " of " + mergingFrom;
614
615 Files.createDirectories(sourceDir);
616 JarEntry entry;
617 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
618 if (entry.isDirectory())
619 continue entries;
620 if (entry.getName().startsWith("META-INF")) {// skip META-INF entries
621 origin.deleted.add("META-INF directory from the sources" + mergingMsg);
622 continue entries;
623 }
624 if (entry.getName().startsWith("module-info.java")) {// skip Java module information
625 origin.deleted.add("Java module information from the sources (module-info.java)" + mergingMsg);
626 continue entries;
627 }
628 if (entry.getName().startsWith("/")) { // absolute paths
629 // TODO does it really happen?
630 logger.log(WARNING, entry.getName() + " has an absolute path");
631 origin.deleted.add(entry.getName() + " from the sources" + mergingMsg);
632 continue entries;
633 }
634 Path target = sourceDir.resolve(entry.getName());
635 Files.createDirectories(target.getParent());
636 if (!Files.exists(target)) {
637 Files.copy(jarIn, target);
638 logger.log(TRACE, () -> "Copied source " + target);
639 } else {
640 logger.log(TRACE, () -> target + " already exists, skipping...");
641 }
642 }
643 }
644 // write the changes
645 if (sourceBundles) {
646 origin.appendChanges(sourceDir);
647 } else {
648 origin.added.add("source code under OSGI-OPT/src");
649 origin.appendChanges(bundleDir);
650 }
651 }
652
653 /** Download a Maven artifact. */
654 Path downloadMaven(URL url, M2Artifact artifact) throws IOException {
655 return downloadMaven(url, artifact, false);
656 }
657
658 /** Download a Maven artifact. */
659 Path downloadMaven(URL url, M2Artifact artifact, boolean sources) throws IOException {
660 return download(url, mavenBase, artifact.getGroupId().replace(".", "/") //
661 + '/' + artifact.getArtifactId() + '/' + artifact.getVersion() //
662 + '/' + artifact.getArtifactId() + "-" + artifact.getVersion() + (sources ? "-sources" : "") + ".jar");
663 }
664
665 /*
666 * ECLIPSE ORIGIN
667 */
668 /** Process an archive in Eclipse format. */
669 void processEclipseArchive(Path duDir) {
670 try {
671 Path categoryRelativePath = descriptorsBase.relativize(duDir.getParent());
672 Path targetCategoryBase = a2Base.resolve(categoryRelativePath);
673 Files.createDirectories(targetCategoryBase);
674 // first delete all directories from previous builds
675 for (Path dir : Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p)))
676 deleteDirectory(dir);
677
678 Files.createDirectories(originBase);
679
680 Path commonBnd = duDir.resolve(COMMON_BND);
681 Properties commonProps = new Properties();
682 try (InputStream in = Files.newInputStream(commonBnd)) {
683 commonProps.load(in);
684 }
685 String url = commonProps.getProperty(ARGEO_ORIGIN_URI.toString());
686 if (url == null) {
687 url = uris.getProperty(duDir.getFileName().toString());
688 if (url == null)
689 throw new IllegalStateException("No url available for " + duDir);
690 commonProps.put(ARGEO_ORIGIN_URI.toString(), url);
691 }
692 Path downloaded = tryDownloadArchive(url, originBase);
693
694 FileSystem zipFs = FileSystems.newFileSystem(downloaded, (ClassLoader) null);
695
696 // filters
697 List<PathMatcher> includeMatchers = new ArrayList<>();
698 Properties includes = new Properties();
699 try (InputStream in = Files.newInputStream(duDir.resolve("includes.properties"))) {
700 includes.load(in);
701 }
702 for (Object pattern : includes.keySet()) {
703 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
704 includeMatchers.add(pathMatcher);
705 }
706
707 List<PathMatcher> excludeMatchers = new ArrayList<>();
708 Path excludeFile = duDir.resolve("excludes.properties");
709 if (Files.exists(excludeFile)) {
710 Properties excludes = new Properties();
711 try (InputStream in = Files.newInputStream(excludeFile)) {
712 excludes.load(in);
713 }
714 for (Object pattern : excludes.keySet()) {
715 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
716 excludeMatchers.add(pathMatcher);
717 }
718 }
719
720 // keys are the bundle directories
721 Map<Path, A2Origin> origins = new HashMap<>();
722 Files.walkFileTree(zipFs.getRootDirectories().iterator().next(), new SimpleFileVisitor<Path>() {
723
724 @Override
725 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
726 includeMatchers: for (PathMatcher includeMatcher : includeMatchers) {
727 if (includeMatcher.matches(file)) {
728 for (PathMatcher excludeMatcher : excludeMatchers) {
729 if (excludeMatcher.matches(file)) {
730 logger.log(TRACE, "Skipping excluded " + file);
731 return FileVisitResult.CONTINUE;
732 }
733 }
734 if (file.getFileName().toString().contains(".source_")) {
735 processEclipseSourceJar(file, targetCategoryBase);
736 logger.log(DEBUG, () -> "Processed source " + file);
737 } else {
738 Map<String, String> map = new HashMap<>();
739 for (Object key : commonProps.keySet())
740 map.put(key.toString(), commonProps.getProperty(key.toString()));
741 A2Origin origin = new A2Origin();
742 Path bundleDir = processBundleJar(file, targetCategoryBase, map, origin);
743 origins.put(bundleDir, origin);
744 logger.log(DEBUG, () -> "Processed " + file);
745 }
746 break includeMatchers;
747 }
748 }
749 return FileVisitResult.CONTINUE;
750 }
751 });
752
753 DirectoryStream<Path> dirs = Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p)
754 && p.getFileName().toString().indexOf('.') >= 0 && !p.getFileName().toString().endsWith(".src"));
755 for (Path bundleDir : dirs) {
756 A2Origin origin = origins.get(bundleDir);
757 Objects.requireNonNull(origin, "No A2 origin found for " + bundleDir);
758 createJar(bundleDir, origin);
759 }
760 } catch (IOException e) {
761 throw new RuntimeException("Cannot process " + duDir, e);
762 }
763
764 }
765
766 /** Process sources in Eclipse format. */
767 void processEclipseSourceJar(Path file, Path targetBase) throws IOException {
768 try {
769 A2Origin origin = new A2Origin();
770 Path bundleDir;
771 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
772 Manifest manifest = jarIn.getManifest();
773
774 String[] relatedBundle = manifest.getMainAttributes().getValue(ECLIPSE_SOURCE_BUNDLE.toString())
775 .split(";");
776 String version = relatedBundle[1].substring("version=\"".length());
777 version = version.substring(0, version.length() - 1);
778 NameVersion nameVersion = new NameVersion(relatedBundle[0], version);
779 bundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
780
781 Path sourceDir = sourceBundles ? bundleDir.getParent().resolve(bundleDir.toString() + ".src")
782 : bundleDir.resolve("OSGI-OPT/src");
783
784 Files.createDirectories(sourceDir);
785 JarEntry entry;
786 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
787 if (entry.isDirectory())
788 continue entries;
789 if (entry.getName().startsWith("META-INF"))// skip META-INF entries
790 continue entries;
791 Path target = sourceDir.resolve(entry.getName());
792 Files.createDirectories(target.getParent());
793 Files.copy(jarIn, target);
794 logger.log(TRACE, () -> "Copied source " + target);
795 }
796
797 // write the changes
798 if (sourceBundles) {
799 origin.appendChanges(sourceDir);
800 } else {
801 origin.added.add("source code under OSGI-OPT/src");
802 origin.appendChanges(bundleDir);
803 }
804 }
805 } catch (IOException e) {
806 throw new IllegalStateException("Cannot process " + file, e);
807 }
808 }
809
810 /*
811 * COMMON PROCESSING
812 */
813 /** Normalise a bundle. */
814 Path processBundleJar(Path file, Path targetBase, Map<String, String> entries, A2Origin origin) throws IOException {
815 boolean embed = Boolean.parseBoolean(entries.getOrDefault(ARGEO_ORIGIN_EMBED.toString(), "false").toString());
816 NameVersion nameVersion;
817 Path bundleDir;
818 // singleton
819 boolean isSingleton = false;
820 Manifest manifest;
821 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
822 Manifest sourceManifest = jarIn.getManifest();
823 manifest = sourceManifest != null ? new Manifest(sourceManifest) : new Manifest();
824
825 String rawSourceSymbolicName = manifest.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME.toString());
826 if (rawSourceSymbolicName != null) {
827 // make sure there is no directive
828 String[] arr = rawSourceSymbolicName.split(";");
829 for (int i = 1; i < arr.length; i++) {
830 if (arr[i].trim().equals("singleton:=true"))
831 isSingleton = true;
832 logger.log(DEBUG, file.getFileName() + " is a singleton");
833 }
834 }
835 // remove problematic entries in MANIFEST
836 manifest.getEntries().clear();
837
838 String ourSymbolicName = entries.get(BUNDLE_SYMBOLICNAME.toString());
839 String ourVersion = entries.get(BUNDLE_VERSION.toString());
840
841 if (ourSymbolicName != null && ourVersion != null) {
842 nameVersion = new NameVersion(ourSymbolicName, ourVersion);
843 } else {
844 nameVersion = nameVersionFromManifest(manifest);
845 if (ourVersion != null && !nameVersion.getVersion().equals(ourVersion)) {
846 logger.log(WARNING,
847 "Original version is " + nameVersion.getVersion() + " while new version is " + ourVersion);
848 entries.put(BUNDLE_VERSION.toString(), ourVersion);
849 }
850 if (ourSymbolicName != null) {
851 // we always force our symbolic name
852 nameVersion.setName(ourSymbolicName);
853 }
854 }
855 bundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
856
857 if (sourceManifest != null) {// copy original MANIFEST
858 Path originalManifest = bundleDir.resolve(A2_ORIGIN).resolve("MANIFEST.MF");
859 Files.createDirectories(originalManifest.getParent());
860 try (OutputStream out = Files.newOutputStream(originalManifest)) {
861 sourceManifest.write(out);
862 }
863 origin.added.add("original MANIFEST (" + bundleDir.relativize(originalManifest) + ")");
864 }
865
866 // force Java 9 module name
867 entries.put(ManifestConstants.AUTOMATIC_MODULE_NAME.toString(), nameVersion.getName());
868
869 boolean isNative = false;
870 String os = null;
871 String arch = null;
872 if (bundleDir.startsWith(a2LibBase)) {
873 isNative = true;
874 Path libRelativePath = a2LibBase.relativize(bundleDir);
875 os = libRelativePath.getName(0).toString();
876 arch = libRelativePath.getName(1).toString();
877 }
878
879 if (!embed) {
880 // copy entries
881 JarEntry entry;
882 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
883 if (entry.isDirectory())
884 continue entries;
885 if (entry.getName().endsWith(".RSA") || entry.getName().endsWith(".SF")) {
886 origin.deleted.add("cryptographic signatures");
887 continue entries;
888 }
889 if (entry.getName().endsWith("module-info.class")) { // skip Java 9 module info
890 origin.deleted.add("Java module information (module-info.class)");
891 continue entries;
892 }
893 if (entry.getName().startsWith("META-INF/versions/")) { // skip multi-version
894 origin.deleted.add("additional Java versions (META-INF/versions)");
895 continue entries;
896 }
897 if (entry.getName().startsWith("META-INF/maven/")) {
898 origin.deleted.add("Maven information (META-INF/maven)");
899 continue entries;
900 }
901 // skip file system providers as they cause issues with native image
902 if (entry.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider")) {
903 origin.deleted
904 .add("file system providers (META-INF/services/java.nio.file.spi.FileSystemProvider)");
905 continue entries;
906 }
907 if (entry.getName().startsWith("OSGI-OPT/src/")) { // skip embedded sources
908 origin.deleted.add("embedded sources");
909 continue entries;
910 }
911 Path target = bundleDir.resolve(entry.getName());
912 Files.createDirectories(target.getParent());
913 Files.copy(jarIn, target);
914
915 // native libraries
916 if (isNative && (entry.getName().endsWith(".so") || entry.getName().endsWith(".dll")
917 || entry.getName().endsWith(".jnilib"))) {
918 Path categoryDir = bundleDir.getParent();
919 boolean copyDll = false;
920 Path targetDll = categoryDir.resolve(bundleDir.relativize(target));
921 if (nameVersion.getName().equals("com.sun.jna")) {
922 if (arch.equals("x86_64"))
923 arch = "x86-64";
924 if (os.equals("macosx"))
925 os = "darwin";
926 if (target.getParent().getFileName().toString().equals(os + "-" + arch)) {
927 copyDll = true;
928 }
929 targetDll = categoryDir.resolve(target.getFileName());
930 } else {
931 copyDll = true;
932 }
933 if (copyDll) {
934 Files.createDirectories(targetDll.getParent());
935 if (Files.exists(targetDll))
936 Files.delete(targetDll);
937 Files.copy(target, targetDll);
938 }
939 Files.delete(target);
940 origin.deleted.add(bundleDir.relativize(target).toString());
941 }
942 logger.log(TRACE, () -> "Copied " + target);
943 }
944 }
945 }
946
947 // copy MANIFEST
948 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
949 Files.createDirectories(manifestPath.getParent());
950
951 if (isSingleton && entries.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
952 entries.put(BUNDLE_SYMBOLICNAME.toString(),
953 entries.get(BUNDLE_SYMBOLICNAME.toString()) + ";singleton:=true");
954 }
955
956 if (embed) {// copy embedded jar
957 Files.copy(file, bundleDir.resolve(file.getFileName()));
958 entries.put(ManifestConstants.BUNDLE_CLASSPATH.toString(), file.getFileName().toString());
959 }
960
961 // Final MANIFEST decisions
962 // This also where we check the original OSGi metadata and compare with our
963 // changes
964 for (String key : entries.keySet()) {
965 String value = entries.get(key);
966 String previousValue = manifest.getMainAttributes().getValue(key);
967 boolean wasDifferent = previousValue != null && !previousValue.equals(value);
968 boolean keepPrevious = false;
969 if (wasDifferent) {
970 if (SPDX_LICENSE_IDENTIFIER.toString().equals(key) && previousValue != null)
971 keepPrevious = true;
972 else if (BUNDLE_VERSION.toString().equals(key) && wasDifferent)
973 if (previousValue.equals(value + ".0")) // typically a Maven first release
974 keepPrevious = true;
975
976 if (keepPrevious) {
977 if (logger.isLoggable(DEBUG))
978 logger.log(DEBUG, file.getFileName() + ": " + key + " was NOT modified, value kept is "
979 + previousValue + ", not overriden with " + value);
980 value = previousValue;
981 }
982 }
983
984 manifest.getMainAttributes().putValue(key, value);
985 if (wasDifferent && !keepPrevious) {
986 if (IMPORT_PACKAGE.toString().equals(key) || EXPORT_PACKAGE.toString().equals(key))
987 logger.log(TRACE, () -> file.getFileName() + ": " + key + " was modified");
988 else
989 logger.log(WARNING,
990 file.getFileName() + ": " + key + " was " + previousValue + ", overridden with " + value);
991 }
992
993 // de-pollute MANIFEST
994 switch (key) {
995 case "Archiver-Version":
996 case "Build-By":
997 case "Created-By":
998 case "Originally-Created-By":
999 case "Tool":
1000 case "Bnd-LastModified":
1001 manifest.getMainAttributes().remove(key);
1002 break;
1003 default: // do nothing
1004 }
1005
1006 // !! hack to remove unresolvable
1007 if (key.equals("Provide-Capability") || key.equals("Require-Capability"))
1008 if (nameVersion.getName().equals("osgi.core") || nameVersion.getName().equals("osgi.cmpn")) {
1009 manifest.getMainAttributes().remove(key);
1010 }
1011 }
1012
1013 // license checks
1014 String spdxLicenceId = manifest.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER.toString());
1015 String bundleLicense = manifest.getMainAttributes().getValue(BUNDLE_LICENSE.toString());
1016 if (spdxLicenceId == null) {
1017 logger.log(ERROR, file.getFileName() + ": " + SPDX_LICENSE_IDENTIFIER + " not available, " + BUNDLE_LICENSE
1018 + " is " + bundleLicense);
1019 } else {
1020 if (!licensesUsed.containsKey(spdxLicenceId))
1021 licensesUsed.put(spdxLicenceId, new TreeSet<>());
1022 licensesUsed.get(spdxLicenceId).add(nameVersion.toString());
1023 }
1024
1025 origin.modified.add("jar MANIFEST (META-INF/MANIFEST.MF)");
1026 // write the MANIFEST
1027 try (OutputStream out = Files.newOutputStream(manifestPath)) {
1028 manifest.write(out);
1029 }
1030 return bundleDir;
1031 }
1032
1033 /*
1034 * UTILITIES
1035 */
1036 /** Recursively deletes a directory. */
1037 static void deleteDirectory(Path path) throws IOException {
1038 if (!Files.exists(path))
1039 return;
1040 Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
1041 @Override
1042 public FileVisitResult postVisitDirectory(Path directory, IOException e) throws IOException {
1043 if (e != null)
1044 throw e;
1045 Files.delete(directory);
1046 return CONTINUE;
1047 }
1048
1049 @Override
1050 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1051 Files.delete(file);
1052 return CONTINUE;
1053 }
1054 });
1055 }
1056
1057 /** Extract name/version from a MANIFEST. */
1058 NameVersion nameVersionFromManifest(Manifest manifest) {
1059 Attributes attrs = manifest.getMainAttributes();
1060 // symbolic name
1061 String symbolicName = attrs.getValue(ManifestConstants.BUNDLE_SYMBOLICNAME.toString());
1062 if (symbolicName == null)
1063 return null;
1064 // make sure there is no directive
1065 symbolicName = symbolicName.split(";")[0];
1066
1067 String version = attrs.getValue(ManifestConstants.BUNDLE_VERSION.toString());
1068 return new NameVersion(symbolicName, version);
1069 }
1070
1071 /** Try to download from an URI. */
1072 Path tryDownloadArchive(String uri, Path dir) throws IOException {
1073 // find mirror
1074 List<String> urlBases = null;
1075 String uriPrefix = null;
1076 uriPrefixes: for (String uriPref : mirrors.keySet()) {
1077 if (uri.startsWith(uriPref)) {
1078 if (mirrors.get(uriPref).size() > 0) {
1079 urlBases = mirrors.get(uriPref);
1080 uriPrefix = uriPref;
1081 break uriPrefixes;
1082 }
1083 }
1084 }
1085 if (urlBases == null)
1086 try {
1087 return downloadArchive(new URL(uri), dir);
1088 } catch (FileNotFoundException e) {
1089 throw new FileNotFoundException("Cannot find " + uri);
1090 }
1091
1092 // try to download
1093 for (String urlBase : urlBases) {
1094 String relativePath = uri.substring(uriPrefix.length());
1095 URL url = new URL(urlBase + relativePath);
1096 try {
1097 return downloadArchive(url, dir);
1098 } catch (FileNotFoundException e) {
1099 logger.log(WARNING, "Cannot download " + url + ", trying another mirror");
1100 }
1101 }
1102 throw new FileNotFoundException("Cannot find " + uri);
1103 }
1104
1105 /**
1106 * Effectively download. Synchronised in order to avoid downloading twice in
1107 * parallel.
1108 */
1109 synchronized Path downloadArchive(URL url, Path dir) throws IOException {
1110 return download(url, dir, (String) null);
1111 }
1112
1113 /** Effectively download. */
1114 Path download(URL url, Path dir, String name) throws IOException {
1115
1116 Path dest;
1117 if (name == null) {
1118 // We use also use parent directory in case the archive itself has a fixed name
1119 String[] segments = url.getPath().split("/");
1120 name = segments.length > 1 ? segments[segments.length - 2] + '-' + segments[segments.length - 1]
1121 : segments[segments.length - 1];
1122 }
1123
1124 dest = dir.resolve(name);
1125 if (Files.exists(dest)) {
1126 logger.log(TRACE, () -> "File " + dest + " already exists for " + url + ", not downloading again");
1127 return dest;
1128 } else {
1129 Files.createDirectories(dest.getParent());
1130 }
1131
1132 try (InputStream in = url.openStream()) {
1133 Files.copy(in, dest);
1134 logger.log(DEBUG, () -> "Downloaded " + dest + " from " + url);
1135 }
1136 return dest;
1137 }
1138
1139 /** Create a JAR file from a directory. */
1140 Path createJar(Path bundleDir, A2Origin origin) throws IOException {
1141 // write changes
1142 origin.appendChanges(bundleDir);
1143 // Create the jar
1144 Path jarPath = bundleDir.getParent().resolve(bundleDir.getFileName() + ".jar");
1145 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
1146 Manifest manifest;
1147 try (InputStream in = Files.newInputStream(manifestPath)) {
1148 manifest = new Manifest(in);
1149 }
1150 try (JarOutputStream jarOut = new JarOutputStream(Files.newOutputStream(jarPath), manifest)) {
1151 jarOut.setLevel(Deflater.DEFAULT_COMPRESSION);
1152 Files.walkFileTree(bundleDir, new SimpleFileVisitor<Path>() {
1153
1154 @Override
1155 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1156 if (file.getFileName().toString().equals("MANIFEST.MF"))
1157 return super.visitFile(file, attrs);
1158 JarEntry entry = new JarEntry(
1159 bundleDir.relativize(file).toString().replace(File.separatorChar, '/'));
1160 jarOut.putNextEntry(entry);
1161 Files.copy(file, jarOut);
1162 return super.visitFile(file, attrs);
1163 }
1164
1165 });
1166 }
1167 deleteDirectory(bundleDir);
1168
1169 if (sourceBundles) {
1170 Path bundleCategoryDir = bundleDir.getParent();
1171 Path sourceDir = bundleCategoryDir.resolve(bundleDir.toString() + ".src");
1172 if (!Files.exists(sourceDir)) {
1173 logger.log(WARNING, sourceDir + " does not exist, skipping...");
1174 return jarPath;
1175
1176 }
1177
1178 Path relPath = a2Base.relativize(bundleCategoryDir);
1179 Path srcCategoryDir = a2SrcBase.resolve(relPath);
1180 Path srcJarP = srcCategoryDir.resolve(sourceDir.getFileName() + ".jar");
1181 Files.createDirectories(srcJarP.getParent());
1182
1183 String bundleSymbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1184 // in case there are additional directives
1185 bundleSymbolicName = bundleSymbolicName.split(";")[0];
1186 Manifest srcManifest = new Manifest();
1187 srcManifest.getMainAttributes().put(MANIFEST_VERSION, "1.0");
1188 srcManifest.getMainAttributes().putValue(BUNDLE_SYMBOLICNAME.toString(), bundleSymbolicName + ".src");
1189 srcManifest.getMainAttributes().putValue(BUNDLE_VERSION.toString(),
1190 manifest.getMainAttributes().getValue(BUNDLE_VERSION.toString()).toString());
1191 srcManifest.getMainAttributes().putValue(ECLIPSE_SOURCE_BUNDLE.toString(), bundleSymbolicName
1192 + ";version=\"" + manifest.getMainAttributes().getValue(BUNDLE_VERSION.toString()));
1193
1194 try (JarOutputStream srcJarOut = new JarOutputStream(Files.newOutputStream(srcJarP), srcManifest)) {
1195 srcJarOut.setLevel(Deflater.BEST_COMPRESSION);
1196 Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
1197
1198 @Override
1199 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1200 if (file.getFileName().toString().equals("MANIFEST.MF"))
1201 return super.visitFile(file, attrs);
1202 JarEntry entry = new JarEntry(
1203 sourceDir.relativize(file).toString().replace(File.separatorChar, '/'));
1204 srcJarOut.putNextEntry(entry);
1205 Files.copy(file, srcJarOut);
1206 return super.visitFile(file, attrs);
1207 }
1208
1209 });
1210 }
1211 deleteDirectory(sourceDir);
1212 }
1213
1214 return jarPath;
1215 }
1216
1217 /** MANIFEST headers. */
1218 enum ManifestConstants {
1219 // OSGi
1220 /** OSGi bundle symbolic name. */
1221 BUNDLE_SYMBOLICNAME("Bundle-SymbolicName"), //
1222 /** OSGi bundle version. */
1223 BUNDLE_VERSION("Bundle-Version"), //
1224 /** OSGi bundle license. */
1225 BUNDLE_LICENSE("Bundle-License"), //
1226 /** OSGi exported packages list. */
1227 EXPORT_PACKAGE("Export-Package"), //
1228 /** OSGi imported packages list. */
1229 IMPORT_PACKAGE("Import-Package"), //
1230 /** OSGi path to embedded jar. */
1231 BUNDLE_CLASSPATH("Bundle-Classpath"), //
1232 // Java
1233 /** Java module name. */
1234 AUTOMATIC_MODULE_NAME("Automatic-Module-Name"), //
1235 // Eclipse
1236 /** Eclipse source bundle. */
1237 ECLIPSE_SOURCE_BUNDLE("Eclipse-SourceBundle"), //
1238 // SPDX
1239 /**
1240 * SPDX license identifier.
1241 *
1242 * @see https://spdx.org/licenses/
1243 */
1244 SPDX_LICENSE_IDENTIFIER("SPDX-License-Identifier"), //
1245 // Argeo Origin
1246 /**
1247 * Maven coordinates of the origin, possibly partial when using common.bnd or
1248 * merge.bnd.
1249 */
1250 ARGEO_ORIGIN_M2("Argeo-Origin-M2"), //
1251 /** List of Maven coordinates to merge. */
1252 ARGEO_ORIGIN_M2_MERGE("Argeo-Origin-M2-Merge"), //
1253 /** Maven repository, if not the default one. */
1254 ARGEO_ORIGIN_M2_REPO("Argeo-Origin-M2-Repo"), //
1255 /**
1256 * Do not perform BND analysis of the origin component. Typically IMport_package
1257 * and Export-Package will be kept untouched.
1258 */
1259 ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED("Argeo-Origin-ManifestNotModified"), //
1260 /**
1261 * Embed the original jar without modifying it (may be required by some
1262 * proprietary licenses, such as JCR Day License).
1263 */
1264 ARGEO_ORIGIN_EMBED("Argeo-Origin-Embed"), //
1265 /**
1266 * Origin (non-Maven) URI of the component. It may be anything (jar, archive,
1267 * etc.).
1268 */
1269 ARGEO_ORIGIN_URI("Argeo-Origin-URI"), //
1270 ;
1271
1272 final String value;
1273
1274 private ManifestConstants(String value) {
1275 this.value = value;
1276 }
1277
1278 @Override
1279 public String toString() {
1280 return value;
1281 }
1282 }
1283 }
1284
1285 /**
1286 * Gathers modifications performed on the original binaries and sources,
1287 * especially in order to comply with their license requirements.
1288 */
1289 class A2Origin {
1290 Set<String> modified = new TreeSet<>();
1291 Set<String> deleted = new TreeSet<>();
1292 Set<String> added = new TreeSet<>();
1293 Set<String> moved = new TreeSet<>();
1294
1295 /** Append changes to the A2-ORIGIN/changes file. */
1296 void appendChanges(Path baseDirectory) throws IOException {
1297 Path changesFile = baseDirectory.resolve("A2-ORIGIN/changes");
1298 Files.createDirectories(changesFile.getParent());
1299 try (BufferedWriter writer = Files.newBufferedWriter(changesFile, StandardOpenOption.APPEND,
1300 StandardOpenOption.CREATE)) {
1301 for (String msg : added)
1302 writer.write("- Added " + msg + ".\n");
1303 for (String msg : modified)
1304 writer.write("- Modified " + msg + ".\n");
1305 for (String msg : moved)
1306 writer.write("- Moved " + msg + ".\n");
1307 for (String msg : deleted)
1308 writer.write("- Deleted " + msg + ".\n");
1309 }
1310 }
1311 }
1312
1313 /** Simple representation of an M2 artifact. */
1314 class M2Artifact extends CategoryNameVersion {
1315 private String classifier;
1316
1317 M2Artifact(String m2coordinates) {
1318 this(m2coordinates, null);
1319 }
1320
1321 M2Artifact(String m2coordinates, String classifier) {
1322 String[] parts = m2coordinates.split(":");
1323 setCategory(parts[0]);
1324 setName(parts[1]);
1325 if (parts.length > 2) {
1326 setVersion(parts[2]);
1327 }
1328 this.classifier = classifier;
1329 }
1330
1331 String getGroupId() {
1332 return super.getCategory();
1333 }
1334
1335 String getArtifactId() {
1336 return super.getName();
1337 }
1338
1339 String toM2Coordinates() {
1340 return getCategory() + ":" + getName() + (getVersion() != null ? ":" + getVersion() : "");
1341 }
1342
1343 String getClassifier() {
1344 return classifier != null ? classifier : "";
1345 }
1346
1347 String getExtension() {
1348 return "jar";
1349 }
1350 }
1351
1352 /** Utilities around Maven (conventions based). */
1353 class M2ConventionsUtils {
1354 final static String MAVEN_CENTRAL_BASE_URL = "https://repo1.maven.org/maven2/";
1355
1356 /** The file name of this artifact when stored */
1357 static String artifactFileName(M2Artifact artifact) {
1358 return artifact.getArtifactId() + '-' + artifact.getVersion()
1359 + (artifact.getClassifier().equals("") ? "" : '-' + artifact.getClassifier()) + '.'
1360 + artifact.getExtension();
1361 }
1362
1363 /** Absolute path to the file */
1364 static String artifactPath(String artifactBasePath, M2Artifact artifact) {
1365 return artifactParentPath(artifactBasePath, artifact) + '/' + artifactFileName(artifact);
1366 }
1367
1368 /** Absolute path to the file */
1369 static String artifactUrl(String repoUrl, M2Artifact artifact) {
1370 if (repoUrl.endsWith("/"))
1371 return repoUrl + artifactPath("/", artifact).substring(1);
1372 else
1373 return repoUrl + artifactPath("/", artifact);
1374 }
1375
1376 /** Absolute path to the file */
1377 static URL mavenRepoUrl(String repoBase, M2Artifact artifact) {
1378 String url = artifactUrl(repoBase == null ? MAVEN_CENTRAL_BASE_URL : repoBase, artifact);
1379 try {
1380 return new URL(url);
1381 } catch (MalformedURLException e) {
1382 // it should not happen
1383 throw new IllegalStateException(e);
1384 }
1385 }
1386
1387 /** Absolute path to the directories where the files will be stored */
1388 static String artifactParentPath(String artifactBasePath, M2Artifact artifact) {
1389 return artifactBasePath + (artifactBasePath.endsWith("/") ? "" : "/") + artifactParentPath(artifact);
1390 }
1391
1392 /** Relative path to the directories where the files will be stored */
1393 static String artifactParentPath(M2Artifact artifact) {
1394 return artifact.getGroupId().replace('.', '/') + '/' + artifact.getArtifactId() + '/' + artifact.getVersion();
1395 }
1396
1397 /** Singleton */
1398 private M2ConventionsUtils() {
1399 }
1400 }
1401
1402 /** Combination of a category, a name and a version. */
1403 class CategoryNameVersion extends NameVersion {
1404 private String category;
1405
1406 CategoryNameVersion() {
1407 }
1408
1409 CategoryNameVersion(String category, String name, String version) {
1410 super(name, version);
1411 this.category = category;
1412 }
1413
1414 CategoryNameVersion(String category, NameVersion nameVersion) {
1415 super(nameVersion);
1416 this.category = category;
1417 }
1418
1419 String getCategory() {
1420 return category;
1421 }
1422
1423 void setCategory(String category) {
1424 this.category = category;
1425 }
1426
1427 @Override
1428 public String toString() {
1429 return category + ":" + super.toString();
1430 }
1431
1432 }
1433
1434 /** Combination of a name and a version. */
1435 class NameVersion implements Comparable<NameVersion> {
1436 private String name;
1437 private String version;
1438
1439 NameVersion() {
1440 }
1441
1442 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1443 NameVersion(String nameVersion) {
1444 int index = nameVersion.indexOf(";version=");
1445 if (index < 0) {
1446 setName(nameVersion);
1447 setVersion(null);
1448 } else {
1449 setName(nameVersion.substring(0, index));
1450 setVersion(nameVersion.substring(index + ";version=".length()));
1451 }
1452 }
1453
1454 NameVersion(String name, String version) {
1455 this.name = name;
1456 this.version = version;
1457 }
1458
1459 NameVersion(NameVersion nameVersion) {
1460 this.name = nameVersion.getName();
1461 this.version = nameVersion.getVersion();
1462 }
1463
1464 String getName() {
1465 return name;
1466 }
1467
1468 void setName(String name) {
1469 this.name = name;
1470 }
1471
1472 String getVersion() {
1473 return version;
1474 }
1475
1476 void setVersion(String version) {
1477 this.version = version;
1478 }
1479
1480 String getBranch() {
1481 String[] parts = getVersion().split("\\.");
1482 if (parts.length < 2)
1483 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1484 return parts[0] + "." + parts[1];
1485 }
1486
1487 @Override
1488 public boolean equals(Object obj) {
1489 if (obj instanceof NameVersion) {
1490 NameVersion nameVersion = (NameVersion) obj;
1491 return name.equals(nameVersion.getName()) && version.equals(nameVersion.getVersion());
1492 } else
1493 return false;
1494 }
1495
1496 @Override
1497 public int hashCode() {
1498 return name.hashCode();
1499 }
1500
1501 @Override
1502 public String toString() {
1503 return name + ":" + version;
1504 }
1505
1506 public int compareTo(NameVersion o) {
1507 if (o.getName().equals(name))
1508 return version.compareTo(o.getVersion());
1509 else
1510 return name.compareTo(o.getName());
1511 }
1512 }