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