]> git.argeo.org Git - cc0/argeo-build.git/blob - Repackage.java
a6c84edd81f627e86410707cfbf81b364078dcdf
[cc0/argeo-build.git] / 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 {
588 throw new IllegalStateException("File " + target + " from " + artifact + " already exists");
589 }
590 }
591 logger.log(TRACE, () -> "Copied " + target);
592 }
593 }
594 origin.added.add("binary content of " + artifact);
595
596 // process sources
597 downloadAndProcessM2Sources(mergeProps, artifact, bundleDir, true, false);
598 }
599
600 // additional service files
601 Path servicesDir = duDir.resolve("services");
602 if (Files.exists(servicesDir)) {
603 for (Path p : Files.newDirectoryStream(servicesDir)) {
604 Path target = bundleDir.resolve("META-INF/services/").resolve(p.getFileName());
605 try (InputStream in = Files.newInputStream(p);
606 OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND);) {
607 out.write("\n".getBytes());
608 in.transferTo(out);
609 logger.log(DEBUG, "Appended " + p);
610 }
611 origin.added.add(bundleDir.relativize(target).toString());
612 }
613 }
614
615 // BND analysis
616 Map<String, String> entries = new TreeMap<>();
617 try (Analyzer bndAnalyzer = new Analyzer()) {
618 bndAnalyzer.setProperties(mergeProps);
619 Jar jar = new Jar(bundleDir.toFile());
620 bndAnalyzer.setJar(jar);
621 Manifest manifest = bndAnalyzer.calcManifest();
622
623 keys: for (Object key : manifest.getMainAttributes().keySet()) {
624 Object value = manifest.getMainAttributes().get(key);
625
626 switch (key.toString()) {
627 case "Tool":
628 case "Bnd-LastModified":
629 case "Created-By":
630 continue keys;
631 }
632 if ("Require-Capability".equals(key.toString())
633 && value.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\"")) {
634 origin.deleted.add("MANIFEST header " + key);
635 continue keys;// hack for very old classes
636 }
637 entries.put(key.toString(), value.toString());
638 }
639 } catch (Exception e) {
640 throw new RuntimeException("Cannot process " + mergeBnd, e);
641 }
642
643 Manifest manifest = new Manifest();
644 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
645 Files.createDirectories(manifestPath.getParent());
646 for (String key : entries.keySet()) {
647 String value = entries.get(key);
648 manifest.getMainAttributes().putValue(key, value);
649 }
650 manifest.getMainAttributes().putValue(ARGEO_ORIGIN_M2.toString(), originDesc.toString());
651
652 processLicense(bundleDir, manifest);
653
654 // write MANIFEST
655 try (OutputStream out = Files.newOutputStream(manifestPath)) {
656 manifest.write(out);
657 }
658 createJar(bundleDir, origin);
659 }
660
661 /** Generates MANIFEST using BND. */
662 Path processBndJar(Path downloaded, Path targetCategoryBase, Properties fileProps, M2Artifact artifact,
663 A2Origin origin) {
664 try {
665 Map<String, String> additionalEntries = new TreeMap<>();
666 boolean doNotModifyManifest = Boolean.parseBoolean(
667 fileProps.getOrDefault(ARGEO_ORIGIN_NO_METADATA_GENERATION.toString(), "false").toString());
668
669 // Note: we always force the symbolic name
670 if (doNotModifyManifest) {
671 for (Object key : fileProps.keySet()) {
672 String value = fileProps.getProperty(key.toString());
673 additionalEntries.put(key.toString(), value);
674 }
675 } else {
676 if (artifact != null) {
677 if (!fileProps.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
678 fileProps.put(BUNDLE_SYMBOLICNAME.toString(), artifact.getName());
679 }
680 if (!fileProps.containsKey(BUNDLE_VERSION.toString())) {
681 fileProps.put(BUNDLE_VERSION.toString(), artifact.getVersion());
682 }
683 }
684
685 if (!fileProps.containsKey(EXPORT_PACKAGE.toString())) {
686 fileProps.put(EXPORT_PACKAGE.toString(),
687 "*;version=\"" + fileProps.getProperty(BUNDLE_VERSION.toString()) + "\"");
688 }
689
690 // BND analysis
691 try (Analyzer bndAnalyzer = new Analyzer()) {
692 bndAnalyzer.setProperties(fileProps);
693 Jar jar = new Jar(downloaded.toFile());
694 bndAnalyzer.setJar(jar);
695 Manifest manifest = bndAnalyzer.calcManifest();
696
697 keys: for (Object key : manifest.getMainAttributes().keySet()) {
698 Object value = manifest.getMainAttributes().get(key);
699
700 switch (key.toString()) {
701 case "Tool":
702 case "Bnd-LastModified":
703 case "Created-By":
704 continue keys;
705 }
706 if ("Require-Capability".equals(key.toString())
707 && value.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\"")) {
708 origin.deleted.add("MANIFEST header " + key);
709 continue keys;// !! hack for very old classes
710 }
711 additionalEntries.put(key.toString(), value.toString());
712 }
713 }
714 }
715 Path targetBundleDir = processBundleJar(downloaded, targetCategoryBase, additionalEntries, origin);
716 logger.log(DEBUG, () -> "Processed " + downloaded);
717 return targetBundleDir;
718 } catch (Exception e) {
719 throw new RuntimeException("Cannot BND process " + downloaded, e);
720 }
721
722 }
723
724 /** Process an artifact that should not be modified. */
725 void processNotModified(Path targetCategoryBase, Path downloaded, Properties fileProps, M2Artifact artifact)
726 throws IOException {
727 // Some proprietary or signed artifacts do not allow any modification
728 // When releasing (with separate sources), we just copy it
729 Path unmodifiedTarget = targetCategoryBase
730 .resolve(fileProps.getProperty(BUNDLE_SYMBOLICNAME.toString()) + "." + artifact.getBranch() + ".jar");
731 Files.createDirectories(unmodifiedTarget.getParent());
732 Files.copy(downloaded, unmodifiedTarget, StandardCopyOption.REPLACE_EXISTING);
733 Path bundleDir = targetCategoryBase
734 .resolve(fileProps.getProperty(BUNDLE_SYMBOLICNAME.toString()) + "." + artifact.getBranch());
735 downloadAndProcessM2Sources(fileProps, artifact, bundleDir, false, true);
736 Manifest manifest;
737 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(unmodifiedTarget))) {
738 manifest = jarIn.getManifest();
739 }
740 createSourceJar(bundleDir, manifest, fileProps);
741 }
742
743 /** Download and integrates sources for a single Maven artifact. */
744 void downloadAndProcessM2Sources(Properties props, M2Artifact artifact, Path targetBundleDir, boolean merging,
745 boolean unmodified) throws IOException {
746 try {
747 String repoStr = props.containsKey(ARGEO_ORIGIN_M2_REPO.toString())
748 ? props.getProperty(ARGEO_ORIGIN_M2_REPO.toString())
749 : null;
750 String alternateUri = props.getProperty(ARGEO_ORIGIN_SOURCES_URI.toString());
751 M2Artifact sourcesArtifact = new M2Artifact(artifact.toM2Coordinates(), "sources");
752 URL sourcesUrl = alternateUri != null ? new URL(alternateUri)
753 : M2ConventionsUtils.mavenRepoUrl(repoStr, sourcesArtifact);
754 Path sourcesDownloaded = downloadMaven(sourcesUrl, sourcesArtifact);
755 processM2SourceJar(sourcesDownloaded, targetBundleDir, merging ? artifact : null, unmodified);
756 logger.log(TRACE, () -> "Processed source " + sourcesDownloaded);
757 } catch (Exception e) {
758 logger.log(ERROR, () -> "Cannot download source for " + artifact);
759 }
760
761 }
762
763 /** Integrate sources from a downloaded jar file. */
764 void processM2SourceJar(Path file, Path bundleDir, M2Artifact mergingFrom, boolean unmodified) throws IOException {
765 A2Origin origin = new A2Origin();
766 Path sourceDir = separateSources || unmodified ? bundleDir.getParent().resolve(bundleDir.toString() + ".src")
767 : bundleDir.resolve("OSGI-OPT/src");
768 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
769
770 String mergingMsg = "";
771 if (mergingFrom != null)
772 mergingMsg = " of " + mergingFrom;
773
774 Files.createDirectories(sourceDir);
775 JarEntry entry;
776 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
777 String relPath = entry.getName();
778 if (entry.isDirectory())
779 continue entries;
780 if (entry.getName().equals("META-INF/MANIFEST.MF")) {// skip META-INF entries
781 origin.deleted.add("MANIFEST.MF from the sources" + mergingMsg);
782 continue entries;
783 }
784 if (!unmodified) {
785 if (entry.getName().startsWith("module-info.java")) {// skip Java module information
786 origin.deleted.add("Java module information from the sources (module-info.java)" + mergingMsg);
787 continue entries;
788 }
789 if (entry.getName().startsWith("/")) { // absolute paths
790 int metaInfIndex = entry.getName().indexOf("META-INF");
791 if (metaInfIndex >= 0) {
792 relPath = entry.getName().substring(metaInfIndex);
793 origin.moved.add(" to " + relPath + " entry with absolute path " + entry.getName());
794 } else {
795 logger.log(WARNING, entry.getName() + " has an absolute path");
796 origin.deleted.add(entry.getName() + " from the sources" + mergingMsg);
797 }
798 continue entries;
799 }
800 }
801 Path target = sourceDir.resolve(relPath);
802 Files.createDirectories(target.getParent());
803 if (!Files.exists(target)) {
804 Files.copy(jarIn, target);
805 logger.log(TRACE, () -> "Copied source " + target);
806 } else {
807 logger.log(TRACE, () -> target + " already exists, skipping...");
808 }
809 }
810 }
811 // write the changes
812 if (separateSources || unmodified) {
813 origin.appendChanges(sourceDir);
814 } else {
815 origin.added.add("source code under OSGI-OPT/src");
816 origin.appendChanges(bundleDir);
817 }
818 }
819
820 /** Download a Maven artifact. */
821 Path downloadMaven(Properties props, M2Artifact artifact) throws IOException {
822 String repoStr = props.containsKey(ARGEO_ORIGIN_M2_REPO.toString())
823 ? props.getProperty(ARGEO_ORIGIN_M2_REPO.toString())
824 : null;
825 String alternateUri = props.getProperty(ARGEO_ORIGIN_URI.toString());
826 URL url = alternateUri != null ? new URL(alternateUri) : M2ConventionsUtils.mavenRepoUrl(repoStr, artifact);
827 return downloadMaven(url, artifact);
828 }
829
830 /** Download a Maven artifact. */
831 Path downloadMaven(URL url, M2Artifact artifact) throws IOException {
832 return download(url, mavenBase, M2ConventionsUtils.artifactPath("", artifact));
833 }
834
835 /*
836 * ECLIPSE ORIGIN
837 */
838 /** Process an archive in Eclipse format. */
839 void processEclipseArchive(Path duDir) {
840 try {
841 Path categoryRelativePath = descriptorsBase.relativize(duDir.getParent());
842 Path targetCategoryBase = a2Base.resolve(categoryRelativePath);
843 Files.createDirectories(targetCategoryBase);
844 // first delete all directories from previous builds
845 for (Path dir : Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p)))
846 deleteDirectory(dir);
847
848 Files.createDirectories(originBase);
849
850 Path commonBnd = duDir.resolve(COMMON_BND);
851 Properties commonProps = new Properties();
852 try (InputStream in = Files.newInputStream(commonBnd)) {
853 commonProps.load(in);
854 }
855 String url = commonProps.getProperty(ARGEO_ORIGIN_URI.toString());
856 if (url == null) {
857 url = uris.getProperty(duDir.getFileName().toString());
858 if (url == null)
859 throw new IllegalStateException("No url available for " + duDir);
860 commonProps.put(ARGEO_ORIGIN_URI.toString(), url);
861 }
862 Path downloaded = tryDownloadArchive(url, originBase);
863
864 FileSystem zipFs = FileSystems.newFileSystem(downloaded, (ClassLoader) null);
865
866 // filters
867 List<PathMatcher> includeMatchers = new ArrayList<>();
868 Properties includes = new Properties();
869 try (InputStream in = Files.newInputStream(duDir.resolve("includes.properties"))) {
870 includes.load(in);
871 }
872 for (Object pattern : includes.keySet()) {
873 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
874 includeMatchers.add(pathMatcher);
875 }
876
877 List<PathMatcher> excludeMatchers = new ArrayList<>();
878 Path excludeFile = duDir.resolve("excludes.properties");
879 if (Files.exists(excludeFile)) {
880 Properties excludes = new Properties();
881 try (InputStream in = Files.newInputStream(excludeFile)) {
882 excludes.load(in);
883 }
884 for (Object pattern : excludes.keySet()) {
885 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
886 excludeMatchers.add(pathMatcher);
887 }
888 }
889
890 // keys are the bundle directories
891 Map<Path, A2Origin> origins = new HashMap<>();
892 Files.walkFileTree(zipFs.getRootDirectories().iterator().next(), new SimpleFileVisitor<Path>() {
893
894 @Override
895 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
896 includeMatchers: for (PathMatcher includeMatcher : includeMatchers) {
897 if (includeMatcher.matches(file)) {
898 for (PathMatcher excludeMatcher : excludeMatchers) {
899 if (excludeMatcher.matches(file)) {
900 logger.log(TRACE, "Skipping excluded " + file);
901 return FileVisitResult.CONTINUE;
902 }
903 }
904 if (file.getFileName().toString().contains(".source_")) {
905 processEclipseSourceJar(file, targetCategoryBase);
906 logger.log(DEBUG, () -> "Processed source " + file);
907 } else {
908 Map<String, String> map = new HashMap<>();
909 for (Object key : commonProps.keySet())
910 map.put(key.toString(), commonProps.getProperty(key.toString()));
911 A2Origin origin = new A2Origin();
912 Path bundleDir = processBundleJar(file, targetCategoryBase, map, origin);
913 origins.put(bundleDir, origin);
914 logger.log(DEBUG, () -> "Processed " + file);
915 }
916 break includeMatchers;
917 }
918 }
919 return FileVisitResult.CONTINUE;
920 }
921 });
922
923 DirectoryStream<Path> dirs = Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p)
924 && p.getFileName().toString().indexOf('.') >= 0 && !p.getFileName().toString().endsWith(".src"));
925 for (Path bundleDir : dirs) {
926 A2Origin origin = origins.get(bundleDir);
927 Objects.requireNonNull(origin, "No A2 origin found for " + bundleDir);
928 createJar(bundleDir, origin);
929 }
930 } catch (IOException e) {
931 throw new RuntimeException("Cannot process " + duDir, e);
932 }
933
934 }
935
936 /** Process sources in Eclipse format. */
937 void processEclipseSourceJar(Path file, Path targetBase) throws IOException {
938 try {
939 A2Origin origin = new A2Origin();
940 Path bundleDir;
941 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
942 Manifest manifest = jarIn.getManifest();
943
944 String[] relatedBundle = manifest.getMainAttributes().getValue(ECLIPSE_SOURCE_BUNDLE.toString())
945 .split(";");
946 String version = relatedBundle[1].substring("version=\"".length());
947 version = version.substring(0, version.length() - 1);
948 NameVersion nameVersion = new NameVersion(relatedBundle[0], version);
949 bundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
950
951 Path sourceDir = separateSources ? bundleDir.getParent().resolve(bundleDir.toString() + ".src")
952 : bundleDir.resolve("OSGI-OPT/src");
953
954 Files.createDirectories(sourceDir);
955 JarEntry entry;
956 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
957 if (entry.isDirectory())
958 continue entries;
959 if (entry.getName().startsWith("META-INF"))// skip META-INF entries
960 continue entries;
961 Path target = sourceDir.resolve(entry.getName());
962 Files.createDirectories(target.getParent());
963 Files.copy(jarIn, target);
964 logger.log(TRACE, () -> "Copied source " + target);
965 }
966
967 // write the changes
968 if (separateSources) {
969 origin.appendChanges(sourceDir);
970 } else {
971 origin.added.add("source code under OSGI-OPT/src");
972 origin.appendChanges(bundleDir);
973 }
974 }
975 } catch (IOException e) {
976 throw new IllegalStateException("Cannot process " + file, e);
977 }
978 }
979
980 /*
981 * COMMON PROCESSING
982 */
983 /** Normalise a single (that is, non-merged) bundle. */
984 Path processBundleJar(Path file, Path targetBase, Map<String, String> entries, A2Origin origin) throws IOException {
985 // boolean embed = Boolean.parseBoolean(entries.getOrDefault(ARGEO_ORIGIN_EMBED.toString(), "false").toString());
986 boolean doNotModify = Boolean
987 .parseBoolean(entries.getOrDefault(ManifestHeader.ARGEO_DO_NOT_MODIFY.toString(), "false").toString());
988 NameVersion nameVersion;
989 Path bundleDir;
990 // singleton
991 boolean isSingleton = false;
992 Manifest manifest;
993 Manifest sourceManifest;
994 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
995 sourceManifest = jarIn.getManifest();
996 manifest = sourceManifest != null ? new Manifest(sourceManifest) : new Manifest();
997
998 String rawSourceSymbolicName = manifest.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME.toString());
999 if (rawSourceSymbolicName != null) {
1000 // make sure there is no directive
1001 String[] arr = rawSourceSymbolicName.split(";");
1002 for (int i = 1; i < arr.length; i++) {
1003 if (arr[i].trim().equals("singleton:=true"))
1004 isSingleton = true;
1005 logger.log(DEBUG, file.getFileName() + " is a singleton");
1006 }
1007 }
1008 // remove problematic entries in MANIFEST
1009 manifest.getEntries().clear();
1010
1011 String ourSymbolicName = entries.get(BUNDLE_SYMBOLICNAME.toString());
1012 String ourVersion = entries.get(BUNDLE_VERSION.toString());
1013
1014 if (ourSymbolicName != null && ourVersion != null) {
1015 nameVersion = new NameVersion(ourSymbolicName, ourVersion);
1016 } else {
1017 nameVersion = nameVersionFromManifest(manifest);
1018 if (ourVersion != null && !nameVersion.getVersion().equals(ourVersion)) {
1019 logger.log(WARNING,
1020 "Original version is " + nameVersion.getVersion() + " while new version is " + ourVersion);
1021 entries.put(BUNDLE_VERSION.toString(), ourVersion);
1022 }
1023 if (ourSymbolicName != null) {
1024 // we always force our symbolic name
1025 nameVersion.setName(ourSymbolicName);
1026 }
1027 }
1028 bundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
1029
1030 // copy original MANIFEST
1031 if (sourceManifest != null) {
1032 Path originalManifest = bundleDir.resolve(ARGEO_ORIGIN).resolve("MANIFEST.MF");
1033 Files.createDirectories(originalManifest.getParent());
1034 try (OutputStream out = Files.newOutputStream(originalManifest)) {
1035 sourceManifest.write(out);
1036 }
1037 origin.moved.add("original MANIFEST to " + bundleDir.relativize(originalManifest));
1038 }
1039
1040 // force Java 9 module name
1041 entries.put(ManifestHeader.AUTOMATIC_MODULE_NAME.toString(), nameVersion.getName());
1042
1043 boolean isNative = false;
1044 String os = null;
1045 String arch = null;
1046 if (bundleDir.startsWith(a2LibBase)) {
1047 isNative = true;
1048 Path libRelativePath = a2LibBase.relativize(bundleDir);
1049 os = libRelativePath.getName(0).toString();
1050 arch = libRelativePath.getName(1).toString();
1051 }
1052
1053 // if (!embed) {
1054 // copy entries
1055 JarEntry entry;
1056 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
1057 if (entry.isDirectory())
1058 continue entries;
1059 if (!doNotModify) {
1060 if (entry.getName().endsWith(".RSA") || entry.getName().endsWith(".DSA")
1061 || entry.getName().endsWith(".SF")) {
1062 origin.deleted.add("cryptographic signatures");
1063 continue entries;
1064 }
1065 if (entry.getName().endsWith("module-info.class")) { // skip Java 9 module info
1066 origin.deleted.add("Java module information (module-info.class)");
1067 continue entries;
1068 }
1069 if (entry.getName().startsWith("META-INF/versions/")) { // skip multi-version
1070 origin.deleted.add("additional Java versions (META-INF/versions)");
1071 continue entries;
1072 }
1073 if (entry.getName().startsWith("META-INF/maven/")) {
1074 origin.deleted.add("Maven information (META-INF/maven)");
1075 continue entries;
1076 }
1077 // skip file system providers as they cause issues with native image
1078 if (entry.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider")) {
1079 origin.deleted
1080 .add("file system providers (META-INF/services/java.nio.file.spi.FileSystemProvider)");
1081 continue entries;
1082 }
1083 }
1084 if (entry.getName().startsWith("OSGI-OPT/src/")) { // skip embedded sources
1085 origin.deleted.add("embedded sources");
1086 continue entries;
1087 }
1088 Path target = bundleDir.resolve(entry.getName());
1089 Files.createDirectories(target.getParent());
1090 Files.copy(jarIn, target);
1091
1092 // native libraries
1093 if (isNative && (entry.getName().endsWith(".so") || entry.getName().endsWith(".dll")
1094 || entry.getName().endsWith(".jnilib"))) {
1095 Path categoryDir = bundleDir.getParent();
1096 boolean copyDll = false;
1097 Path targetDll = categoryDir.resolve(bundleDir.relativize(target));
1098 if (nameVersion.getName().equals("com.sun.jna")) {
1099 if (arch.equals("x86_64"))
1100 arch = "x86-64";
1101 if (os.equals("macosx"))
1102 os = "darwin";
1103 if (target.getParent().getFileName().toString().equals(os + "-" + arch)) {
1104 copyDll = true;
1105 }
1106 targetDll = categoryDir.resolve(target.getFileName());
1107 } else {
1108 copyDll = true;
1109 }
1110 if (copyDll) {
1111 Files.createDirectories(targetDll.getParent());
1112 if (Files.exists(targetDll))
1113 Files.delete(targetDll);
1114 Files.copy(target, targetDll);
1115 }
1116 Files.delete(target);
1117 origin.deleted.add(bundleDir.relativize(target).toString());
1118 }
1119 logger.log(TRACE, () -> "Copied " + target);
1120 // }
1121 }
1122 }
1123
1124 // copy MANIFEST
1125 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
1126 Files.createDirectories(manifestPath.getParent());
1127
1128 if (isSingleton && entries.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
1129 entries.put(BUNDLE_SYMBOLICNAME.toString(),
1130 entries.get(BUNDLE_SYMBOLICNAME.toString()) + ";singleton:=true");
1131 }
1132
1133 // if (embed) {// copy embedded jar
1134 // Files.copy(file, bundleDir.resolve(file.getFileName()));
1135 // entries.put(ManifestHeader.BUNDLE_CLASSPATH.toString(), file.getFileName().toString());
1136 // }
1137
1138 // Final MANIFEST decisions
1139 // We also check the original OSGi metadata and compare with our changes
1140 for (String key : entries.keySet()) {
1141 String value = entries.get(key);
1142 String previousValue = manifest.getMainAttributes().getValue(key);
1143 boolean wasDifferent = previousValue != null && !previousValue.equals(value);
1144 boolean keepPrevious = false;
1145 if (wasDifferent) {
1146 if (SPDX_LICENSE_IDENTIFIER.toString().equals(key) && previousValue != null)
1147 keepPrevious = true;
1148 else if (BUNDLE_VERSION.toString().equals(key) && wasDifferent)
1149 if (previousValue.equals(value + ".0")) // typically a Maven first release
1150 keepPrevious = true;
1151
1152 if (keepPrevious) {
1153 if (logger.isLoggable(DEBUG))
1154 logger.log(DEBUG, file.getFileName() + ": " + key + " was NOT modified, value kept is "
1155 + previousValue + ", not overriden with " + value);
1156 value = previousValue;
1157 }
1158 }
1159
1160 manifest.getMainAttributes().putValue(key, value);
1161 if (wasDifferent && !keepPrevious) {
1162 if (IMPORT_PACKAGE.toString().equals(key) || EXPORT_PACKAGE.toString().equals(key))
1163 logger.log(TRACE, () -> file.getFileName() + ": " + key + " was modified");
1164 else if (BUNDLE_SYMBOLICNAME.toString().equals(key) || AUTOMATIC_MODULE_NAME.toString().equals(key))
1165 logger.log(DEBUG,
1166 file.getFileName() + ": " + key + " was " + previousValue + ", overridden with " + value);
1167 else
1168 logger.log(WARNING,
1169 file.getFileName() + ": " + key + " was " + previousValue + ", overridden with " + value);
1170 origin.modified.add("MANIFEST header " + key);
1171 }
1172
1173 // !! hack to remove unresolvable
1174 if (key.equals("Provide-Capability") || key.equals("Require-Capability"))
1175 if (nameVersion.getName().equals("osgi.core") || nameVersion.getName().equals("osgi.cmpn")) {
1176 manifest.getMainAttributes().remove(key);
1177 origin.deleted.add("MANIFEST header " + key);
1178 }
1179 }
1180
1181 // de-pollute MANIFEST
1182 for (Iterator<Map.Entry<Object, Object>> manifestEntries = manifest.getMainAttributes().entrySet()
1183 .iterator(); manifestEntries.hasNext();) {
1184 Map.Entry<Object, Object> manifestEntry = manifestEntries.next();
1185 switch (manifestEntry.getKey().toString()) {
1186 case "Archiver-Version":
1187 case "Build-By":
1188 case "Created-By":
1189 case "Originally-Created-By":
1190 case "Tool":
1191 case "Bnd-LastModified":
1192 manifestEntries.remove();
1193 origin.deleted.add("MANIFEST header " + manifestEntry.getKey());
1194 break;
1195 default:
1196 if (sourceManifest != null && !sourceManifest.getMainAttributes().containsKey(manifestEntry.getKey()))
1197 origin.added.add("MANIFEST header " + manifestEntry.getKey());
1198 }
1199 }
1200
1201 processLicense(bundleDir, manifest);
1202
1203 origin.modified.add("MANIFEST (META-INF/MANIFEST.MF)");
1204 // write the MANIFEST
1205 try (OutputStream out = Files.newOutputStream(manifestPath)) {
1206 manifest.write(out);
1207 }
1208 return bundleDir;
1209 }
1210
1211 /** Process SPDX license identifier. */
1212 void processLicense(Path bundleDir, Manifest manifest) {
1213 String spdxLicenceId = manifest.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER.toString());
1214 String bundleLicense = manifest.getMainAttributes().getValue(BUNDLE_LICENSE.toString());
1215 if (spdxLicenceId == null) {
1216 logger.log(ERROR, bundleDir.getFileName() + ": " + SPDX_LICENSE_IDENTIFIER + " not available, "
1217 + BUNDLE_LICENSE + " is " + bundleLicense);
1218 } else {
1219 // only use the first licensing option
1220 int orIndex = spdxLicenceId.indexOf(" OR ");
1221 if (orIndex >= 0)
1222 spdxLicenceId = spdxLicenceId.substring(0, orIndex).trim();
1223
1224 String bundleDirName = bundleDir.getFileName().toString();
1225 // force licenses of some well-known components
1226 // even if we say otherwise (typically because from an Eclipse archive)
1227 if (bundleDirName.startsWith("org.apache."))
1228 spdxLicenceId = "Apache-2.0";
1229 if (bundleDirName.startsWith("com.sun.jna."))
1230 spdxLicenceId = "Apache-2.0";
1231 if (bundleDirName.startsWith("com.ibm.icu."))
1232 spdxLicenceId = "ICU";
1233 if (bundleDirName.startsWith("javax.annotation."))
1234 spdxLicenceId = "GPL-2.0-only WITH Classpath-exception-2.0";
1235 if (bundleDirName.startsWith("javax.inject."))
1236 spdxLicenceId = "Apache-2.0";
1237 if (bundleDirName.startsWith("org.osgi."))
1238 spdxLicenceId = "Apache-2.0";
1239
1240 manifest.getMainAttributes().putValue(SPDX_LICENSE_IDENTIFIER.toString(), spdxLicenceId);
1241 if (!licensesUsed.containsKey(spdxLicenceId))
1242 licensesUsed.put(spdxLicenceId, new TreeSet<>());
1243 licensesUsed.get(spdxLicenceId).add(bundleDir.getParent().getFileName() + "/" + bundleDir.getFileName());
1244 }
1245 }
1246
1247 /*
1248 * UTILITIES
1249 */
1250 /** Recursively deletes a directory. */
1251 static void deleteDirectory(Path path) throws IOException {
1252 if (!Files.exists(path))
1253 return;
1254 Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
1255 @Override
1256 public FileVisitResult postVisitDirectory(Path directory, IOException e) throws IOException {
1257 if (e != null)
1258 throw e;
1259 Files.delete(directory);
1260 return CONTINUE;
1261 }
1262
1263 @Override
1264 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1265 Files.delete(file);
1266 return CONTINUE;
1267 }
1268 });
1269 }
1270
1271 /** Extract name/version from a MANIFEST. */
1272 NameVersion nameVersionFromManifest(Manifest manifest) {
1273 Attributes attrs = manifest.getMainAttributes();
1274 // symbolic name
1275 String symbolicName = attrs.getValue(ManifestHeader.BUNDLE_SYMBOLICNAME.toString());
1276 if (symbolicName == null)
1277 return null;
1278 // make sure there is no directive
1279 symbolicName = symbolicName.split(";")[0];
1280
1281 String version = attrs.getValue(ManifestHeader.BUNDLE_VERSION.toString());
1282 return new NameVersion(symbolicName, version);
1283 }
1284
1285 /** Try to download from an URI. */
1286 Path tryDownloadArchive(String uri, Path dir) throws IOException {
1287 // find mirror
1288 List<String> urlBases = null;
1289 String uriPrefix = null;
1290 uriPrefixes: for (String uriPref : mirrors.keySet()) {
1291 if (uri.startsWith(uriPref)) {
1292 if (mirrors.get(uriPref).size() > 0) {
1293 urlBases = mirrors.get(uriPref);
1294 uriPrefix = uriPref;
1295 break uriPrefixes;
1296 }
1297 }
1298 }
1299 if (urlBases == null)
1300 try {
1301 return downloadArchive(new URL(uri), dir);
1302 } catch (FileNotFoundException e) {
1303 throw new FileNotFoundException("Cannot find " + uri);
1304 }
1305
1306 // try to download
1307 for (String urlBase : urlBases) {
1308 String relativePath = uri.substring(uriPrefix.length());
1309 URL url = new URL(urlBase + relativePath);
1310 try {
1311 return downloadArchive(url, dir);
1312 } catch (FileNotFoundException e) {
1313 logger.log(WARNING, "Cannot download " + url + ", trying another mirror");
1314 }
1315 }
1316 throw new FileNotFoundException("Cannot find " + uri);
1317 }
1318
1319 /**
1320 * Effectively download. Synchronised in order to avoid downloading twice in
1321 * parallel.
1322 */
1323 synchronized Path downloadArchive(URL url, Path dir) throws IOException {
1324 return download(url, dir, (String) null);
1325 }
1326
1327 /** Effectively download. */
1328 Path download(URL url, Path dir, String name) throws IOException {
1329
1330 Path dest;
1331 if (name == null) {
1332 // We use also use parent directory in case the archive itself has a fixed name
1333 String[] segments = url.getPath().split("/");
1334 name = segments.length > 1 ? segments[segments.length - 2] + '-' + segments[segments.length - 1]
1335 : segments[segments.length - 1];
1336 }
1337
1338 dest = dir.resolve(name);
1339 if (Files.exists(dest)) {
1340 logger.log(TRACE, () -> "File " + dest + " already exists for " + url + ", not downloading again");
1341 return dest;
1342 } else {
1343 Files.createDirectories(dest.getParent());
1344 }
1345
1346 try (InputStream in = url.openStream()) {
1347 Files.copy(in, dest);
1348 logger.log(DEBUG, () -> "Downloaded " + dest + " from " + url);
1349 }
1350 return dest;
1351 }
1352
1353 /** Create a JAR file from a directory. */
1354 Path createJar(Path bundleDir, A2Origin origin) throws IOException {
1355 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
1356 Manifest manifest;
1357 try (InputStream in = Files.newInputStream(manifestPath)) {
1358 manifest = new Manifest(in);
1359 }
1360 // legal requirements
1361 origin.appendChanges(bundleDir);
1362 createReadMe(bundleDir, manifest);
1363
1364 // create the jar
1365 Path jarPath = bundleDir.getParent().resolve(bundleDir.getFileName() + ".jar");
1366 try (JarOutputStream jarOut = new JarOutputStream(Files.newOutputStream(jarPath), manifest)) {
1367 jarOut.setLevel(Deflater.DEFAULT_COMPRESSION);
1368 Files.walkFileTree(bundleDir, new SimpleFileVisitor<Path>() {
1369
1370 @Override
1371 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1372 if (file.getFileName().toString().equals("MANIFEST.MF"))
1373 return super.visitFile(file, attrs);
1374 JarEntry entry = new JarEntry(
1375 bundleDir.relativize(file).toString().replace(File.separatorChar, '/'));
1376 jarOut.putNextEntry(entry);
1377 Files.copy(file, jarOut);
1378 return super.visitFile(file, attrs);
1379 }
1380
1381 });
1382 }
1383 deleteDirectory(bundleDir);
1384
1385 if (separateSources)
1386 createSourceJar(bundleDir, manifest, null);
1387
1388 return jarPath;
1389 }
1390
1391 /** Package sources separately, in the Eclipse-SourceBundle format. */
1392 void createSourceJar(Path bundleDir, Manifest manifest, Properties props) throws IOException {
1393 boolean unmodified = props != null;
1394 Path bundleCategoryDir = bundleDir.getParent();
1395 Path sourceDir = bundleCategoryDir.resolve(bundleDir.toString() + ".src");
1396 if (!Files.exists(sourceDir)) {
1397 logger.log(WARNING, sourceDir + " does not exist, skipping...");
1398 return;
1399 }
1400
1401 Path relPath = a2Base.relativize(bundleCategoryDir);
1402 Path srcCategoryDir = a2SrcBase.resolve(relPath);
1403 Path srcJarP = srcCategoryDir.resolve(sourceDir.getFileName() + ".jar");
1404 Files.createDirectories(srcJarP.getParent());
1405
1406 String bundleSymbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1407 // in case there are additional directives
1408 bundleSymbolicName = bundleSymbolicName.split(";")[0];
1409 Manifest srcManifest = new Manifest();
1410 srcManifest.getMainAttributes().put(MANIFEST_VERSION, "1.0");
1411 BUNDLE_SYMBOLICNAME.put(srcManifest, bundleSymbolicName + ".src");
1412 BUNDLE_VERSION.put(srcManifest, BUNDLE_VERSION.get(manifest));
1413 ECLIPSE_SOURCE_BUNDLE.put(srcManifest,
1414 bundleSymbolicName + ";version=\"" + BUNDLE_VERSION.get(manifest) + "\"");
1415
1416 // metadata
1417 createReadMe(sourceDir, unmodified ? props : manifest);
1418 // create jar
1419 try (JarOutputStream srcJarOut = new JarOutputStream(Files.newOutputStream(srcJarP), srcManifest)) {
1420 // srcJarOut.setLevel(Deflater.BEST_COMPRESSION);
1421 Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
1422
1423 @Override
1424 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1425 if (file.getFileName().toString().equals("MANIFEST.MF"))
1426 return super.visitFile(file, attrs);
1427 JarEntry entry = new JarEntry(
1428 sourceDir.relativize(file).toString().replace(File.separatorChar, '/'));
1429 srcJarOut.putNextEntry(entry);
1430 Files.copy(file, srcJarOut);
1431 return super.visitFile(file, attrs);
1432 }
1433
1434 });
1435 }
1436 deleteDirectory(sourceDir);
1437 }
1438
1439 /**
1440 * Generate a readme clarifying and prominently notifying of the repackaging and
1441 * modifications.
1442 */
1443 void createReadMe(Path jarDir, Object mapping) throws IOException {
1444 // write repackaged README
1445 try (BufferedWriter writer = Files.newBufferedWriter(jarDir.resolve(README_REPACKAGED))) {
1446 boolean merged = ARGEO_ORIGIN_M2_MERGE.get(mapping) != null;
1447 if (merged)
1448 writer.append("This component is a merging of third party components"
1449 + " in order to comply with A2 packaging standards.\n");
1450 else
1451 writer.append("This component is a repackaging of a third party component"
1452 + " in order to comply with A2 packaging standards.\n");
1453
1454 // license
1455 String spdxLicenseId = SPDX_LICENSE_IDENTIFIER.get(mapping);
1456 if (spdxLicenseId == null)
1457 throw new IllegalStateException("An SPDX license id must have beend defined at this stage.");
1458 writer.append("\nIt is redistributed under the following license:\n\n");
1459 writer.append("SPDX-Identifier: " + spdxLicenseId + "\n\n");
1460
1461 if (!spdxLicenseId.startsWith("LicenseRef")) {// standard
1462 int withIndex = spdxLicenseId.indexOf(" WITH ");
1463 if (withIndex >= 0) {
1464 String simpleId = spdxLicenseId.substring(0, withIndex).trim();
1465 String exception = spdxLicenseId.substring(withIndex + " WITH ".length());
1466 writer.append("which are available here: https://spdx.org/licenses/" + simpleId
1467 + "\nand here: https://spdx.org/licenses/" + exception + "\n");
1468 } else {
1469 writer.append("which is available here: https://spdx.org/licenses/" + spdxLicenseId + "\n");
1470 }
1471 } else {
1472 String url = BUNDLE_LICENSE.get(mapping);
1473 if (url != null) {
1474 writer.write("which is available here: " + url + "\n");
1475 } else {
1476 logger.log(ERROR, "No licence URL for " + jarDir);
1477 }
1478 }
1479
1480 // origin
1481 String originDesc = ARGEO_ORIGIN_URI.get(mapping);
1482 if (originDesc != null)
1483 writer.append("\nThe original component comes from " + originDesc + ".\n");
1484 else {
1485 String m2Repo = ARGEO_ORIGIN_M2_REPO.get(mapping);
1486 originDesc = ARGEO_ORIGIN_M2.get(mapping);
1487 if (originDesc != null)
1488 writer.append("\nThe original component has M2 coordinates:\n" + originDesc.replace(',', '\n')
1489 + "\n" + (m2Repo != null ? "\nin M2 repository " + m2Repo + "\n" : ""));
1490 else
1491 logger.log(ERROR, "Cannot find origin information in " + jarDir);
1492 }
1493 String originSources = ARGEO_ORIGIN_SOURCES_URI.get(mapping);
1494 if (originSources != null)
1495 writer.append("\nThe original sources come from " + originSources + ".\n");
1496
1497 if (Files.exists(jarDir.resolve(CHANGES)))
1498 writer.append("\nA detailed list of changes is available under " + CHANGES + ".\n");
1499
1500 if (!jarDir.getFileName().toString().endsWith(".src")) {// binary archive
1501 if (separateSources)
1502 writer.append("Corresponding sources are available in the related archive named "
1503 + jarDir.toString() + ".src.jar.\n");
1504 else
1505 writer.append("Corresponding sources are available under OSGI-OPT/src.\n");
1506 }
1507 }
1508 }
1509
1510 /**
1511 * Gathers modifications performed on the original binaries and sources,
1512 * especially in order to comply with their license requirements.
1513 */
1514 class A2Origin {
1515 A2Origin() {
1516
1517 }
1518
1519 Set<String> modified = new TreeSet<>();
1520 Set<String> deleted = new TreeSet<>();
1521 Set<String> added = new TreeSet<>();
1522 Set<String> moved = new TreeSet<>();
1523
1524 /** Append changes to the A2-ORIGIN/changes file. */
1525 void appendChanges(Path baseDirectory) throws IOException {
1526 if (modified.isEmpty() && deleted.isEmpty() && added.isEmpty() && moved.isEmpty())
1527 return; // no changes
1528 Path changesFile = baseDirectory.resolve(CHANGES);
1529 Files.createDirectories(changesFile.getParent());
1530 try (BufferedWriter writer = Files.newBufferedWriter(changesFile, APPEND, CREATE)) {
1531 for (String msg : added)
1532 writer.write("- Added " + msg + ".\n");
1533 for (String msg : modified)
1534 writer.write("- Modified " + msg + ".\n");
1535 for (String msg : moved)
1536 writer.write("- Moved " + msg + ".\n");
1537 for (String msg : deleted)
1538 writer.write("- Deleted " + msg + ".\n");
1539 }
1540 }
1541 }
1542 }
1543
1544 /** Simple representation of an M2 artifact. */
1545 class M2Artifact extends CategoryNameVersion {
1546 private String classifier;
1547
1548 M2Artifact(String m2coordinates) {
1549 this(m2coordinates, null);
1550 }
1551
1552 M2Artifact(String m2coordinates, String classifier) {
1553 String[] parts = m2coordinates.split(":");
1554 setCategory(parts[0]);
1555 setName(parts[1]);
1556 if (parts.length > 2) {
1557 setVersion(parts[2]);
1558 }
1559 this.classifier = classifier;
1560 }
1561
1562 String getGroupId() {
1563 return super.getCategory();
1564 }
1565
1566 String getArtifactId() {
1567 return super.getName();
1568 }
1569
1570 String toM2Coordinates() {
1571 return getCategory() + ":" + getName() + (getVersion() != null ? ":" + getVersion() : "");
1572 }
1573
1574 String getClassifier() {
1575 return classifier != null ? classifier : "";
1576 }
1577
1578 String getExtension() {
1579 return "jar";
1580 }
1581 }
1582
1583 /** Utilities around Maven (conventions based). */
1584 class M2ConventionsUtils {
1585 final static String MAVEN_CENTRAL_BASE_URL = "https://repo1.maven.org/maven2/";
1586
1587 /** The file name of this artifact when stored */
1588 static String artifactFileName(M2Artifact artifact) {
1589 return artifact.getArtifactId() + '-' + artifact.getVersion()
1590 + (artifact.getClassifier().equals("") ? "" : '-' + artifact.getClassifier()) + '.'
1591 + artifact.getExtension();
1592 }
1593
1594 /** Absolute path to the file */
1595 static String artifactPath(String artifactBasePath, M2Artifact artifact) {
1596 return artifactParentPath(artifactBasePath, artifact) + '/' + artifactFileName(artifact);
1597 }
1598
1599 /** Absolute path to the file */
1600 static String artifactUrl(String repoUrl, M2Artifact artifact) {
1601 if (repoUrl.endsWith("/"))
1602 return repoUrl + artifactPath("/", artifact).substring(1);
1603 else
1604 return repoUrl + artifactPath("/", artifact);
1605 }
1606
1607 /** Absolute path to the file */
1608 static URL mavenRepoUrl(String repoBase, M2Artifact artifact) {
1609 String url = artifactUrl(repoBase == null ? MAVEN_CENTRAL_BASE_URL : repoBase, artifact);
1610 try {
1611 return new URL(url);
1612 } catch (MalformedURLException e) {
1613 // it should not happen
1614 throw new IllegalStateException(e);
1615 }
1616 }
1617
1618 /** Absolute path to the directories where the files will be stored */
1619 static String artifactParentPath(String artifactBasePath, M2Artifact artifact) {
1620 return artifactBasePath + (artifactBasePath.endsWith("/") || artifactBasePath.equals("") ? "" : "/")
1621 + artifactParentPath(artifact);
1622 }
1623
1624 /** Relative path to the directories where the files will be stored */
1625 static String artifactParentPath(M2Artifact artifact) {
1626 return artifact.getGroupId().replace('.', '/') + '/' + artifact.getArtifactId() + '/' + artifact.getVersion();
1627 }
1628
1629 /** Singleton */
1630 private M2ConventionsUtils() {
1631 }
1632 }
1633
1634 /** Combination of a category, a name and a version. */
1635 class CategoryNameVersion extends NameVersion {
1636 private String category;
1637
1638 CategoryNameVersion() {
1639 }
1640
1641 CategoryNameVersion(String category, String name, String version) {
1642 super(name, version);
1643 this.category = category;
1644 }
1645
1646 CategoryNameVersion(String category, NameVersion nameVersion) {
1647 super(nameVersion);
1648 this.category = category;
1649 }
1650
1651 String getCategory() {
1652 return category;
1653 }
1654
1655 void setCategory(String category) {
1656 this.category = category;
1657 }
1658
1659 @Override
1660 public String toString() {
1661 return category + ":" + super.toString();
1662 }
1663
1664 }
1665
1666 /** Combination of a name and a version. */
1667 class NameVersion implements Comparable<NameVersion> {
1668 private String name;
1669 private String version;
1670
1671 NameVersion() {
1672 }
1673
1674 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1675 NameVersion(String nameVersion) {
1676 int index = nameVersion.indexOf(";version=");
1677 if (index < 0) {
1678 setName(nameVersion);
1679 setVersion(null);
1680 } else {
1681 setName(nameVersion.substring(0, index));
1682 setVersion(nameVersion.substring(index + ";version=".length()));
1683 }
1684 }
1685
1686 NameVersion(String name, String version) {
1687 this.name = name;
1688 this.version = version;
1689 }
1690
1691 NameVersion(NameVersion nameVersion) {
1692 this.name = nameVersion.getName();
1693 this.version = nameVersion.getVersion();
1694 }
1695
1696 String getName() {
1697 return name;
1698 }
1699
1700 void setName(String name) {
1701 this.name = name;
1702 }
1703
1704 String getVersion() {
1705 return version;
1706 }
1707
1708 void setVersion(String version) {
1709 this.version = version;
1710 }
1711
1712 String getBranch() {
1713 String[] parts = getVersion().split("\\.");
1714 if (parts.length < 2)
1715 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1716 return parts[0] + "." + parts[1];
1717 }
1718
1719 @Override
1720 public boolean equals(Object obj) {
1721 if (obj instanceof NameVersion) {
1722 NameVersion nameVersion = (NameVersion) obj;
1723 return name.equals(nameVersion.getName()) && version.equals(nameVersion.getVersion());
1724 } else
1725 return false;
1726 }
1727
1728 @Override
1729 public int hashCode() {
1730 return name.hashCode();
1731 }
1732
1733 @Override
1734 public String toString() {
1735 return name + ":" + version;
1736 }
1737
1738 public int compareTo(NameVersion o) {
1739 if (o.getName().equals(name))
1740 return version.compareTo(o.getVersion());
1741 else
1742 return name.compareTo(o.getName());
1743 }
1744 }