]> git.argeo.org Git - cc0/argeo-build.git/blob - src/org/argeo/build/Repackage.java
01a84cf4ce932d44b50be2c7e95523ea6a02383e
[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(".SF")) {
904 origin.deleted.add("cryptographic signatures");
905 continue entries;
906 }
907 if (entry.getName().endsWith("module-info.class")) { // skip Java 9 module info
908 origin.deleted.add("Java module information (module-info.class)");
909 continue entries;
910 }
911 if (entry.getName().startsWith("META-INF/versions/")) { // skip multi-version
912 origin.deleted.add("additional Java versions (META-INF/versions)");
913 continue entries;
914 }
915 if (entry.getName().startsWith("META-INF/maven/")) {
916 origin.deleted.add("Maven information (META-INF/maven)");
917 continue entries;
918 }
919 // skip file system providers as they cause issues with native image
920 if (entry.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider")) {
921 origin.deleted
922 .add("file system providers (META-INF/services/java.nio.file.spi.FileSystemProvider)");
923 continue entries;
924 }
925 if (entry.getName().startsWith("OSGI-OPT/src/")) { // skip embedded sources
926 origin.deleted.add("embedded sources");
927 continue entries;
928 }
929 Path target = bundleDir.resolve(entry.getName());
930 Files.createDirectories(target.getParent());
931 Files.copy(jarIn, target);
932
933 // native libraries
934 if (isNative && (entry.getName().endsWith(".so") || entry.getName().endsWith(".dll")
935 || entry.getName().endsWith(".jnilib"))) {
936 Path categoryDir = bundleDir.getParent();
937 boolean copyDll = false;
938 Path targetDll = categoryDir.resolve(bundleDir.relativize(target));
939 if (nameVersion.getName().equals("com.sun.jna")) {
940 if (arch.equals("x86_64"))
941 arch = "x86-64";
942 if (os.equals("macosx"))
943 os = "darwin";
944 if (target.getParent().getFileName().toString().equals(os + "-" + arch)) {
945 copyDll = true;
946 }
947 targetDll = categoryDir.resolve(target.getFileName());
948 } else {
949 copyDll = true;
950 }
951 if (copyDll) {
952 Files.createDirectories(targetDll.getParent());
953 if (Files.exists(targetDll))
954 Files.delete(targetDll);
955 Files.copy(target, targetDll);
956 }
957 Files.delete(target);
958 origin.deleted.add(bundleDir.relativize(target).toString());
959 }
960 logger.log(TRACE, () -> "Copied " + target);
961 }
962 }
963 }
964
965 // copy MANIFEST
966 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
967 Files.createDirectories(manifestPath.getParent());
968
969 if (isSingleton && entries.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
970 entries.put(BUNDLE_SYMBOLICNAME.toString(),
971 entries.get(BUNDLE_SYMBOLICNAME.toString()) + ";singleton:=true");
972 }
973
974 if (embed) {// copy embedded jar
975 Files.copy(file, bundleDir.resolve(file.getFileName()));
976 entries.put(ManifestConstants.BUNDLE_CLASSPATH.toString(), file.getFileName().toString());
977 }
978
979 // Final MANIFEST decisions
980 // This also where we check the original OSGi metadata and compare with our
981 // changes
982 for (String key : entries.keySet()) {
983 String value = entries.get(key);
984 String previousValue = manifest.getMainAttributes().getValue(key);
985 boolean wasDifferent = previousValue != null && !previousValue.equals(value);
986 boolean keepPrevious = false;
987 if (wasDifferent) {
988 if (SPDX_LICENSE_IDENTIFIER.toString().equals(key) && previousValue != null)
989 keepPrevious = true;
990 else if (BUNDLE_VERSION.toString().equals(key) && wasDifferent)
991 if (previousValue.equals(value + ".0")) // typically a Maven first release
992 keepPrevious = true;
993
994 if (keepPrevious) {
995 if (logger.isLoggable(DEBUG))
996 logger.log(DEBUG, file.getFileName() + ": " + key + " was NOT modified, value kept is "
997 + previousValue + ", not overriden with " + value);
998 value = previousValue;
999 }
1000 }
1001
1002 manifest.getMainAttributes().putValue(key, value);
1003 if (wasDifferent && !keepPrevious) {
1004 if (IMPORT_PACKAGE.toString().equals(key) || EXPORT_PACKAGE.toString().equals(key))
1005 logger.log(TRACE, () -> file.getFileName() + ": " + key + " was modified");
1006 else
1007 logger.log(WARNING,
1008 file.getFileName() + ": " + key + " was " + previousValue + ", overridden with " + value);
1009 }
1010
1011 // de-pollute MANIFEST
1012 switch (key) {
1013 case "Archiver-Version":
1014 case "Build-By":
1015 case "Created-By":
1016 case "Originally-Created-By":
1017 case "Tool":
1018 case "Bnd-LastModified":
1019 manifest.getMainAttributes().remove(key);
1020 break;
1021 default: // do nothing
1022 }
1023
1024 // !! hack to remove unresolvable
1025 if (key.equals("Provide-Capability") || key.equals("Require-Capability"))
1026 if (nameVersion.getName().equals("osgi.core") || nameVersion.getName().equals("osgi.cmpn")) {
1027 manifest.getMainAttributes().remove(key);
1028 }
1029 }
1030
1031 // license checks
1032 String spdxLicenceId = manifest.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER.toString());
1033 String bundleLicense = manifest.getMainAttributes().getValue(BUNDLE_LICENSE.toString());
1034 if (spdxLicenceId == null) {
1035 logger.log(ERROR, file.getFileName() + ": " + SPDX_LICENSE_IDENTIFIER + " not available, " + BUNDLE_LICENSE
1036 + " is " + bundleLicense);
1037 } else {
1038 if (!licensesUsed.containsKey(spdxLicenceId))
1039 licensesUsed.put(spdxLicenceId, new TreeSet<>());
1040 licensesUsed.get(spdxLicenceId).add(nameVersion.toString());
1041 }
1042
1043 origin.modified.add("jar MANIFEST (META-INF/MANIFEST.MF)");
1044 // write the MANIFEST
1045 try (OutputStream out = Files.newOutputStream(manifestPath)) {
1046 manifest.write(out);
1047 }
1048 return bundleDir;
1049 }
1050
1051 /*
1052 * UTILITIES
1053 */
1054 /** Recursively deletes a directory. */
1055 static void deleteDirectory(Path path) throws IOException {
1056 if (!Files.exists(path))
1057 return;
1058 Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
1059 @Override
1060 public FileVisitResult postVisitDirectory(Path directory, IOException e) throws IOException {
1061 if (e != null)
1062 throw e;
1063 Files.delete(directory);
1064 return CONTINUE;
1065 }
1066
1067 @Override
1068 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1069 Files.delete(file);
1070 return CONTINUE;
1071 }
1072 });
1073 }
1074
1075 /** Extract name/version from a MANIFEST. */
1076 NameVersion nameVersionFromManifest(Manifest manifest) {
1077 Attributes attrs = manifest.getMainAttributes();
1078 // symbolic name
1079 String symbolicName = attrs.getValue(ManifestConstants.BUNDLE_SYMBOLICNAME.toString());
1080 if (symbolicName == null)
1081 return null;
1082 // make sure there is no directive
1083 symbolicName = symbolicName.split(";")[0];
1084
1085 String version = attrs.getValue(ManifestConstants.BUNDLE_VERSION.toString());
1086 return new NameVersion(symbolicName, version);
1087 }
1088
1089 /** Try to download from an URI. */
1090 Path tryDownloadArchive(String uri, Path dir) throws IOException {
1091 // find mirror
1092 List<String> urlBases = null;
1093 String uriPrefix = null;
1094 uriPrefixes: for (String uriPref : mirrors.keySet()) {
1095 if (uri.startsWith(uriPref)) {
1096 if (mirrors.get(uriPref).size() > 0) {
1097 urlBases = mirrors.get(uriPref);
1098 uriPrefix = uriPref;
1099 break uriPrefixes;
1100 }
1101 }
1102 }
1103 if (urlBases == null)
1104 try {
1105 return downloadArchive(new URL(uri), dir);
1106 } catch (FileNotFoundException e) {
1107 throw new FileNotFoundException("Cannot find " + uri);
1108 }
1109
1110 // try to download
1111 for (String urlBase : urlBases) {
1112 String relativePath = uri.substring(uriPrefix.length());
1113 URL url = new URL(urlBase + relativePath);
1114 try {
1115 return downloadArchive(url, dir);
1116 } catch (FileNotFoundException e) {
1117 logger.log(WARNING, "Cannot download " + url + ", trying another mirror");
1118 }
1119 }
1120 throw new FileNotFoundException("Cannot find " + uri);
1121 }
1122
1123 /**
1124 * Effectively download. Synchronised in order to avoid downloading twice in
1125 * parallel.
1126 */
1127 synchronized Path downloadArchive(URL url, Path dir) throws IOException {
1128 return download(url, dir, (String) null);
1129 }
1130
1131 /** Effectively download. */
1132 Path download(URL url, Path dir, String name) throws IOException {
1133
1134 Path dest;
1135 if (name == null) {
1136 // We use also use parent directory in case the archive itself has a fixed name
1137 String[] segments = url.getPath().split("/");
1138 name = segments.length > 1 ? segments[segments.length - 2] + '-' + segments[segments.length - 1]
1139 : segments[segments.length - 1];
1140 }
1141
1142 dest = dir.resolve(name);
1143 if (Files.exists(dest)) {
1144 logger.log(TRACE, () -> "File " + dest + " already exists for " + url + ", not downloading again");
1145 return dest;
1146 } else {
1147 Files.createDirectories(dest.getParent());
1148 }
1149
1150 try (InputStream in = url.openStream()) {
1151 Files.copy(in, dest);
1152 logger.log(DEBUG, () -> "Downloaded " + dest + " from " + url);
1153 }
1154 return dest;
1155 }
1156
1157 /** Create a JAR file from a directory. */
1158 Path createJar(Path bundleDir, A2Origin origin) throws IOException {
1159 // write changes
1160 origin.appendChanges(bundleDir);
1161 // Create the jar
1162 Path jarPath = bundleDir.getParent().resolve(bundleDir.getFileName() + ".jar");
1163 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
1164 Manifest manifest;
1165 try (InputStream in = Files.newInputStream(manifestPath)) {
1166 manifest = new Manifest(in);
1167 }
1168 try (JarOutputStream jarOut = new JarOutputStream(Files.newOutputStream(jarPath), manifest)) {
1169 jarOut.setLevel(Deflater.DEFAULT_COMPRESSION);
1170 Files.walkFileTree(bundleDir, new SimpleFileVisitor<Path>() {
1171
1172 @Override
1173 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1174 if (file.getFileName().toString().equals("MANIFEST.MF"))
1175 return super.visitFile(file, attrs);
1176 JarEntry entry = new JarEntry(
1177 bundleDir.relativize(file).toString().replace(File.separatorChar, '/'));
1178 jarOut.putNextEntry(entry);
1179 Files.copy(file, jarOut);
1180 return super.visitFile(file, attrs);
1181 }
1182
1183 });
1184 }
1185 deleteDirectory(bundleDir);
1186
1187 if (sourceBundles)
1188 createSourceJar(bundleDir, manifest);
1189
1190 return jarPath;
1191 }
1192
1193 void createSourceJar(Path bundleDir, Manifest manifest) throws IOException {
1194 Path bundleCategoryDir = bundleDir.getParent();
1195 Path sourceDir = bundleCategoryDir.resolve(bundleDir.toString() + ".src");
1196 if (!Files.exists(sourceDir)) {
1197 logger.log(WARNING, sourceDir + " does not exist, skipping...");
1198 return;
1199
1200 }
1201
1202 Path relPath = a2Base.relativize(bundleCategoryDir);
1203 Path srcCategoryDir = a2SrcBase.resolve(relPath);
1204 Path srcJarP = srcCategoryDir.resolve(sourceDir.getFileName() + ".jar");
1205 Files.createDirectories(srcJarP.getParent());
1206
1207 String bundleSymbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1208 // in case there are additional directives
1209 bundleSymbolicName = bundleSymbolicName.split(";")[0];
1210 Manifest srcManifest = new Manifest();
1211 srcManifest.getMainAttributes().put(MANIFEST_VERSION, "1.0");
1212 srcManifest.getMainAttributes().putValue(BUNDLE_SYMBOLICNAME.toString(), bundleSymbolicName + ".src");
1213 srcManifest.getMainAttributes().putValue(BUNDLE_VERSION.toString(),
1214 manifest.getMainAttributes().getValue(BUNDLE_VERSION.toString()).toString());
1215 srcManifest.getMainAttributes().putValue(ECLIPSE_SOURCE_BUNDLE.toString(),
1216 bundleSymbolicName + ";version=\"" + manifest.getMainAttributes().getValue(BUNDLE_VERSION.toString()));
1217
1218 try (JarOutputStream srcJarOut = new JarOutputStream(Files.newOutputStream(srcJarP), srcManifest)) {
1219 srcJarOut.setLevel(Deflater.BEST_COMPRESSION);
1220 Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
1221
1222 @Override
1223 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1224 if (file.getFileName().toString().equals("MANIFEST.MF"))
1225 return super.visitFile(file, attrs);
1226 JarEntry entry = new JarEntry(
1227 sourceDir.relativize(file).toString().replace(File.separatorChar, '/'));
1228 srcJarOut.putNextEntry(entry);
1229 Files.copy(file, srcJarOut);
1230 return super.visitFile(file, attrs);
1231 }
1232
1233 });
1234 }
1235 deleteDirectory(sourceDir);
1236 }
1237
1238 /** MANIFEST headers. */
1239 enum ManifestConstants {
1240 // OSGi
1241 /** OSGi bundle symbolic name. */
1242 BUNDLE_SYMBOLICNAME("Bundle-SymbolicName"), //
1243 /** OSGi bundle version. */
1244 BUNDLE_VERSION("Bundle-Version"), //
1245 /** OSGi bundle license. */
1246 BUNDLE_LICENSE("Bundle-License"), //
1247 /** OSGi exported packages list. */
1248 EXPORT_PACKAGE("Export-Package"), //
1249 /** OSGi imported packages list. */
1250 IMPORT_PACKAGE("Import-Package"), //
1251 /** OSGi path to embedded jar. */
1252 BUNDLE_CLASSPATH("Bundle-Classpath"), //
1253 // Java
1254 /** Java module name. */
1255 AUTOMATIC_MODULE_NAME("Automatic-Module-Name"), //
1256 // Eclipse
1257 /** Eclipse source bundle. */
1258 ECLIPSE_SOURCE_BUNDLE("Eclipse-SourceBundle"), //
1259 // SPDX
1260 /**
1261 * SPDX license identifier.
1262 *
1263 * @see https://spdx.org/licenses/
1264 */
1265 SPDX_LICENSE_IDENTIFIER("SPDX-License-Identifier"), //
1266 // Argeo Origin
1267 /**
1268 * Maven coordinates of the origin, possibly partial when using common.bnd or
1269 * merge.bnd.
1270 */
1271 ARGEO_ORIGIN_M2("Argeo-Origin-M2"), //
1272 /** List of Maven coordinates to merge. */
1273 ARGEO_ORIGIN_M2_MERGE("Argeo-Origin-M2-Merge"), //
1274 /** Maven repository, if not the default one. */
1275 ARGEO_ORIGIN_M2_REPO("Argeo-Origin-M2-Repo"), //
1276 /**
1277 * Do not perform BND analysis of the origin component. Typically IMport_package
1278 * and Export-Package will be kept untouched.
1279 */
1280 ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED("Argeo-Origin-ManifestNotModified"), //
1281 /**
1282 * Embed the original jar without modifying it (may be required by some
1283 * proprietary licenses, such as JCR Day License).
1284 */
1285 ARGEO_ORIGIN_EMBED("Argeo-Origin-Embed"), //
1286 /**
1287 * Do not modify original jar (may be required by some proprietary licenses,
1288 * such as JCR Day License).
1289 */
1290 ARGEO_DO_NOT_MODIFY("Argeo-Origin-Do-Not-Modify"), //
1291 /**
1292 * Origin (non-Maven) URI of the component. It may be anything (jar, archive,
1293 * etc.).
1294 */
1295 ARGEO_ORIGIN_URI("Argeo-Origin-URI"), //
1296 ;
1297
1298 final String value;
1299
1300 private ManifestConstants(String value) {
1301 this.value = value;
1302 }
1303
1304 @Override
1305 public String toString() {
1306 return value;
1307 }
1308 }
1309 }
1310
1311 /**
1312 * Gathers modifications performed on the original binaries and sources,
1313 * especially in order to comply with their license requirements.
1314 */
1315 class A2Origin {
1316 Set<String> modified = new TreeSet<>();
1317 Set<String> deleted = new TreeSet<>();
1318 Set<String> added = new TreeSet<>();
1319 Set<String> moved = new TreeSet<>();
1320
1321 /** Append changes to the A2-ORIGIN/changes file. */
1322 void appendChanges(Path baseDirectory) throws IOException {
1323 Path changesFile = baseDirectory.resolve("A2-ORIGIN/changes");
1324 Files.createDirectories(changesFile.getParent());
1325 try (BufferedWriter writer = Files.newBufferedWriter(changesFile, StandardOpenOption.APPEND,
1326 StandardOpenOption.CREATE)) {
1327 for (String msg : added)
1328 writer.write("- Added " + msg + ".\n");
1329 for (String msg : modified)
1330 writer.write("- Modified " + msg + ".\n");
1331 for (String msg : moved)
1332 writer.write("- Moved " + msg + ".\n");
1333 for (String msg : deleted)
1334 writer.write("- Deleted " + msg + ".\n");
1335 }
1336 }
1337 }
1338
1339 /** Simple representation of an M2 artifact. */
1340 class M2Artifact extends CategoryNameVersion {
1341 private String classifier;
1342
1343 M2Artifact(String m2coordinates) {
1344 this(m2coordinates, null);
1345 }
1346
1347 M2Artifact(String m2coordinates, String classifier) {
1348 String[] parts = m2coordinates.split(":");
1349 setCategory(parts[0]);
1350 setName(parts[1]);
1351 if (parts.length > 2) {
1352 setVersion(parts[2]);
1353 }
1354 this.classifier = classifier;
1355 }
1356
1357 String getGroupId() {
1358 return super.getCategory();
1359 }
1360
1361 String getArtifactId() {
1362 return super.getName();
1363 }
1364
1365 String toM2Coordinates() {
1366 return getCategory() + ":" + getName() + (getVersion() != null ? ":" + getVersion() : "");
1367 }
1368
1369 String getClassifier() {
1370 return classifier != null ? classifier : "";
1371 }
1372
1373 String getExtension() {
1374 return "jar";
1375 }
1376 }
1377
1378 /** Utilities around Maven (conventions based). */
1379 class M2ConventionsUtils {
1380 final static String MAVEN_CENTRAL_BASE_URL = "https://repo1.maven.org/maven2/";
1381
1382 /** The file name of this artifact when stored */
1383 static String artifactFileName(M2Artifact artifact) {
1384 return artifact.getArtifactId() + '-' + artifact.getVersion()
1385 + (artifact.getClassifier().equals("") ? "" : '-' + artifact.getClassifier()) + '.'
1386 + artifact.getExtension();
1387 }
1388
1389 /** Absolute path to the file */
1390 static String artifactPath(String artifactBasePath, M2Artifact artifact) {
1391 return artifactParentPath(artifactBasePath, artifact) + '/' + artifactFileName(artifact);
1392 }
1393
1394 /** Absolute path to the file */
1395 static String artifactUrl(String repoUrl, M2Artifact artifact) {
1396 if (repoUrl.endsWith("/"))
1397 return repoUrl + artifactPath("/", artifact).substring(1);
1398 else
1399 return repoUrl + artifactPath("/", artifact);
1400 }
1401
1402 /** Absolute path to the file */
1403 static URL mavenRepoUrl(String repoBase, M2Artifact artifact) {
1404 String url = artifactUrl(repoBase == null ? MAVEN_CENTRAL_BASE_URL : repoBase, artifact);
1405 try {
1406 return new URL(url);
1407 } catch (MalformedURLException e) {
1408 // it should not happen
1409 throw new IllegalStateException(e);
1410 }
1411 }
1412
1413 /** Absolute path to the directories where the files will be stored */
1414 static String artifactParentPath(String artifactBasePath, M2Artifact artifact) {
1415 return artifactBasePath + (artifactBasePath.endsWith("/") ? "" : "/") + artifactParentPath(artifact);
1416 }
1417
1418 /** Relative path to the directories where the files will be stored */
1419 static String artifactParentPath(M2Artifact artifact) {
1420 return artifact.getGroupId().replace('.', '/') + '/' + artifact.getArtifactId() + '/' + artifact.getVersion();
1421 }
1422
1423 /** Singleton */
1424 private M2ConventionsUtils() {
1425 }
1426 }
1427
1428 /** Combination of a category, a name and a version. */
1429 class CategoryNameVersion extends NameVersion {
1430 private String category;
1431
1432 CategoryNameVersion() {
1433 }
1434
1435 CategoryNameVersion(String category, String name, String version) {
1436 super(name, version);
1437 this.category = category;
1438 }
1439
1440 CategoryNameVersion(String category, NameVersion nameVersion) {
1441 super(nameVersion);
1442 this.category = category;
1443 }
1444
1445 String getCategory() {
1446 return category;
1447 }
1448
1449 void setCategory(String category) {
1450 this.category = category;
1451 }
1452
1453 @Override
1454 public String toString() {
1455 return category + ":" + super.toString();
1456 }
1457
1458 }
1459
1460 /** Combination of a name and a version. */
1461 class NameVersion implements Comparable<NameVersion> {
1462 private String name;
1463 private String version;
1464
1465 NameVersion() {
1466 }
1467
1468 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1469 NameVersion(String nameVersion) {
1470 int index = nameVersion.indexOf(";version=");
1471 if (index < 0) {
1472 setName(nameVersion);
1473 setVersion(null);
1474 } else {
1475 setName(nameVersion.substring(0, index));
1476 setVersion(nameVersion.substring(index + ";version=".length()));
1477 }
1478 }
1479
1480 NameVersion(String name, String version) {
1481 this.name = name;
1482 this.version = version;
1483 }
1484
1485 NameVersion(NameVersion nameVersion) {
1486 this.name = nameVersion.getName();
1487 this.version = nameVersion.getVersion();
1488 }
1489
1490 String getName() {
1491 return name;
1492 }
1493
1494 void setName(String name) {
1495 this.name = name;
1496 }
1497
1498 String getVersion() {
1499 return version;
1500 }
1501
1502 void setVersion(String version) {
1503 this.version = version;
1504 }
1505
1506 String getBranch() {
1507 String[] parts = getVersion().split("\\.");
1508 if (parts.length < 2)
1509 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1510 return parts[0] + "." + parts[1];
1511 }
1512
1513 @Override
1514 public boolean equals(Object obj) {
1515 if (obj instanceof NameVersion) {
1516 NameVersion nameVersion = (NameVersion) obj;
1517 return name.equals(nameVersion.getName()) && version.equals(nameVersion.getVersion());
1518 } else
1519 return false;
1520 }
1521
1522 @Override
1523 public int hashCode() {
1524 return name.hashCode();
1525 }
1526
1527 @Override
1528 public String toString() {
1529 return name + ":" + version;
1530 }
1531
1532 public int compareTo(NameVersion o) {
1533 if (o.getName().equals(name))
1534 return version.compareTo(o.getVersion());
1535 else
1536 return name.compareTo(o.getName());
1537 }
1538 }