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