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