]> git.argeo.org Git - cc0/argeo-build.git/blob - src/org/argeo/build/Repackage.java
22c6ce135e2996e98a7140a7d5a8ddc425c7eb13
[cc0/argeo-build.git] / src / org / argeo / 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().equals("META-INF/DEPENDENCIES")) {
409 origin.deleted.add("dependency list (META-INF/DEPENDENCIES) from " + artifact);
410 continue entries;
411 }
412 if (entry.getName().startsWith("META-INF/maven/")) {
413 origin.deleted.add("Maven information (META-INF/maven) from " + artifact);
414 continue entries;
415 }
416 if (entry.getName().startsWith(".cache/")) { // Apache SSHD
417 origin.deleted.add("cache directory (.cache) from " + artifact);
418 continue entries;
419 }
420
421 if (entry.getName().endsWith("NOTICE") || entry.getName().endsWith("NOTICE.txt")
422 || entry.getName().endsWith("LICENSE") || entry.getName().endsWith("LICENSE.md")
423 || entry.getName().endsWith("LICENSE-notice.md") || entry.getName().endsWith("COPYING")
424 || entry.getName().endsWith("COPYING.LESSER")) {
425 Path artifactOriginDir = bundleDir.resolve(A2_ORIGIN).resolve(artifact.getGroupId())
426 .resolve(artifact.getArtifactId());
427 Path target = artifactOriginDir.resolve(entry.getName());
428 Files.createDirectories(target.getParent());
429 Files.copy(jarIn, target);
430 origin.moved.add(entry.getName() + " in " + artifact + " to " + bundleDir.relativize(target));
431 continue entries;
432 }
433 Path target = bundleDir.resolve(entry.getName());
434 Files.createDirectories(target.getParent());
435 if (!Files.exists(target)) {
436 Files.copy(jarIn, target);
437 } else {
438 if (entry.getName().startsWith("META-INF/services/")) {
439 try (OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND)) {
440 out.write("\n".getBytes());
441 jarIn.transferTo(out);
442 logger.log(DEBUG, artifact.getArtifactId() + " - Appended " + entry.getName());
443 }
444 origin.modified.add(entry.getName() + ", merging from " + artifact);
445 } else if (entry.getName().startsWith("org/apache/batik/")) {
446 logger.log(TRACE, "Skip " + entry.getName());
447 continue entries;
448 } else {
449 throw new IllegalStateException("File " + target + " from " + artifact + " already exists");
450 }
451 }
452 logger.log(TRACE, () -> "Copied " + target);
453 }
454 }
455 origin.added.add("binary content of " + artifact);
456
457 // process sources
458 downloadAndProcessM2Sources(repoStr, artifact, bundleDir, true);
459 }
460
461 // additional service files
462 Path servicesDir = duDir.resolve("services");
463 if (Files.exists(servicesDir)) {
464 for (Path p : Files.newDirectoryStream(servicesDir)) {
465 Path target = bundleDir.resolve("META-INF/services/").resolve(p.getFileName());
466 try (InputStream in = Files.newInputStream(p);
467 OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND);) {
468 out.write("\n".getBytes());
469 in.transferTo(out);
470 logger.log(DEBUG, "Appended " + p);
471 }
472 origin.added.add(bundleDir.relativize(target).toString());
473 }
474 }
475
476 Map<String, String> entries = new TreeMap<>();
477 try (Analyzer bndAnalyzer = new Analyzer()) {
478 bndAnalyzer.setProperties(mergeProps);
479 Jar jar = new Jar(bundleDir.toFile());
480 bndAnalyzer.setJar(jar);
481 Manifest manifest = bndAnalyzer.calcManifest();
482
483 keys: for (Object key : manifest.getMainAttributes().keySet()) {
484 Object value = manifest.getMainAttributes().get(key);
485
486 switch (key.toString()) {
487 case "Tool":
488 case "Bnd-LastModified":
489 case "Created-By":
490 continue keys;
491 }
492 if ("Require-Capability".equals(key.toString())
493 && value.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
494 continue keys;// hack for very old classes
495 entries.put(key.toString(), value.toString());
496 }
497 } catch (Exception e) {
498 throw new RuntimeException("Cannot process " + mergeBnd, e);
499 }
500
501 Manifest manifest = new Manifest();
502 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
503 Files.createDirectories(manifestPath.getParent());
504 for (String key : entries.keySet()) {
505 String value = entries.get(key);
506 manifest.getMainAttributes().putValue(key, value);
507 }
508
509 try (OutputStream out = Files.newOutputStream(manifestPath)) {
510 manifest.write(out);
511 }
512 createJar(bundleDir, origin);
513 }
514
515 /** Generate MANIFEST using BND. */
516 Path processBndJar(Path downloaded, Path targetCategoryBase, Properties fileProps, M2Artifact artifact,
517 A2Origin origin) {
518
519 try {
520 Map<String, String> additionalEntries = new TreeMap<>();
521 boolean doNotModify = Boolean.parseBoolean(
522 fileProps.getOrDefault(ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED.toString(), "false").toString());
523
524 // Note: we always force the symbolic name
525 if (doNotModify) {
526 fileEntries: for (Object key : fileProps.keySet()) {
527 if (ARGEO_ORIGIN_M2.toString().equals(key))
528 continue fileEntries;
529 String value = fileProps.getProperty(key.toString());
530 additionalEntries.put(key.toString(), value);
531 }
532 } else {
533 if (artifact != null) {
534 if (!fileProps.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
535 fileProps.put(BUNDLE_SYMBOLICNAME.toString(), artifact.getName());
536 }
537 if (!fileProps.containsKey(BUNDLE_VERSION.toString())) {
538 fileProps.put(BUNDLE_VERSION.toString(), artifact.getVersion());
539 }
540 }
541
542 if (!fileProps.containsKey(EXPORT_PACKAGE.toString())) {
543 fileProps.put(EXPORT_PACKAGE.toString(),
544 "*;version=\"" + fileProps.getProperty(BUNDLE_VERSION.toString()) + "\"");
545 }
546
547 try (Analyzer bndAnalyzer = new Analyzer()) {
548 bndAnalyzer.setProperties(fileProps);
549 Jar jar = new Jar(downloaded.toFile());
550 bndAnalyzer.setJar(jar);
551 Manifest manifest = bndAnalyzer.calcManifest();
552
553 keys: for (Object key : manifest.getMainAttributes().keySet()) {
554 Object value = manifest.getMainAttributes().get(key);
555
556 switch (key.toString()) {
557 case "Tool":
558 case "Bnd-LastModified":
559 case "Created-By":
560 continue keys;
561 }
562 if ("Require-Capability".equals(key.toString())
563 && value.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
564 continue keys;// !! hack for very old classes
565 additionalEntries.put(key.toString(), value.toString());
566 }
567 }
568 }
569 Path targetBundleDir = processBundleJar(downloaded, targetCategoryBase, additionalEntries, origin);
570 logger.log(DEBUG, () -> "Processed " + downloaded);
571 return targetBundleDir;
572 } catch (Exception e) {
573 throw new RuntimeException("Cannot BND process " + downloaded, e);
574 }
575
576 }
577
578 /** Download and integrates sources for a single Maven artifact. */
579 void downloadAndProcessM2Sources(String repoStr, M2Artifact artifact, Path targetBundleDir, boolean merging)
580 throws IOException {
581 try {
582 M2Artifact sourcesArtifact = new M2Artifact(artifact.toM2Coordinates(), "sources");
583 URL sourcesUrl = M2ConventionsUtils.mavenRepoUrl(repoStr, sourcesArtifact);
584 Path sourcesDownloaded = downloadMaven(sourcesUrl, artifact, true);
585 processM2SourceJar(sourcesDownloaded, targetBundleDir, merging ? artifact : null);
586 logger.log(TRACE, () -> "Processed source " + sourcesDownloaded);
587 } catch (Exception e) {
588 logger.log(ERROR, () -> "Cannot download source for " + artifact);
589 }
590
591 }
592
593 /** Integrate sources from a downloaded jar file. */
594 void processM2SourceJar(Path file, Path bundleDir, M2Artifact mergingFrom) throws IOException {
595 A2Origin origin = new A2Origin();
596 Path sourceDir = sourceBundles ? bundleDir.getParent().resolve(bundleDir.toString() + ".src")
597 : bundleDir.resolve("OSGI-OPT/src");
598 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
599
600 String mergingMsg = "";
601 if (mergingFrom != null)
602 mergingMsg = " of " + mergingFrom;
603
604 Files.createDirectories(sourceDir);
605 JarEntry entry;
606 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
607 if (entry.isDirectory())
608 continue entries;
609 if (entry.getName().startsWith("META-INF")) {// skip META-INF entries
610 origin.deleted.add("META-INF directory from the sources" + mergingMsg);
611 continue entries;
612 }
613 if (entry.getName().startsWith("module-info.java")) {// skip Java module information
614 origin.deleted.add("Java module information from the sources (module-info.java)" + mergingMsg);
615 continue entries;
616 }
617 if (entry.getName().startsWith("/")) { // absolute paths
618 // TODO does it really happen?
619 logger.log(WARNING, entry.getName() + " has an absolute path");
620 origin.deleted.add(entry.getName() + " from the sources" + mergingMsg);
621 continue entries;
622 }
623 Path target = sourceDir.resolve(entry.getName());
624 Files.createDirectories(target.getParent());
625 if (!Files.exists(target)) {
626 Files.copy(jarIn, target);
627 logger.log(TRACE, () -> "Copied source " + target);
628 } else {
629 logger.log(TRACE, () -> target + " already exists, skipping...");
630 }
631 }
632 }
633 // write the changes
634 if (sourceBundles) {
635 origin.appendChanges(sourceDir);
636 } else {
637 origin.added.add("source code under OSGI-OPT/src");
638 origin.appendChanges(bundleDir);
639 }
640 }
641
642 /** Download a Maven artifact. */
643 Path downloadMaven(URL url, M2Artifact artifact) throws IOException {
644 return downloadMaven(url, artifact, false);
645 }
646
647 /** Download a Maven artifact. */
648 Path downloadMaven(URL url, M2Artifact artifact, boolean sources) throws IOException {
649 return download(url, mavenBase, artifact.getGroupId().replace(".", "/") //
650 + '/' + artifact.getArtifactId() + '/' + artifact.getVersion() //
651 + '/' + artifact.getArtifactId() + "-" + artifact.getVersion() + (sources ? "-sources" : "") + ".jar");
652 }
653
654 /*
655 * ECLIPSE ORIGIN
656 */
657 /** Process an archive in Eclipse format. */
658 void processEclipseArchive(Path duDir) {
659 try {
660 Path categoryRelativePath = descriptorsBase.relativize(duDir.getParent());
661 Path targetCategoryBase = a2Base.resolve(categoryRelativePath);
662 Files.createDirectories(targetCategoryBase);
663 // first delete all directories from previous builds
664 for (Path dir : Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p)))
665 deleteDirectory(dir);
666
667 Files.createDirectories(originBase);
668
669 Path commonBnd = duDir.resolve(COMMON_BND);
670 Properties commonProps = new Properties();
671 try (InputStream in = Files.newInputStream(commonBnd)) {
672 commonProps.load(in);
673 }
674 String url = commonProps.getProperty(ARGEO_ORIGIN_URI.toString());
675 if (url == null) {
676 url = uris.getProperty(duDir.getFileName().toString());
677 if (url == null)
678 throw new IllegalStateException("No url available for " + duDir);
679 commonProps.put(ARGEO_ORIGIN_URI.toString(), url);
680 }
681 Path downloaded = tryDownloadArchive(url, originBase);
682
683 FileSystem zipFs = FileSystems.newFileSystem(downloaded, (ClassLoader) null);
684
685 // filters
686 List<PathMatcher> includeMatchers = new ArrayList<>();
687 Properties includes = new Properties();
688 try (InputStream in = Files.newInputStream(duDir.resolve("includes.properties"))) {
689 includes.load(in);
690 }
691 for (Object pattern : includes.keySet()) {
692 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
693 includeMatchers.add(pathMatcher);
694 }
695
696 List<PathMatcher> excludeMatchers = new ArrayList<>();
697 Path excludeFile = duDir.resolve("excludes.properties");
698 if (Files.exists(excludeFile)) {
699 Properties excludes = new Properties();
700 try (InputStream in = Files.newInputStream(excludeFile)) {
701 excludes.load(in);
702 }
703 for (Object pattern : excludes.keySet()) {
704 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
705 excludeMatchers.add(pathMatcher);
706 }
707 }
708
709 // keys are the bundle directories
710 Map<Path, A2Origin> origins = new HashMap<>();
711 Files.walkFileTree(zipFs.getRootDirectories().iterator().next(), new SimpleFileVisitor<Path>() {
712
713 @Override
714 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
715 includeMatchers: for (PathMatcher includeMatcher : includeMatchers) {
716 if (includeMatcher.matches(file)) {
717 for (PathMatcher excludeMatcher : excludeMatchers) {
718 if (excludeMatcher.matches(file)) {
719 logger.log(TRACE, "Skipping excluded " + file);
720 return FileVisitResult.CONTINUE;
721 }
722 }
723 if (file.getFileName().toString().contains(".source_")) {
724 processEclipseSourceJar(file, targetCategoryBase);
725 logger.log(DEBUG, () -> "Processed source " + file);
726 } else {
727 Map<String, String> map = new HashMap<>();
728 for (Object key : commonProps.keySet())
729 map.put(key.toString(), commonProps.getProperty(key.toString()));
730 A2Origin origin = new A2Origin();
731 Path bundleDir = processBundleJar(file, targetCategoryBase, map, origin);
732 origins.put(bundleDir, origin);
733 logger.log(DEBUG, () -> "Processed " + file);
734 }
735 break includeMatchers;
736 }
737 }
738 return FileVisitResult.CONTINUE;
739 }
740 });
741
742 DirectoryStream<Path> dirs = Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p)
743 && p.getFileName().toString().indexOf('.') >= 0 && !p.getFileName().toString().endsWith(".src"));
744 for (Path bundleDir : dirs) {
745 A2Origin origin = origins.get(bundleDir);
746 Objects.requireNonNull(origin, "No A2 origin found for " + bundleDir);
747 createJar(bundleDir, origin);
748 }
749 } catch (IOException e) {
750 throw new RuntimeException("Cannot process " + duDir, e);
751 }
752
753 }
754
755 /** Process sources in Eclipse format. */
756 void processEclipseSourceJar(Path file, Path targetBase) throws IOException {
757 try {
758 A2Origin origin = new A2Origin();
759 Path bundleDir;
760 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
761 Manifest manifest = jarIn.getManifest();
762
763 String[] relatedBundle = manifest.getMainAttributes().getValue(ECLIPSE_SOURCE_BUNDLE.toString())
764 .split(";");
765 String version = relatedBundle[1].substring("version=\"".length());
766 version = version.substring(0, version.length() - 1);
767 NameVersion nameVersion = new NameVersion(relatedBundle[0], version);
768 bundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
769
770 Path sourceDir = sourceBundles ? bundleDir.getParent().resolve(bundleDir.toString() + ".src")
771 : bundleDir.resolve("OSGI-OPT/src");
772
773 Files.createDirectories(sourceDir);
774 JarEntry entry;
775 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
776 if (entry.isDirectory())
777 continue entries;
778 if (entry.getName().startsWith("META-INF"))// skip META-INF entries
779 continue entries;
780 Path target = sourceDir.resolve(entry.getName());
781 Files.createDirectories(target.getParent());
782 Files.copy(jarIn, target);
783 logger.log(TRACE, () -> "Copied source " + target);
784 }
785
786 // write the changes
787 if (sourceBundles) {
788 origin.appendChanges(sourceDir);
789 } else {
790 origin.added.add("source code under OSGI-OPT/src");
791 origin.appendChanges(bundleDir);
792 }
793 }
794 } catch (IOException e) {
795 throw new IllegalStateException("Cannot process " + file, e);
796 }
797 }
798
799 /*
800 * COMMON PROCESSING
801 */
802 /** Normalise a bundle. */
803 Path processBundleJar(Path file, Path targetBase, Map<String, String> entries, A2Origin origin) throws IOException {
804 boolean embed = Boolean.parseBoolean(entries.getOrDefault(ARGEO_ORIGIN_EMBED.toString(), "false").toString());
805 NameVersion nameVersion;
806 Path bundleDir;
807 // singleton
808 boolean isSingleton = false;
809 Manifest manifest;
810 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
811 Manifest sourceManifest = jarIn.getManifest();
812 manifest = sourceManifest != null ? new Manifest(sourceManifest) : new Manifest();
813
814 String rawSourceSymbolicName = manifest.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME.toString());
815 if (rawSourceSymbolicName != null) {
816 // make sure there is no directive
817 String[] arr = rawSourceSymbolicName.split(";");
818 for (int i = 1; i < arr.length; i++) {
819 if (arr[i].trim().equals("singleton:=true"))
820 isSingleton = true;
821 logger.log(DEBUG, file.getFileName() + " is a singleton");
822 }
823 }
824 // remove problematic entries in MANIFEST
825 manifest.getEntries().clear();
826
827 String ourSymbolicName = entries.get(BUNDLE_SYMBOLICNAME.toString());
828 String ourVersion = entries.get(BUNDLE_VERSION.toString());
829
830 if (ourSymbolicName != null && ourVersion != null) {
831 nameVersion = new NameVersion(ourSymbolicName, ourVersion);
832 } else {
833 nameVersion = nameVersionFromManifest(manifest);
834 if (ourVersion != null && !nameVersion.getVersion().equals(ourVersion)) {
835 logger.log(WARNING,
836 "Original version is " + nameVersion.getVersion() + " while new version is " + ourVersion);
837 entries.put(BUNDLE_VERSION.toString(), ourVersion);
838 }
839 if (ourSymbolicName != null) {
840 // we always force our symbolic name
841 nameVersion.setName(ourSymbolicName);
842 }
843 }
844 bundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
845
846 if (sourceManifest != null) {
847 Path originalManifest = bundleDir.resolve(A2_ORIGIN).resolve("MANIFEST.MF");
848 try (OutputStream out = Files.newOutputStream(originalManifest)) {
849 sourceManifest.write(null);
850 }
851 origin.added.add("original MANIFEST (" + bundleDir.relativize(originalManifest) + ")");
852 }
853
854 // force Java 9 module name
855 entries.put(ManifestConstants.AUTOMATIC_MODULE_NAME.toString(), nameVersion.getName());
856
857 boolean isNative = false;
858 String os = null;
859 String arch = null;
860 if (bundleDir.startsWith(a2LibBase)) {
861 isNative = true;
862 Path libRelativePath = a2LibBase.relativize(bundleDir);
863 os = libRelativePath.getName(0).toString();
864 arch = libRelativePath.getName(1).toString();
865 }
866
867 if (!embed) {
868 // copy entries
869 JarEntry entry;
870 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
871 if (entry.isDirectory())
872 continue entries;
873 if (entry.getName().endsWith(".RSA") || entry.getName().endsWith(".SF")) {
874 origin.deleted.add("cryptographic signatures");
875 continue entries;
876 }
877 if (entry.getName().endsWith("module-info.class")) { // skip Java 9 module info
878 origin.deleted.add("Java module information (module-info.class)");
879 continue entries;
880 }
881 if (entry.getName().startsWith("META-INF/versions/")) { // skip multi-version
882 origin.deleted.add("additional Java versions (META-INF/versions)");
883 continue entries;
884 }
885 if (entry.getName().startsWith("META-INF/maven/")) {
886 origin.deleted.add("Maven information (META-INF/maven)");
887 continue entries;
888 }
889 // skip file system providers as they cause issues with native image
890 if (entry.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider")) {
891 origin.deleted
892 .add("file system providers (META-INF/services/java.nio.file.spi.FileSystemProvider)");
893 continue entries;
894 }
895 if (entry.getName().startsWith("OSGI-OPT/src/")) { // skip embedded sources
896 origin.deleted.add("embedded sources");
897 continue entries;
898 }
899 Path target = bundleDir.resolve(entry.getName());
900 Files.createDirectories(target.getParent());
901 Files.copy(jarIn, target);
902
903 // native libraries
904 if (isNative && (entry.getName().endsWith(".so") || entry.getName().endsWith(".dll")
905 || entry.getName().endsWith(".jnilib"))) {
906 Path categoryDir = bundleDir.getParent();
907 boolean copyDll = false;
908 Path targetDll = categoryDir.resolve(bundleDir.relativize(target));
909 if (nameVersion.getName().equals("com.sun.jna")) {
910 if (arch.equals("x86_64"))
911 arch = "x86-64";
912 if (os.equals("macosx"))
913 os = "darwin";
914 if (target.getParent().getFileName().toString().equals(os + "-" + arch)) {
915 copyDll = true;
916 }
917 targetDll = categoryDir.resolve(target.getFileName());
918 } else {
919 copyDll = true;
920 }
921 if (copyDll) {
922 Files.createDirectories(targetDll.getParent());
923 if (Files.exists(targetDll))
924 Files.delete(targetDll);
925 Files.copy(target, targetDll);
926 }
927 Files.delete(target);
928 origin.deleted.add(bundleDir.relativize(target).toString());
929 }
930 logger.log(TRACE, () -> "Copied " + target);
931 }
932 }
933 }
934
935 // copy MANIFEST
936 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
937 Files.createDirectories(manifestPath.getParent());
938
939 if (isSingleton && entries.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
940 entries.put(BUNDLE_SYMBOLICNAME.toString(),
941 entries.get(BUNDLE_SYMBOLICNAME.toString()) + ";singleton:=true");
942 }
943
944 if (embed) {// copy embedded jar
945 Files.copy(file, bundleDir.resolve(file.getFileName()));
946 entries.put(ManifestConstants.BUNDLE_CLASSPATH.toString(), file.getFileName().toString());
947 }
948
949 // Final MANIFEST decisions
950 // This also where we check the original OSGi metadata and compare with our
951 // changes
952 for (String key : entries.keySet()) {
953 String value = entries.get(key);
954 String previousValue = manifest.getMainAttributes().getValue(key);
955 boolean wasDifferent = previousValue != null && !previousValue.equals(value);
956 boolean keepPrevious = false;
957 if (wasDifferent) {
958 if (SPDX_LICENSE_IDENTIFIER.toString().equals(key) && previousValue != null)
959 keepPrevious = true;
960 else if (BUNDLE_VERSION.toString().equals(key) && wasDifferent)
961 if (previousValue.equals(value + ".0")) // typically a Maven first release
962 keepPrevious = true;
963
964 if (keepPrevious) {
965 if (logger.isLoggable(DEBUG))
966 logger.log(DEBUG, file.getFileName() + ": " + key + " was NOT modified, value kept is "
967 + previousValue + ", not overriden with " + value);
968 value = previousValue;
969 }
970 }
971
972 manifest.getMainAttributes().putValue(key, value);
973 if (wasDifferent && !keepPrevious) {
974 if (IMPORT_PACKAGE.toString().equals(key) || EXPORT_PACKAGE.toString().equals(key))
975 logger.log(TRACE, () -> file.getFileName() + ": " + key + " was modified");
976 else
977 logger.log(WARNING,
978 file.getFileName() + ": " + key + " was " + previousValue + ", overridden with " + value);
979 }
980
981 // de-pollute MANIFEST
982 switch (key) {
983 case "Archiver-Version":
984 case "Build-By":
985 case "Created-By":
986 case "Originally-Created-By":
987 case "Tool":
988 case "Bnd-LastModified":
989 manifest.getMainAttributes().remove(key);
990 break;
991 default: // do nothing
992 }
993
994 // !! hack to remove unresolvable
995 if (key.equals("Provide-Capability") || key.equals("Require-Capability"))
996 if (nameVersion.getName().equals("osgi.core") || nameVersion.getName().equals("osgi.cmpn")) {
997 manifest.getMainAttributes().remove(key);
998 }
999 }
1000
1001 // license checks
1002 String spdxLicenceId = manifest.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER.toString());
1003 String bundleLicense = manifest.getMainAttributes().getValue(BUNDLE_LICENSE.toString());
1004 if (spdxLicenceId == null) {
1005 logger.log(ERROR, file.getFileName() + ": " + SPDX_LICENSE_IDENTIFIER + " not available, " + BUNDLE_LICENSE
1006 + " is " + bundleLicense);
1007 } else {
1008 if (!licensesUsed.containsKey(spdxLicenceId))
1009 licensesUsed.put(spdxLicenceId, new TreeSet<>());
1010 licensesUsed.get(spdxLicenceId).add(nameVersion.toString());
1011 }
1012
1013 origin.modified.add("jar MANIFEST (META-INF/MANIFEST.MF)");
1014 // write the MANIFEST
1015 try (OutputStream out = Files.newOutputStream(manifestPath)) {
1016 manifest.write(out);
1017 }
1018 return bundleDir;
1019 }
1020
1021 /*
1022 * UTILITIES
1023 */
1024 /** Recursively deletes a directory. */
1025 static void deleteDirectory(Path path) throws IOException {
1026 if (!Files.exists(path))
1027 return;
1028 Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
1029 @Override
1030 public FileVisitResult postVisitDirectory(Path directory, IOException e) throws IOException {
1031 if (e != null)
1032 throw e;
1033 Files.delete(directory);
1034 return CONTINUE;
1035 }
1036
1037 @Override
1038 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1039 Files.delete(file);
1040 return CONTINUE;
1041 }
1042 });
1043 }
1044
1045 /** Extract name/version from a MANIFEST. */
1046 NameVersion nameVersionFromManifest(Manifest manifest) {
1047 Attributes attrs = manifest.getMainAttributes();
1048 // symbolic name
1049 String symbolicName = attrs.getValue(ManifestConstants.BUNDLE_SYMBOLICNAME.toString());
1050 if (symbolicName == null)
1051 return null;
1052 // make sure there is no directive
1053 symbolicName = symbolicName.split(";")[0];
1054
1055 String version = attrs.getValue(ManifestConstants.BUNDLE_VERSION.toString());
1056 return new NameVersion(symbolicName, version);
1057 }
1058
1059 /** Try to download from an URI. */
1060 Path tryDownloadArchive(String uri, Path dir) throws IOException {
1061 // find mirror
1062 List<String> urlBases = null;
1063 String uriPrefix = null;
1064 uriPrefixes: for (String uriPref : mirrors.keySet()) {
1065 if (uri.startsWith(uriPref)) {
1066 if (mirrors.get(uriPref).size() > 0) {
1067 urlBases = mirrors.get(uriPref);
1068 uriPrefix = uriPref;
1069 break uriPrefixes;
1070 }
1071 }
1072 }
1073 if (urlBases == null)
1074 try {
1075 return downloadArchive(new URL(uri), dir);
1076 } catch (FileNotFoundException e) {
1077 throw new FileNotFoundException("Cannot find " + uri);
1078 }
1079
1080 // try to download
1081 for (String urlBase : urlBases) {
1082 String relativePath = uri.substring(uriPrefix.length());
1083 URL url = new URL(urlBase + relativePath);
1084 try {
1085 return downloadArchive(url, dir);
1086 } catch (FileNotFoundException e) {
1087 logger.log(WARNING, "Cannot download " + url + ", trying another mirror");
1088 }
1089 }
1090 throw new FileNotFoundException("Cannot find " + uri);
1091 }
1092
1093 /**
1094 * Effectively download. Synchronised in order to avoid downloading twice in
1095 * parallel.
1096 */
1097 synchronized Path downloadArchive(URL url, Path dir) throws IOException {
1098 return download(url, dir, (String) null);
1099 }
1100
1101 /** Effectively download. */
1102 Path download(URL url, Path dir, String name) throws IOException {
1103
1104 Path dest;
1105 if (name == null) {
1106 // We use also use parent directory in case the archive itself has a fixed name
1107 String[] segments = url.getPath().split("/");
1108 name = segments.length > 1 ? segments[segments.length - 2] + '-' + segments[segments.length - 1]
1109 : segments[segments.length - 1];
1110 }
1111
1112 dest = dir.resolve(name);
1113 if (Files.exists(dest)) {
1114 logger.log(TRACE, () -> "File " + dest + " already exists for " + url + ", not downloading again");
1115 return dest;
1116 } else {
1117 Files.createDirectories(dest.getParent());
1118 }
1119
1120 try (InputStream in = url.openStream()) {
1121 Files.copy(in, dest);
1122 logger.log(DEBUG, () -> "Downloaded " + dest + " from " + url);
1123 }
1124 return dest;
1125 }
1126
1127 /** Create a JAR file from a directory. */
1128 Path createJar(Path bundleDir, A2Origin origin) throws IOException {
1129 // write changes
1130 origin.appendChanges(bundleDir);
1131 // Create the jar
1132 Path jarPath = bundleDir.getParent().resolve(bundleDir.getFileName() + ".jar");
1133 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
1134 Manifest manifest;
1135 try (InputStream in = Files.newInputStream(manifestPath)) {
1136 manifest = new Manifest(in);
1137 }
1138 try (JarOutputStream jarOut = new JarOutputStream(Files.newOutputStream(jarPath), manifest)) {
1139 jarOut.setLevel(Deflater.DEFAULT_COMPRESSION);
1140 Files.walkFileTree(bundleDir, new SimpleFileVisitor<Path>() {
1141
1142 @Override
1143 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1144 if (file.getFileName().toString().equals("MANIFEST.MF"))
1145 return super.visitFile(file, attrs);
1146 JarEntry entry = new JarEntry(
1147 bundleDir.relativize(file).toString().replace(File.separatorChar, '/'));
1148 jarOut.putNextEntry(entry);
1149 Files.copy(file, jarOut);
1150 return super.visitFile(file, attrs);
1151 }
1152
1153 });
1154 }
1155 deleteDirectory(bundleDir);
1156
1157 if (sourceBundles) {
1158 Path bundleCategoryDir = bundleDir.getParent();
1159 Path sourceDir = bundleCategoryDir.resolve(bundleDir.toString() + ".src");
1160 if (!Files.exists(sourceDir)) {
1161 logger.log(WARNING, sourceDir + " does not exist, skipping...");
1162 return jarPath;
1163
1164 }
1165
1166 Path relPath = a2Base.relativize(bundleCategoryDir);
1167 Path srcCategoryDir = a2SrcBase.resolve(relPath);
1168 Path srcJarP = srcCategoryDir.resolve(sourceDir.getFileName() + ".jar");
1169 Files.createDirectories(srcJarP.getParent());
1170
1171 String bundleSymbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1172 // in case there are additional directives
1173 bundleSymbolicName = bundleSymbolicName.split(";")[0];
1174 Manifest srcManifest = new Manifest();
1175 srcManifest.getMainAttributes().put(MANIFEST_VERSION, "1.0");
1176 srcManifest.getMainAttributes().putValue(BUNDLE_SYMBOLICNAME.toString(), bundleSymbolicName + ".src");
1177 srcManifest.getMainAttributes().putValue(BUNDLE_VERSION.toString(),
1178 manifest.getMainAttributes().getValue(BUNDLE_VERSION.toString()).toString());
1179 srcManifest.getMainAttributes().putValue(ECLIPSE_SOURCE_BUNDLE.toString(), bundleSymbolicName
1180 + ";version=\"" + manifest.getMainAttributes().getValue(BUNDLE_VERSION.toString()));
1181
1182 try (JarOutputStream srcJarOut = new JarOutputStream(Files.newOutputStream(srcJarP), srcManifest)) {
1183 srcJarOut.setLevel(Deflater.BEST_COMPRESSION);
1184 Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
1185
1186 @Override
1187 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1188 if (file.getFileName().toString().equals("MANIFEST.MF"))
1189 return super.visitFile(file, attrs);
1190 JarEntry entry = new JarEntry(
1191 sourceDir.relativize(file).toString().replace(File.separatorChar, '/'));
1192 srcJarOut.putNextEntry(entry);
1193 Files.copy(file, srcJarOut);
1194 return super.visitFile(file, attrs);
1195 }
1196
1197 });
1198 }
1199 deleteDirectory(sourceDir);
1200 }
1201
1202 return jarPath;
1203 }
1204
1205 /** MANIFEST headers. */
1206 enum ManifestConstants {
1207 // OSGi
1208 /** OSGi bundle symbolic name. */
1209 BUNDLE_SYMBOLICNAME("Bundle-SymbolicName"), //
1210 /** OSGi bundle version. */
1211 BUNDLE_VERSION("Bundle-Version"), //
1212 /** OSGi bundle license. */
1213 BUNDLE_LICENSE("Bundle-License"), //
1214 /** OSGi exported packages list. */
1215 EXPORT_PACKAGE("Export-Package"), //
1216 /** OSGi imported packages list. */
1217 IMPORT_PACKAGE("Import-Package"), //
1218 /** OSGi path to embedded jar. */
1219 BUNDLE_CLASSPATH("Bundle-Classpath"), //
1220 // Java
1221 /** Java module name. */
1222 AUTOMATIC_MODULE_NAME("Automatic-Module-Name"), //
1223 // Eclipse
1224 /** Eclipse source bundle. */
1225 ECLIPSE_SOURCE_BUNDLE("Eclipse-SourceBundle"), //
1226 // SPDX
1227 /**
1228 * SPDX license identifier.
1229 *
1230 * @see https://spdx.org/licenses/
1231 */
1232 SPDX_LICENSE_IDENTIFIER("SPDX-License-Identifier"), //
1233 // Argeo Origin
1234 /**
1235 * Maven coordinates of the origin, possibly partial when using common.bnd or
1236 * merge.bnd.
1237 */
1238 ARGEO_ORIGIN_M2("Argeo-Origin-M2"), //
1239 /** List of Maven coordinates to merge. */
1240 ARGEO_ORIGIN_M2_MERGE("Argeo-Origin-M2-Merge"), //
1241 /** Maven repository, if not the default one. */
1242 ARGEO_ORIGIN_M2_REPO("Argeo-Origin-M2-Repo"), //
1243 /**
1244 * Do not perform BND analysis of the origin component. Typically IMport_package
1245 * and Export-Package will be kept untouched.
1246 */
1247 ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED("Argeo-Origin-ManifestNotModified"), //
1248 /**
1249 * Embed the original jar without modifying it (may be required by some
1250 * proprietary licenses, such as JCR Day License).
1251 */
1252 ARGEO_ORIGIN_EMBED("Argeo-Origin-Embed"), //
1253 /**
1254 * Origin (non-Maven) URI of the component. It may be anything (jar, archive,
1255 * etc.).
1256 */
1257 ARGEO_ORIGIN_URI("Argeo-Origin-URI"), //
1258 ;
1259
1260 final String value;
1261
1262 private ManifestConstants(String value) {
1263 this.value = value;
1264 }
1265
1266 @Override
1267 public String toString() {
1268 return value;
1269 }
1270 }
1271 }
1272
1273 /**
1274 * Gathers modifications performed on the original binaries and sources,
1275 * especially in order to comply with their license requirements.
1276 */
1277 class A2Origin {
1278 Set<String> modified = new TreeSet<>();
1279 Set<String> deleted = new TreeSet<>();
1280 Set<String> added = new TreeSet<>();
1281 Set<String> moved = new TreeSet<>();
1282
1283 /** Append changes to the A2-ORIGIN/changes file. */
1284 void appendChanges(Path baseDirectory) throws IOException {
1285 Path changesFile = baseDirectory.resolve("A2-ORIGIN/changes");
1286 Files.createDirectories(changesFile.getParent());
1287 try (BufferedWriter writer = Files.newBufferedWriter(changesFile, StandardOpenOption.APPEND,
1288 StandardOpenOption.CREATE)) {
1289 for (String msg : added)
1290 writer.write("- Added " + msg + ".\n");
1291 for (String msg : modified)
1292 writer.write("- Modified " + msg + ".\n");
1293 for (String msg : moved)
1294 writer.write("- Moved " + msg + ".\n");
1295 for (String msg : deleted)
1296 writer.write("- Deleted " + msg + ".\n");
1297 }
1298 }
1299 }
1300
1301 /** Simple representation of an M2 artifact. */
1302 class M2Artifact extends CategoryNameVersion {
1303 private String classifier;
1304
1305 M2Artifact(String m2coordinates) {
1306 this(m2coordinates, null);
1307 }
1308
1309 M2Artifact(String m2coordinates, String classifier) {
1310 String[] parts = m2coordinates.split(":");
1311 setCategory(parts[0]);
1312 setName(parts[1]);
1313 if (parts.length > 2) {
1314 setVersion(parts[2]);
1315 }
1316 this.classifier = classifier;
1317 }
1318
1319 String getGroupId() {
1320 return super.getCategory();
1321 }
1322
1323 String getArtifactId() {
1324 return super.getName();
1325 }
1326
1327 String toM2Coordinates() {
1328 return getCategory() + ":" + getName() + (getVersion() != null ? ":" + getVersion() : "");
1329 }
1330
1331 String getClassifier() {
1332 return classifier != null ? classifier : "";
1333 }
1334
1335 String getExtension() {
1336 return "jar";
1337 }
1338 }
1339
1340 /** Utilities around Maven (conventions based). */
1341 class M2ConventionsUtils {
1342 final static String MAVEN_CENTRAL_BASE_URL = "https://repo1.maven.org/maven2/";
1343
1344 /** The file name of this artifact when stored */
1345 static String artifactFileName(M2Artifact artifact) {
1346 return artifact.getArtifactId() + '-' + artifact.getVersion()
1347 + (artifact.getClassifier().equals("") ? "" : '-' + artifact.getClassifier()) + '.'
1348 + artifact.getExtension();
1349 }
1350
1351 /** Absolute path to the file */
1352 static String artifactPath(String artifactBasePath, M2Artifact artifact) {
1353 return artifactParentPath(artifactBasePath, artifact) + '/' + artifactFileName(artifact);
1354 }
1355
1356 /** Absolute path to the file */
1357 static String artifactUrl(String repoUrl, M2Artifact artifact) {
1358 if (repoUrl.endsWith("/"))
1359 return repoUrl + artifactPath("/", artifact).substring(1);
1360 else
1361 return repoUrl + artifactPath("/", artifact);
1362 }
1363
1364 /** Absolute path to the file */
1365 static URL mavenRepoUrl(String repoBase, M2Artifact artifact) {
1366 String url = artifactUrl(repoBase == null ? MAVEN_CENTRAL_BASE_URL : repoBase, artifact);
1367 try {
1368 return new URL(url);
1369 } catch (MalformedURLException e) {
1370 // it should not happen
1371 throw new IllegalStateException(e);
1372 }
1373 }
1374
1375 /** Absolute path to the directories where the files will be stored */
1376 static String artifactParentPath(String artifactBasePath, M2Artifact artifact) {
1377 return artifactBasePath + (artifactBasePath.endsWith("/") ? "" : "/") + artifactParentPath(artifact);
1378 }
1379
1380 /** Relative path to the directories where the files will be stored */
1381 static String artifactParentPath(M2Artifact artifact) {
1382 return artifact.getGroupId().replace('.', '/') + '/' + artifact.getArtifactId() + '/' + artifact.getVersion();
1383 }
1384
1385 /** Singleton */
1386 private M2ConventionsUtils() {
1387 }
1388 }
1389
1390 /** Combination of a category, a name and a version. */
1391 class CategoryNameVersion extends NameVersion {
1392 private String category;
1393
1394 CategoryNameVersion() {
1395 }
1396
1397 CategoryNameVersion(String category, String name, String version) {
1398 super(name, version);
1399 this.category = category;
1400 }
1401
1402 CategoryNameVersion(String category, NameVersion nameVersion) {
1403 super(nameVersion);
1404 this.category = category;
1405 }
1406
1407 String getCategory() {
1408 return category;
1409 }
1410
1411 void setCategory(String category) {
1412 this.category = category;
1413 }
1414
1415 @Override
1416 public String toString() {
1417 return category + ":" + super.toString();
1418 }
1419
1420 }
1421
1422 /** Combination of a name and a version. */
1423 class NameVersion implements Comparable<NameVersion> {
1424 private String name;
1425 private String version;
1426
1427 NameVersion() {
1428 }
1429
1430 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1431 NameVersion(String nameVersion) {
1432 int index = nameVersion.indexOf(";version=");
1433 if (index < 0) {
1434 setName(nameVersion);
1435 setVersion(null);
1436 } else {
1437 setName(nameVersion.substring(0, index));
1438 setVersion(nameVersion.substring(index + ";version=".length()));
1439 }
1440 }
1441
1442 NameVersion(String name, String version) {
1443 this.name = name;
1444 this.version = version;
1445 }
1446
1447 NameVersion(NameVersion nameVersion) {
1448 this.name = nameVersion.getName();
1449 this.version = nameVersion.getVersion();
1450 }
1451
1452 String getName() {
1453 return name;
1454 }
1455
1456 void setName(String name) {
1457 this.name = name;
1458 }
1459
1460 String getVersion() {
1461 return version;
1462 }
1463
1464 void setVersion(String version) {
1465 this.version = version;
1466 }
1467
1468 String getBranch() {
1469 String[] parts = getVersion().split("\\.");
1470 if (parts.length < 2)
1471 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1472 return parts[0] + "." + parts[1];
1473 }
1474
1475 @Override
1476 public boolean equals(Object obj) {
1477 if (obj instanceof NameVersion) {
1478 NameVersion nameVersion = (NameVersion) obj;
1479 return name.equals(nameVersion.getName()) && version.equals(nameVersion.getVersion());
1480 } else
1481 return false;
1482 }
1483
1484 @Override
1485 public int hashCode() {
1486 return name.hashCode();
1487 }
1488
1489 @Override
1490 public String toString() {
1491 return name + ":" + version;
1492 }
1493
1494 public int compareTo(NameVersion o) {
1495 if (o.getName().equals(name))
1496 return version.compareTo(o.getVersion());
1497 else
1498 return name.compareTo(o.getName());
1499 }
1500 }