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