]> git.argeo.org Git - cc0/argeo-build.git/blob - src/org/argeo/build/Repackage.java
b4b95c1d33fe7c5b5f253edc34bfbc3e23285266
[cc0/argeo-build.git] / src / org / argeo / build / Repackage.java
1 package org.argeo.build;
2
3 import static java.lang.System.Logger.Level.DEBUG;
4 import static java.lang.System.Logger.Level.ERROR;
5 import static java.lang.System.Logger.Level.INFO;
6 import static java.lang.System.Logger.Level.TRACE;
7 import static java.lang.System.Logger.Level.WARNING;
8 import static java.nio.file.FileVisitResult.CONTINUE;
9 import static java.nio.file.StandardOpenOption.APPEND;
10 import static java.nio.file.StandardOpenOption.CREATE;
11 import static java.util.jar.Attributes.Name.MANIFEST_VERSION;
12 import static org.argeo.build.Repackage.ManifestHeader.ARGEO_DO_NOT_MODIFY;
13 import static org.argeo.build.Repackage.ManifestHeader.ARGEO_ORIGIN_M2;
14 import static org.argeo.build.Repackage.ManifestHeader.ARGEO_ORIGIN_M2_MERGE;
15 import static org.argeo.build.Repackage.ManifestHeader.ARGEO_ORIGIN_M2_REPO;
16 import static org.argeo.build.Repackage.ManifestHeader.ARGEO_ORIGIN_NO_METADATA_GENERATION;
17 import static org.argeo.build.Repackage.ManifestHeader.ARGEO_ORIGIN_SOURCES_URI;
18 import static org.argeo.build.Repackage.ManifestHeader.ARGEO_ORIGIN_URI;
19 import static org.argeo.build.Repackage.ManifestHeader.AUTOMATIC_MODULE_NAME;
20 import static org.argeo.build.Repackage.ManifestHeader.BUNDLE_LICENSE;
21 import static org.argeo.build.Repackage.ManifestHeader.BUNDLE_SYMBOLICNAME;
22 import static org.argeo.build.Repackage.ManifestHeader.BUNDLE_VERSION;
23 import static org.argeo.build.Repackage.ManifestHeader.ECLIPSE_SOURCE_BUNDLE;
24 import static org.argeo.build.Repackage.ManifestHeader.EXPORT_PACKAGE;
25 import static org.argeo.build.Repackage.ManifestHeader.IMPORT_PACKAGE;
26 import static org.argeo.build.Repackage.ManifestHeader.SPDX_LICENSE_IDENTIFIER;
27
28 import java.io.BufferedWriter;
29 import java.io.File;
30 import java.io.FileNotFoundException;
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.io.OutputStream;
34 import java.lang.System.Logger;
35 import java.net.MalformedURLException;
36 import java.net.URL;
37 import java.nio.charset.StandardCharsets;
38 import java.nio.file.DirectoryStream;
39 import java.nio.file.FileSystem;
40 import java.nio.file.FileSystems;
41 import java.nio.file.FileVisitResult;
42 import java.nio.file.Files;
43 import java.nio.file.Path;
44 import java.nio.file.PathMatcher;
45 import java.nio.file.Paths;
46 import java.nio.file.SimpleFileVisitor;
47 import java.nio.file.StandardCopyOption;
48 import java.nio.file.StandardOpenOption;
49 import java.nio.file.attribute.BasicFileAttributes;
50 import java.util.ArrayList;
51 import java.util.HashMap;
52 import java.util.Iterator;
53 import java.util.List;
54 import java.util.Map;
55 import java.util.Objects;
56 import java.util.Properties;
57 import java.util.Set;
58 import java.util.StringJoiner;
59 import java.util.TreeMap;
60 import java.util.TreeSet;
61 import java.util.concurrent.CompletableFuture;
62 import java.util.jar.Attributes;
63 import java.util.jar.JarEntry;
64 import java.util.jar.JarInputStream;
65 import java.util.jar.JarOutputStream;
66 import java.util.jar.Manifest;
67 import java.util.zip.Deflater;
68
69 import aQute.bnd.osgi.Analyzer;
70 import aQute.bnd.osgi.Jar;
71
72 /** Repackages existing jar files into OSGi bundles in an A2 repository. */
73 public class Repackage {
74 final static Logger logger = System.getLogger(Repackage.class.getName());
75
76 /**
77 * Environment variable on whether sources should be packaged separately or
78 * integrated in the bundles.
79 */
80 final static String ENV_SOURCE_BUNDLES = "SOURCE_BUNDLES";
81 /** Environment variable on whether operations should be parallelised. */
82 final static String ENV_ARGEO_BUILD_SEQUENTIAL = "ARGEO_BUILD_SEQUENTIAL";
83
84 /** Whether repackaging should run in parallel (default) or sequentially. */
85 final static boolean sequential = Boolean.parseBoolean(System.getenv(ENV_ARGEO_BUILD_SEQUENTIAL));
86
87 /** Main entry point. */
88 public static void main(String[] args) {
89 if (sequential)
90 logger.log(INFO, "Build will be sequential");
91 if (args.length < 2) {
92 System.err.println("Usage: <path to a2 output dir> <category1> <category2> ...");
93 System.exit(1);
94 }
95 Path a2Base = Paths.get(args[0]).toAbsolutePath().normalize();
96 Path descriptorsBase = Paths.get(".").toAbsolutePath().normalize();
97 Repackage factory = new Repackage(a2Base, descriptorsBase);
98
99 List<CompletableFuture<Void>> toDos = new ArrayList<>();
100 for (int i = 1; i < args.length; i++) {
101 Path p = Paths.get(args[i]);
102 if (sequential)
103 factory.processCategory(p);
104 else
105 toDos.add(CompletableFuture.runAsync(() -> factory.processCategory(p)));
106 }
107 if (!sequential)
108 CompletableFuture.allOf(toDos.toArray(new CompletableFuture[toDos.size()])).join();
109
110 // Summary
111 StringBuilder sb = new StringBuilder();
112 for (String licenseId : licensesUsed.keySet())
113 for (String name : licensesUsed.get(licenseId))
114 sb.append((licenseId.equals("") ? "Proprietary" : licenseId) + "\t\t" + name + "\n");
115 logger.log(INFO, "# License summary:\n" + sb);
116 }
117
118 /** MANIFEST headers. */
119 enum ManifestHeader {
120 // OSGi
121 /** OSGi bundle symbolic name. */
122 BUNDLE_SYMBOLICNAME("Bundle-SymbolicName"), //
123 /** OSGi bundle version. */
124 BUNDLE_VERSION("Bundle-Version"), //
125 /** OSGi bundle license. */
126 BUNDLE_LICENSE("Bundle-License"), //
127 /** OSGi exported packages list. */
128 EXPORT_PACKAGE("Export-Package"), //
129 /** OSGi imported packages list. */
130 IMPORT_PACKAGE("Import-Package"), //
131 /** OSGi path to embedded jar. */
132 BUNDLE_CLASSPATH("Bundle-Classpath"), //
133 // Java
134 /** Java module name. */
135 AUTOMATIC_MODULE_NAME("Automatic-Module-Name"), //
136 // Eclipse
137 /** Eclipse source bundle. */
138 ECLIPSE_SOURCE_BUNDLE("Eclipse-SourceBundle"), //
139 // SPDX
140 /**
141 * SPDX license identifier.
142 *
143 * @see https://spdx.org/licenses/
144 */
145 SPDX_LICENSE_IDENTIFIER("SPDX-License-Identifier"), //
146 // Argeo Origin
147 /**
148 * Maven coordinates of the origin, possibly partial when using common.bnd or
149 * merge.bnd.
150 */
151 ARGEO_ORIGIN_M2("Argeo-Origin-M2"), //
152 /** List of Maven coordinates to merge. */
153 ARGEO_ORIGIN_M2_MERGE("Argeo-Origin-M2-Merge"), //
154 /** Maven repository, if not the default one. */
155 ARGEO_ORIGIN_M2_REPO("Argeo-Origin-M2-Repo"), //
156 /**
157 * Do not perform BND analysis of the origin component. Typically Import_package
158 * and Export-Package will be kept untouched.
159 */
160 ARGEO_ORIGIN_NO_METADATA_GENERATION("Argeo-Origin-NoMetadataGeneration"), //
161 // /**
162 // * Embed the original jar without modifying it (may be required by some
163 // * proprietary licenses, such as JCR Day License).
164 // */
165 // ARGEO_ORIGIN_EMBED("Argeo-Origin-Embed"), //
166 /**
167 * Do not modify original jar (may be required by some proprietary licenses,
168 * such as JCR Day License).
169 */
170 ARGEO_DO_NOT_MODIFY("Argeo-Origin-Do-Not-Modify"), //
171 /**
172 * Origin (non-Maven) URI of the component. It may be anything (jar, archive,
173 * etc.).
174 */
175 ARGEO_ORIGIN_URI("Argeo-Origin-URI"), //
176 /**
177 * Origin (non-Maven) URI of the source of the component. It may be anything
178 * (jar, archive, code repository, etc.).
179 */
180 ARGEO_ORIGIN_SOURCES_URI("Argeo-Origin-Sources-URI"), //
181 ;
182
183 final String 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 if (!props.containsKey(ARGEO_ORIGIN_SOURCES_URI.toString()))
756 ARGEO_ORIGIN_SOURCES_URI.put(props, sourcesUrl.toString());
757 processM2SourceJar(sourcesDownloaded, targetBundleDir, merging ? artifact : null, unmodified);
758 logger.log(TRACE, () -> "Processed source " + sourcesDownloaded);
759 } catch (Exception e) {
760 logger.log(ERROR, () -> "Cannot download source for " + artifact);
761 }
762
763 }
764
765 /** Integrate sources from a downloaded jar file. */
766 void processM2SourceJar(Path file, Path bundleDir, M2Artifact mergingFrom, boolean unmodified) throws IOException {
767 A2Origin origin = new A2Origin();
768 Path sourceDir = separateSources || unmodified ? bundleDir.getParent().resolve(bundleDir.toString() + ".src")
769 : bundleDir.resolve("OSGI-OPT/src");
770 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
771
772 String mergingMsg = "";
773 if (mergingFrom != null)
774 mergingMsg = " of " + mergingFrom;
775
776 Files.createDirectories(sourceDir);
777 JarEntry entry;
778 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
779 String relPath = entry.getName();
780 if (entry.isDirectory())
781 continue entries;
782 if (entry.getName().equals("META-INF/MANIFEST.MF")) {// skip META-INF entries
783 origin.deleted.add("MANIFEST.MF from the sources" + mergingMsg);
784 continue entries;
785 }
786 if (!unmodified) {
787 if (entry.getName().startsWith("module-info.java")) {// skip Java module information
788 origin.deleted.add("Java module information from the sources (module-info.java)" + mergingMsg);
789 continue entries;
790 }
791 if (entry.getName().startsWith("/")) { // absolute paths
792 int metaInfIndex = entry.getName().indexOf("META-INF");
793 if (metaInfIndex >= 0) {
794 relPath = entry.getName().substring(metaInfIndex);
795 origin.moved.add(" to " + relPath + " entry with absolute path " + entry.getName());
796 } else {
797 logger.log(WARNING, entry.getName() + " has an absolute path");
798 origin.deleted.add(entry.getName() + " from the sources" + mergingMsg);
799 }
800 continue entries;
801 }
802 }
803 Path target = sourceDir.resolve(relPath);
804 Files.createDirectories(target.getParent());
805 if (!Files.exists(target)) {
806 Files.copy(jarIn, target);
807 logger.log(TRACE, () -> "Copied source " + target);
808 } else {
809 logger.log(TRACE, () -> target + " already exists, skipping...");
810 }
811 }
812 }
813 // write the changes
814 if (separateSources || unmodified) {
815 origin.appendChanges(sourceDir);
816 } else {
817 origin.added.add("source code under OSGI-OPT/src");
818 origin.appendChanges(bundleDir);
819 }
820 }
821
822 /** Download a Maven artifact. */
823 Path downloadMaven(Properties props, M2Artifact artifact) throws IOException {
824 String repoStr = props.containsKey(ARGEO_ORIGIN_M2_REPO.toString())
825 ? props.getProperty(ARGEO_ORIGIN_M2_REPO.toString())
826 : null;
827 String alternateUri = props.getProperty(ARGEO_ORIGIN_URI.toString());
828 URL url = alternateUri != null ? new URL(alternateUri) : M2ConventionsUtils.mavenRepoUrl(repoStr, artifact);
829 return downloadMaven(url, artifact);
830 }
831
832 /** Download a Maven artifact. */
833 Path downloadMaven(URL url, M2Artifact artifact) throws IOException {
834 return download(url, mavenBase, M2ConventionsUtils.artifactPath("", artifact));
835 }
836
837 /*
838 * ECLIPSE ORIGIN
839 */
840 /** Process an archive in Eclipse format. */
841 void processEclipseArchive(Path duDir) {
842 try {
843 Path categoryRelativePath = descriptorsBase.relativize(duDir.getParent());
844 Path targetCategoryBase = a2Base.resolve(categoryRelativePath);
845 Files.createDirectories(targetCategoryBase);
846 // first delete all directories from previous builds
847 for (Path dir : Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p)))
848 deleteDirectory(dir);
849
850 Files.createDirectories(originBase);
851
852 Path commonBnd = duDir.resolve(COMMON_BND);
853 Properties commonProps = new Properties();
854 try (InputStream in = Files.newInputStream(commonBnd)) {
855 commonProps.load(in);
856 }
857 String url = commonProps.getProperty(ARGEO_ORIGIN_URI.toString());
858 if (url == null) {
859 url = uris.getProperty(duDir.getFileName().toString());
860 if (url == null)
861 throw new IllegalStateException("No url available for " + duDir);
862 commonProps.put(ARGEO_ORIGIN_URI.toString(), url);
863 }
864 Path downloaded = tryDownloadArchive(url, originBase);
865
866 FileSystem zipFs = FileSystems.newFileSystem(downloaded, (ClassLoader) null);
867
868 // filters
869 List<PathMatcher> includeMatchers = new ArrayList<>();
870 Properties includes = new Properties();
871 try (InputStream in = Files.newInputStream(duDir.resolve("includes.properties"))) {
872 includes.load(in);
873 }
874 for (Object pattern : includes.keySet()) {
875 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
876 includeMatchers.add(pathMatcher);
877 }
878
879 List<PathMatcher> excludeMatchers = new ArrayList<>();
880 Path excludeFile = duDir.resolve("excludes.properties");
881 if (Files.exists(excludeFile)) {
882 Properties excludes = new Properties();
883 try (InputStream in = Files.newInputStream(excludeFile)) {
884 excludes.load(in);
885 }
886 for (Object pattern : excludes.keySet()) {
887 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
888 excludeMatchers.add(pathMatcher);
889 }
890 }
891
892 // keys are the bundle directories
893 Map<Path, A2Origin> origins = new HashMap<>();
894 Files.walkFileTree(zipFs.getRootDirectories().iterator().next(), new SimpleFileVisitor<Path>() {
895
896 @Override
897 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
898 includeMatchers: for (PathMatcher includeMatcher : includeMatchers) {
899 if (includeMatcher.matches(file)) {
900 for (PathMatcher excludeMatcher : excludeMatchers) {
901 if (excludeMatcher.matches(file)) {
902 logger.log(TRACE, "Skipping excluded " + file);
903 return FileVisitResult.CONTINUE;
904 }
905 }
906 if (file.getFileName().toString().contains(".source_")) {
907 processEclipseSourceJar(file, targetCategoryBase);
908 logger.log(DEBUG, () -> "Processed source " + file);
909 } else {
910 Map<String, String> map = new HashMap<>();
911 for (Object key : commonProps.keySet())
912 map.put(key.toString(), commonProps.getProperty(key.toString()));
913 A2Origin origin = new A2Origin();
914 Path bundleDir = processBundleJar(file, targetCategoryBase, map, origin);
915 origins.put(bundleDir, origin);
916 logger.log(DEBUG, () -> "Processed " + file);
917 }
918 break includeMatchers;
919 }
920 }
921 return FileVisitResult.CONTINUE;
922 }
923 });
924
925 DirectoryStream<Path> dirs = Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p)
926 && p.getFileName().toString().indexOf('.') >= 0 && !p.getFileName().toString().endsWith(".src"));
927 for (Path bundleDir : dirs) {
928 A2Origin origin = origins.get(bundleDir);
929 Objects.requireNonNull(origin, "No A2 origin found for " + bundleDir);
930 createJar(bundleDir, origin);
931 }
932 } catch (IOException e) {
933 throw new RuntimeException("Cannot process " + duDir, e);
934 }
935
936 }
937
938 /** Process sources in Eclipse format. */
939 void processEclipseSourceJar(Path file, Path targetBase) throws IOException {
940 try {
941 A2Origin origin = new A2Origin();
942 Path bundleDir;
943 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
944 Manifest manifest = jarIn.getManifest();
945
946 String[] relatedBundle = manifest.getMainAttributes().getValue(ECLIPSE_SOURCE_BUNDLE.toString())
947 .split(";");
948 String version = relatedBundle[1].substring("version=\"".length());
949 version = version.substring(0, version.length() - 1);
950 NameVersion nameVersion = new NameVersion(relatedBundle[0], version);
951 bundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
952
953 Path sourceDir = separateSources ? bundleDir.getParent().resolve(bundleDir.toString() + ".src")
954 : bundleDir.resolve("OSGI-OPT/src");
955
956 Files.createDirectories(sourceDir);
957 JarEntry entry;
958 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
959 if (entry.isDirectory())
960 continue entries;
961 if (entry.getName().startsWith("META-INF"))// skip META-INF entries
962 continue entries;
963 Path target = sourceDir.resolve(entry.getName());
964 Files.createDirectories(target.getParent());
965 Files.copy(jarIn, target);
966 logger.log(TRACE, () -> "Copied source " + target);
967 }
968
969 // write the changes
970 if (separateSources) {
971 origin.appendChanges(sourceDir);
972 } else {
973 origin.added.add("source code under OSGI-OPT/src");
974 origin.appendChanges(bundleDir);
975 }
976 }
977 } catch (IOException e) {
978 throw new IllegalStateException("Cannot process " + file, e);
979 }
980 }
981
982 /*
983 * COMMON PROCESSING
984 */
985 /** Normalise a single (that is, non-merged) bundle. */
986 Path processBundleJar(Path file, Path targetBase, Map<String, String> entries, A2Origin origin) throws IOException {
987 // boolean embed = Boolean.parseBoolean(entries.getOrDefault(ARGEO_ORIGIN_EMBED.toString(), "false").toString());
988 boolean doNotModify = Boolean
989 .parseBoolean(entries.getOrDefault(ManifestHeader.ARGEO_DO_NOT_MODIFY.toString(), "false").toString());
990 NameVersion nameVersion;
991 Path bundleDir;
992 // singleton
993 boolean isSingleton = false;
994 Manifest manifest;
995 Manifest sourceManifest;
996 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
997 sourceManifest = jarIn.getManifest();
998 manifest = sourceManifest != null ? new Manifest(sourceManifest) : new Manifest();
999
1000 String rawSourceSymbolicName = manifest.getMainAttributes().getValue(BUNDLE_SYMBOLICNAME.toString());
1001 if (rawSourceSymbolicName != null) {
1002 // make sure there is no directive
1003 String[] arr = rawSourceSymbolicName.split(";");
1004 for (int i = 1; i < arr.length; i++) {
1005 if (arr[i].trim().equals("singleton:=true"))
1006 isSingleton = true;
1007 logger.log(DEBUG, file.getFileName() + " is a singleton");
1008 }
1009 }
1010 // remove problematic entries in MANIFEST
1011 manifest.getEntries().clear();
1012
1013 String ourSymbolicName = entries.get(BUNDLE_SYMBOLICNAME.toString());
1014 String ourVersion = entries.get(BUNDLE_VERSION.toString());
1015
1016 if (ourSymbolicName != null && ourVersion != null) {
1017 nameVersion = new NameVersion(ourSymbolicName, ourVersion);
1018 } else {
1019 nameVersion = nameVersionFromManifest(manifest);
1020 if (ourVersion != null && !nameVersion.getVersion().equals(ourVersion)) {
1021 logger.log(WARNING,
1022 "Original version is " + nameVersion.getVersion() + " while new version is " + ourVersion);
1023 entries.put(BUNDLE_VERSION.toString(), ourVersion);
1024 }
1025 if (ourSymbolicName != null) {
1026 // we always force our symbolic name
1027 nameVersion.setName(ourSymbolicName);
1028 }
1029 }
1030 bundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
1031
1032 // copy original MANIFEST
1033 if (sourceManifest != null) {
1034 Path originalManifest = bundleDir.resolve(ARGEO_ORIGIN).resolve("MANIFEST.MF");
1035 Files.createDirectories(originalManifest.getParent());
1036 try (OutputStream out = Files.newOutputStream(originalManifest)) {
1037 sourceManifest.write(out);
1038 }
1039 origin.moved.add("original MANIFEST to " + bundleDir.relativize(originalManifest));
1040 }
1041
1042 // force Java 9 module name
1043 entries.put(ManifestHeader.AUTOMATIC_MODULE_NAME.toString(), nameVersion.getName());
1044
1045 boolean isNative = false;
1046 String os = null;
1047 String arch = null;
1048 if (bundleDir.startsWith(a2LibBase)) {
1049 isNative = true;
1050 Path libRelativePath = a2LibBase.relativize(bundleDir);
1051 os = libRelativePath.getName(0).toString();
1052 arch = libRelativePath.getName(1).toString();
1053 }
1054
1055 // if (!embed) {
1056 // copy entries
1057 JarEntry entry;
1058 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
1059 if (entry.isDirectory())
1060 continue entries;
1061 if (!doNotModify) {
1062 if (entry.getName().endsWith(".RSA") || entry.getName().endsWith(".DSA")
1063 || entry.getName().endsWith(".SF")) {
1064 origin.deleted.add("cryptographic signatures");
1065 continue entries;
1066 }
1067 if (entry.getName().endsWith("module-info.class")) { // skip Java 9 module info
1068 origin.deleted.add("Java module information (module-info.class)");
1069 continue entries;
1070 }
1071 if (entry.getName().startsWith("META-INF/versions/")) { // skip multi-version
1072 origin.deleted.add("additional Java versions (META-INF/versions)");
1073 continue entries;
1074 }
1075 if (entry.getName().startsWith("META-INF/maven/")) {
1076 origin.deleted.add("Maven information (META-INF/maven)");
1077 continue entries;
1078 }
1079 // skip file system providers as they cause issues with native image
1080 if (entry.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider")) {
1081 origin.deleted
1082 .add("file system providers (META-INF/services/java.nio.file.spi.FileSystemProvider)");
1083 continue entries;
1084 }
1085 }
1086 if (entry.getName().startsWith("OSGI-OPT/src/")) { // skip embedded sources
1087 origin.deleted.add("embedded sources");
1088 continue entries;
1089 }
1090 Path target = bundleDir.resolve(entry.getName());
1091 Files.createDirectories(target.getParent());
1092 Files.copy(jarIn, target);
1093
1094 // native libraries
1095 if (isNative && (entry.getName().endsWith(".so") || entry.getName().endsWith(".dll")
1096 || entry.getName().endsWith(".jnilib"))) {
1097 Path categoryDir = bundleDir.getParent();
1098 boolean copyDll = false;
1099 Path targetDll = categoryDir.resolve(bundleDir.relativize(target));
1100 if (nameVersion.getName().equals("com.sun.jna")) {
1101 if (arch.equals("x86_64"))
1102 arch = "x86-64";
1103 if (os.equals("macosx"))
1104 os = "darwin";
1105 if (target.getParent().getFileName().toString().equals(os + "-" + arch)) {
1106 copyDll = true;
1107 }
1108 targetDll = categoryDir.resolve(target.getFileName());
1109 } else {
1110 copyDll = true;
1111 }
1112 if (copyDll) {
1113 Files.createDirectories(targetDll.getParent());
1114 if (Files.exists(targetDll))
1115 Files.delete(targetDll);
1116 Files.copy(target, targetDll);
1117 }
1118 Files.delete(target);
1119 origin.deleted.add(bundleDir.relativize(target).toString());
1120 }
1121 logger.log(TRACE, () -> "Copied " + target);
1122 // }
1123 }
1124 }
1125
1126 // copy MANIFEST
1127 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
1128 Files.createDirectories(manifestPath.getParent());
1129
1130 if (isSingleton && entries.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
1131 entries.put(BUNDLE_SYMBOLICNAME.toString(),
1132 entries.get(BUNDLE_SYMBOLICNAME.toString()) + ";singleton:=true");
1133 }
1134
1135 // if (embed) {// copy embedded jar
1136 // Files.copy(file, bundleDir.resolve(file.getFileName()));
1137 // entries.put(ManifestHeader.BUNDLE_CLASSPATH.toString(), file.getFileName().toString());
1138 // }
1139
1140 // Final MANIFEST decisions
1141 // We also check the original OSGi metadata and compare with our changes
1142 for (String key : entries.keySet()) {
1143 String value = entries.get(key);
1144 String previousValue = manifest.getMainAttributes().getValue(key);
1145 boolean wasDifferent = previousValue != null && !previousValue.equals(value);
1146 boolean keepPrevious = false;
1147 if (wasDifferent) {
1148 if (SPDX_LICENSE_IDENTIFIER.toString().equals(key) && previousValue != null)
1149 keepPrevious = true;
1150 else if (BUNDLE_VERSION.toString().equals(key) && wasDifferent)
1151 if (previousValue.equals(value + ".0")) // typically a Maven first release
1152 keepPrevious = true;
1153
1154 if (keepPrevious) {
1155 if (logger.isLoggable(DEBUG))
1156 logger.log(DEBUG, file.getFileName() + ": " + key + " was NOT modified, value kept is "
1157 + previousValue + ", not overriden with " + value);
1158 value = previousValue;
1159 }
1160 }
1161
1162 manifest.getMainAttributes().putValue(key, value);
1163 if (wasDifferent && !keepPrevious) {
1164 if (IMPORT_PACKAGE.toString().equals(key) || EXPORT_PACKAGE.toString().equals(key))
1165 logger.log(TRACE, () -> file.getFileName() + ": " + key + " was modified");
1166 else if (BUNDLE_SYMBOLICNAME.toString().equals(key) || AUTOMATIC_MODULE_NAME.toString().equals(key))
1167 logger.log(DEBUG,
1168 file.getFileName() + ": " + key + " was " + previousValue + ", overridden with " + value);
1169 else
1170 logger.log(WARNING,
1171 file.getFileName() + ": " + key + " was " + previousValue + ", overridden with " + value);
1172 origin.modified.add("MANIFEST header " + key);
1173 }
1174
1175 // !! hack to remove unresolvable
1176 if (key.equals("Provide-Capability") || key.equals("Require-Capability"))
1177 if (nameVersion.getName().equals("osgi.core") || nameVersion.getName().equals("osgi.cmpn")) {
1178 manifest.getMainAttributes().remove(key);
1179 origin.deleted.add("MANIFEST header " + key);
1180 }
1181 }
1182
1183 // de-pollute MANIFEST
1184 for (Iterator<Map.Entry<Object, Object>> manifestEntries = manifest.getMainAttributes().entrySet()
1185 .iterator(); manifestEntries.hasNext();) {
1186 Map.Entry<Object, Object> manifestEntry = manifestEntries.next();
1187 switch (manifestEntry.getKey().toString()) {
1188 case "Archiver-Version":
1189 case "Build-By":
1190 case "Created-By":
1191 case "Originally-Created-By":
1192 case "Tool":
1193 case "Bnd-LastModified":
1194 manifestEntries.remove();
1195 origin.deleted.add("MANIFEST header " + manifestEntry.getKey());
1196 break;
1197 default:
1198 if (sourceManifest != null && !sourceManifest.getMainAttributes().containsKey(manifestEntry.getKey()))
1199 origin.added.add("MANIFEST header " + manifestEntry.getKey());
1200 }
1201 }
1202
1203 processLicense(bundleDir, manifest);
1204
1205 origin.modified.add("MANIFEST (META-INF/MANIFEST.MF)");
1206 // write the MANIFEST
1207 try (OutputStream out = Files.newOutputStream(manifestPath)) {
1208 manifest.write(out);
1209 }
1210 return bundleDir;
1211 }
1212
1213 /** Process SPDX license identifier. */
1214 void processLicense(Path bundleDir, Manifest manifest) {
1215 String spdxLicenceId = manifest.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER.toString());
1216 String bundleLicense = manifest.getMainAttributes().getValue(BUNDLE_LICENSE.toString());
1217 if (spdxLicenceId == null) {
1218 logger.log(ERROR, bundleDir.getFileName() + ": " + SPDX_LICENSE_IDENTIFIER + " not available, "
1219 + BUNDLE_LICENSE + " is " + bundleLicense);
1220 } else {
1221 // only use the first licensing option
1222 int orIndex = spdxLicenceId.indexOf(" OR ");
1223 if (orIndex >= 0)
1224 spdxLicenceId = spdxLicenceId.substring(0, orIndex).trim();
1225
1226 String bundleDirName = bundleDir.getFileName().toString();
1227 // force licenses of some well-known components
1228 // even if we say otherwise (typically because from an Eclipse archive)
1229 if (bundleDirName.startsWith("org.apache."))
1230 spdxLicenceId = "Apache-2.0";
1231 if (bundleDirName.startsWith("com.sun.jna."))
1232 spdxLicenceId = "Apache-2.0";
1233 if (bundleDirName.startsWith("com.ibm.icu."))
1234 spdxLicenceId = "ICU";
1235 if (bundleDirName.startsWith("javax.annotation."))
1236 spdxLicenceId = "GPL-2.0-only WITH Classpath-exception-2.0";
1237 if (bundleDirName.startsWith("javax.inject."))
1238 spdxLicenceId = "Apache-2.0";
1239 if (bundleDirName.startsWith("org.osgi."))
1240 spdxLicenceId = "Apache-2.0";
1241
1242 manifest.getMainAttributes().putValue(SPDX_LICENSE_IDENTIFIER.toString(), spdxLicenceId);
1243 if (!licensesUsed.containsKey(spdxLicenceId))
1244 licensesUsed.put(spdxLicenceId, new TreeSet<>());
1245 licensesUsed.get(spdxLicenceId).add(bundleDir.getParent().getFileName() + "/" + bundleDir.getFileName());
1246 }
1247 }
1248
1249 /*
1250 * UTILITIES
1251 */
1252 /** Recursively deletes a directory. */
1253 static void deleteDirectory(Path path) throws IOException {
1254 if (!Files.exists(path))
1255 return;
1256 Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
1257 @Override
1258 public FileVisitResult postVisitDirectory(Path directory, IOException e) throws IOException {
1259 if (e != null)
1260 throw e;
1261 Files.delete(directory);
1262 return CONTINUE;
1263 }
1264
1265 @Override
1266 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1267 Files.delete(file);
1268 return CONTINUE;
1269 }
1270 });
1271 }
1272
1273 /** Extract name/version from a MANIFEST. */
1274 NameVersion nameVersionFromManifest(Manifest manifest) {
1275 Attributes attrs = manifest.getMainAttributes();
1276 // symbolic name
1277 String symbolicName = attrs.getValue(ManifestHeader.BUNDLE_SYMBOLICNAME.toString());
1278 if (symbolicName == null)
1279 return null;
1280 // make sure there is no directive
1281 symbolicName = symbolicName.split(";")[0];
1282
1283 String version = attrs.getValue(ManifestHeader.BUNDLE_VERSION.toString());
1284 return new NameVersion(symbolicName, version);
1285 }
1286
1287 /** Try to download from an URI. */
1288 Path tryDownloadArchive(String uri, Path dir) throws IOException {
1289 // find mirror
1290 List<String> urlBases = null;
1291 String uriPrefix = null;
1292 uriPrefixes: for (String uriPref : mirrors.keySet()) {
1293 if (uri.startsWith(uriPref)) {
1294 if (mirrors.get(uriPref).size() > 0) {
1295 urlBases = mirrors.get(uriPref);
1296 uriPrefix = uriPref;
1297 break uriPrefixes;
1298 }
1299 }
1300 }
1301 if (urlBases == null)
1302 try {
1303 return downloadArchive(new URL(uri), dir);
1304 } catch (FileNotFoundException e) {
1305 throw new FileNotFoundException("Cannot find " + uri);
1306 }
1307
1308 // try to download
1309 for (String urlBase : urlBases) {
1310 String relativePath = uri.substring(uriPrefix.length());
1311 URL url = new URL(urlBase + relativePath);
1312 try {
1313 return downloadArchive(url, dir);
1314 } catch (FileNotFoundException e) {
1315 logger.log(WARNING, "Cannot download " + url + ", trying another mirror");
1316 }
1317 }
1318 throw new FileNotFoundException("Cannot find " + uri);
1319 }
1320
1321 /**
1322 * Effectively download. Synchronised in order to avoid downloading twice in
1323 * parallel.
1324 */
1325 synchronized Path downloadArchive(URL url, Path dir) throws IOException {
1326 return download(url, dir, (String) null);
1327 }
1328
1329 /** Effectively download. */
1330 Path download(URL url, Path dir, String name) throws IOException {
1331
1332 Path dest;
1333 if (name == null) {
1334 // We use also use parent directory in case the archive itself has a fixed name
1335 String[] segments = url.getPath().split("/");
1336 name = segments.length > 1 ? segments[segments.length - 2] + '-' + segments[segments.length - 1]
1337 : segments[segments.length - 1];
1338 }
1339
1340 dest = dir.resolve(name);
1341 if (Files.exists(dest)) {
1342 logger.log(TRACE, () -> "File " + dest + " already exists for " + url + ", not downloading again");
1343 return dest;
1344 } else {
1345 Files.createDirectories(dest.getParent());
1346 }
1347
1348 try (InputStream in = url.openStream()) {
1349 Files.copy(in, dest);
1350 logger.log(DEBUG, () -> "Downloaded " + dest + " from " + url);
1351 }
1352 return dest;
1353 }
1354
1355 /** Create a JAR file from a directory. */
1356 Path createJar(Path bundleDir, A2Origin origin) throws IOException {
1357 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
1358 Manifest manifest;
1359 try (InputStream in = Files.newInputStream(manifestPath)) {
1360 manifest = new Manifest(in);
1361 }
1362 // legal requirements
1363 origin.appendChanges(bundleDir);
1364 createReadMe(bundleDir, manifest);
1365
1366 // create the jar
1367 Path jarPath = bundleDir.getParent().resolve(bundleDir.getFileName() + ".jar");
1368 try (JarOutputStream jarOut = new JarOutputStream(Files.newOutputStream(jarPath), manifest)) {
1369 jarOut.setLevel(Deflater.DEFAULT_COMPRESSION);
1370 Files.walkFileTree(bundleDir, new SimpleFileVisitor<Path>() {
1371
1372 @Override
1373 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1374 if (file.getFileName().toString().equals("MANIFEST.MF"))
1375 return super.visitFile(file, attrs);
1376 JarEntry entry = new JarEntry(
1377 bundleDir.relativize(file).toString().replace(File.separatorChar, '/'));
1378 jarOut.putNextEntry(entry);
1379 Files.copy(file, jarOut);
1380 return super.visitFile(file, attrs);
1381 }
1382
1383 });
1384 }
1385 deleteDirectory(bundleDir);
1386
1387 if (separateSources)
1388 createSourceJar(bundleDir, manifest, null);
1389
1390 return jarPath;
1391 }
1392
1393 /** Package sources separately, in the Eclipse-SourceBundle format. */
1394 void createSourceJar(Path bundleDir, Manifest manifest, Properties props) throws IOException {
1395 boolean unmodified = props != null;
1396 Path bundleCategoryDir = bundleDir.getParent();
1397 Path sourceDir = bundleCategoryDir.resolve(bundleDir.toString() + ".src");
1398 if (!Files.exists(sourceDir)) {
1399 logger.log(WARNING, sourceDir + " does not exist, skipping...");
1400 return;
1401 }
1402
1403 Path relPath = a2Base.relativize(bundleCategoryDir);
1404 Path srcCategoryDir = a2SrcBase.resolve(relPath);
1405 Path srcJarP = srcCategoryDir.resolve(sourceDir.getFileName() + ".jar");
1406 Files.createDirectories(srcJarP.getParent());
1407
1408 String bundleSymbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1409 // in case there are additional directives
1410 bundleSymbolicName = bundleSymbolicName.split(";")[0];
1411 Manifest srcManifest = new Manifest();
1412 srcManifest.getMainAttributes().put(MANIFEST_VERSION, "1.0");
1413 BUNDLE_SYMBOLICNAME.put(srcManifest, bundleSymbolicName + ".src");
1414 BUNDLE_VERSION.put(srcManifest, BUNDLE_VERSION.get(manifest));
1415 ECLIPSE_SOURCE_BUNDLE.put(srcManifest,
1416 bundleSymbolicName + ";version=\"" + BUNDLE_VERSION.get(manifest) + "\"");
1417
1418 // metadata
1419 createReadMe(sourceDir, unmodified ? props : manifest);
1420 // create jar
1421 try (JarOutputStream srcJarOut = new JarOutputStream(Files.newOutputStream(srcJarP), srcManifest)) {
1422 // srcJarOut.setLevel(Deflater.BEST_COMPRESSION);
1423 Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
1424
1425 @Override
1426 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1427 if (file.getFileName().toString().equals("MANIFEST.MF"))
1428 return super.visitFile(file, attrs);
1429 JarEntry entry = new JarEntry(
1430 sourceDir.relativize(file).toString().replace(File.separatorChar, '/'));
1431 srcJarOut.putNextEntry(entry);
1432 Files.copy(file, srcJarOut);
1433 return super.visitFile(file, attrs);
1434 }
1435
1436 });
1437 }
1438 deleteDirectory(sourceDir);
1439 }
1440
1441 /**
1442 * Generate a readme clarifying and prominently notifying of the repackaging and
1443 * modifications.
1444 */
1445 void createReadMe(Path jarDir, Object mapping) throws IOException {
1446 // write repackaged README
1447 try (BufferedWriter writer = Files.newBufferedWriter(jarDir.resolve(README_REPACKAGED))) {
1448 boolean merged = ARGEO_ORIGIN_M2_MERGE.get(mapping) != null;
1449 if (merged)
1450 writer.append("This component is a merging of third party components"
1451 + " in order to comply with A2 packaging standards.\n");
1452 else
1453 writer.append("This component is a repackaging of a third party component"
1454 + " in order to comply with A2 packaging standards.\n");
1455
1456 // license
1457 String spdxLicenseId = SPDX_LICENSE_IDENTIFIER.get(mapping);
1458 if (spdxLicenseId == null)
1459 throw new IllegalStateException("An SPDX license id must have beend defined at this stage.");
1460 writer.append("\nIt is redistributed under the following license:\n\n");
1461 writer.append("SPDX-Identifier: " + spdxLicenseId + "\n\n");
1462
1463 if (!spdxLicenseId.startsWith("LicenseRef")) {// standard
1464 int withIndex = spdxLicenseId.indexOf(" WITH ");
1465 if (withIndex >= 0) {
1466 String simpleId = spdxLicenseId.substring(0, withIndex).trim();
1467 String exception = spdxLicenseId.substring(withIndex + " WITH ".length());
1468 writer.append("which are available here: https://spdx.org/licenses/" + simpleId
1469 + "\nand here: https://spdx.org/licenses/" + exception + "\n");
1470 } else {
1471 writer.append("which is available here: https://spdx.org/licenses/" + spdxLicenseId + "\n");
1472 }
1473 } else {
1474 String url = BUNDLE_LICENSE.get(mapping);
1475 if (url != null) {
1476 writer.write("which is available here: " + url + "\n");
1477 } else {
1478 logger.log(ERROR, "No licence URL for " + jarDir);
1479 }
1480 }
1481
1482 // origin
1483 String originDesc = ARGEO_ORIGIN_URI.get(mapping);
1484 if (originDesc != null)
1485 writer.append("\nThe original component comes from " + originDesc + ".\n");
1486 else {
1487 String m2Repo = ARGEO_ORIGIN_M2_REPO.get(mapping);
1488 originDesc = ARGEO_ORIGIN_M2.get(mapping);
1489 if (originDesc != null)
1490 writer.append("\nThe original component has M2 coordinates:\n" + originDesc.replace(',', '\n')
1491 + "\n" + (m2Repo != null ? "\nin M2 repository " + m2Repo + "\n" : ""));
1492 else
1493 logger.log(ERROR, "Cannot find origin information in " + jarDir);
1494 }
1495 String originSources = ARGEO_ORIGIN_SOURCES_URI.get(mapping);
1496 if (originSources != null)
1497 writer.append("\nThe original sources come from " + originSources + ".\n");
1498
1499 if (Files.exists(jarDir.resolve(CHANGES)))
1500 writer.append("\nA detailed list of changes is available under " + CHANGES + ".\n");
1501
1502 if (!jarDir.getFileName().toString().endsWith(".src")) {// binary archive
1503 if (separateSources)
1504 writer.append("Corresponding sources are available in the related archive named "
1505 + jarDir.toString() + ".src.jar.\n");
1506 else
1507 writer.append("Corresponding sources are available under OSGI-OPT/src.\n");
1508 }
1509 }
1510 }
1511
1512 /**
1513 * Gathers modifications performed on the original binaries and sources,
1514 * especially in order to comply with their license requirements.
1515 */
1516 class A2Origin {
1517 A2Origin() {
1518
1519 }
1520
1521 Set<String> modified = new TreeSet<>();
1522 Set<String> deleted = new TreeSet<>();
1523 Set<String> added = new TreeSet<>();
1524 Set<String> moved = new TreeSet<>();
1525
1526 /** Append changes to the A2-ORIGIN/changes file. */
1527 void appendChanges(Path baseDirectory) throws IOException {
1528 if (modified.isEmpty() && deleted.isEmpty() && added.isEmpty() && moved.isEmpty())
1529 return; // no changes
1530 Path changesFile = baseDirectory.resolve(CHANGES);
1531 Files.createDirectories(changesFile.getParent());
1532 try (BufferedWriter writer = Files.newBufferedWriter(changesFile, APPEND, CREATE)) {
1533 for (String msg : added)
1534 writer.write("- Added " + msg + ".\n");
1535 for (String msg : modified)
1536 writer.write("- Modified " + msg + ".\n");
1537 for (String msg : moved)
1538 writer.write("- Moved " + msg + ".\n");
1539 for (String msg : deleted)
1540 writer.write("- Deleted " + msg + ".\n");
1541 }
1542 }
1543 }
1544 }
1545
1546 /** Simple representation of an M2 artifact. */
1547 class M2Artifact extends CategoryNameVersion {
1548 private String classifier;
1549
1550 M2Artifact(String m2coordinates) {
1551 this(m2coordinates, null);
1552 }
1553
1554 M2Artifact(String m2coordinates, String classifier) {
1555 String[] parts = m2coordinates.split(":");
1556 setCategory(parts[0]);
1557 setName(parts[1]);
1558 if (parts.length > 2) {
1559 setVersion(parts[2]);
1560 }
1561 this.classifier = classifier;
1562 }
1563
1564 String getGroupId() {
1565 return super.getCategory();
1566 }
1567
1568 String getArtifactId() {
1569 return super.getName();
1570 }
1571
1572 String toM2Coordinates() {
1573 return getCategory() + ":" + getName() + (getVersion() != null ? ":" + getVersion() : "");
1574 }
1575
1576 String getClassifier() {
1577 return classifier != null ? classifier : "";
1578 }
1579
1580 String getExtension() {
1581 return "jar";
1582 }
1583 }
1584
1585 /** Utilities around Maven (conventions based). */
1586 class M2ConventionsUtils {
1587 final static String MAVEN_CENTRAL_BASE_URL = "https://repo1.maven.org/maven2/";
1588
1589 /** The file name of this artifact when stored */
1590 static String artifactFileName(M2Artifact artifact) {
1591 return artifact.getArtifactId() + '-' + artifact.getVersion()
1592 + (artifact.getClassifier().equals("") ? "" : '-' + artifact.getClassifier()) + '.'
1593 + artifact.getExtension();
1594 }
1595
1596 /** Absolute path to the file */
1597 static String artifactPath(String artifactBasePath, M2Artifact artifact) {
1598 return artifactParentPath(artifactBasePath, artifact) + '/' + artifactFileName(artifact);
1599 }
1600
1601 /** Absolute path to the file */
1602 static String artifactUrl(String repoUrl, M2Artifact artifact) {
1603 if (repoUrl.endsWith("/"))
1604 return repoUrl + artifactPath("/", artifact).substring(1);
1605 else
1606 return repoUrl + artifactPath("/", artifact);
1607 }
1608
1609 /** Absolute path to the file */
1610 static URL mavenRepoUrl(String repoBase, M2Artifact artifact) {
1611 String url = artifactUrl(repoBase == null ? MAVEN_CENTRAL_BASE_URL : repoBase, artifact);
1612 try {
1613 return new URL(url);
1614 } catch (MalformedURLException e) {
1615 // it should not happen
1616 throw new IllegalStateException(e);
1617 }
1618 }
1619
1620 /** Absolute path to the directories where the files will be stored */
1621 static String artifactParentPath(String artifactBasePath, M2Artifact artifact) {
1622 return artifactBasePath + (artifactBasePath.endsWith("/") || artifactBasePath.equals("") ? "" : "/")
1623 + artifactParentPath(artifact);
1624 }
1625
1626 /** Relative path to the directories where the files will be stored */
1627 static String artifactParentPath(M2Artifact artifact) {
1628 return artifact.getGroupId().replace('.', '/') + '/' + artifact.getArtifactId() + '/' + artifact.getVersion();
1629 }
1630
1631 /** Singleton */
1632 private M2ConventionsUtils() {
1633 }
1634 }
1635
1636 /** Combination of a category, a name and a version. */
1637 class CategoryNameVersion extends NameVersion {
1638 private String category;
1639
1640 CategoryNameVersion() {
1641 }
1642
1643 CategoryNameVersion(String category, String name, String version) {
1644 super(name, version);
1645 this.category = category;
1646 }
1647
1648 CategoryNameVersion(String category, NameVersion nameVersion) {
1649 super(nameVersion);
1650 this.category = category;
1651 }
1652
1653 String getCategory() {
1654 return category;
1655 }
1656
1657 void setCategory(String category) {
1658 this.category = category;
1659 }
1660
1661 @Override
1662 public String toString() {
1663 return category + ":" + super.toString();
1664 }
1665
1666 }
1667
1668 /** Combination of a name and a version. */
1669 class NameVersion implements Comparable<NameVersion> {
1670 private String name;
1671 private String version;
1672
1673 NameVersion() {
1674 }
1675
1676 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1677 NameVersion(String nameVersion) {
1678 int index = nameVersion.indexOf(";version=");
1679 if (index < 0) {
1680 setName(nameVersion);
1681 setVersion(null);
1682 } else {
1683 setName(nameVersion.substring(0, index));
1684 setVersion(nameVersion.substring(index + ";version=".length()));
1685 }
1686 }
1687
1688 NameVersion(String name, String version) {
1689 this.name = name;
1690 this.version = version;
1691 }
1692
1693 NameVersion(NameVersion nameVersion) {
1694 this.name = nameVersion.getName();
1695 this.version = nameVersion.getVersion();
1696 }
1697
1698 String getName() {
1699 return name;
1700 }
1701
1702 void setName(String name) {
1703 this.name = name;
1704 }
1705
1706 String getVersion() {
1707 return version;
1708 }
1709
1710 void setVersion(String version) {
1711 this.version = version;
1712 }
1713
1714 String getBranch() {
1715 String[] parts = getVersion().split("\\.");
1716 if (parts.length < 2)
1717 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1718 return parts[0] + "." + parts[1];
1719 }
1720
1721 @Override
1722 public boolean equals(Object obj) {
1723 if (obj instanceof NameVersion) {
1724 NameVersion nameVersion = (NameVersion) obj;
1725 return name.equals(nameVersion.getName()) && version.equals(nameVersion.getVersion());
1726 } else
1727 return false;
1728 }
1729
1730 @Override
1731 public int hashCode() {
1732 return name.hashCode();
1733 }
1734
1735 @Override
1736 public String toString() {
1737 return name + ":" + version;
1738 }
1739
1740 public int compareTo(NameVersion o) {
1741 if (o.getName().equals(name))
1742 return version.compareTo(o.getVersion());
1743 else
1744 return name.compareTo(o.getName());
1745 }
1746 }