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