]> git.argeo.org Git - cc0/argeo-build.git/blob - src/org/argeo/build/Repackage.java
65317e5ad5b98ff65a951b87ff1f67f9d75bf005
[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.util.jar.Attributes.Name.MANIFEST_VERSION;
10 import static org.argeo.build.Repackage.ManifestConstants.ARGEO_ORIGIN_M2;
11 import static org.argeo.build.Repackage.ManifestConstants.ARGEO_ORIGIN_M2_REPO;
12 import static org.argeo.build.Repackage.ManifestConstants.BUNDLE_LICENSE;
13 import static org.argeo.build.Repackage.ManifestConstants.BUNDLE_SYMBOLICNAME;
14 import static org.argeo.build.Repackage.ManifestConstants.BUNDLE_VERSION;
15 import static org.argeo.build.Repackage.ManifestConstants.ECLIPSE_SOURCE_BUNDLE;
16 import static org.argeo.build.Repackage.ManifestConstants.EXPORT_PACKAGE;
17 import static org.argeo.build.Repackage.ManifestConstants.IMPORT_PACKAGE;
18 import static org.argeo.build.Repackage.ManifestConstants.SPDX_LICENSE_IDENTIFIER;
19
20 import java.io.File;
21 import java.io.FileNotFoundException;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.OutputStream;
25 import java.lang.System.Logger;
26 import java.net.MalformedURLException;
27 import java.net.URL;
28 import java.nio.charset.StandardCharsets;
29 import java.nio.file.DirectoryStream;
30 import java.nio.file.FileSystem;
31 import java.nio.file.FileSystems;
32 import java.nio.file.FileVisitResult;
33 import java.nio.file.Files;
34 import java.nio.file.Path;
35 import java.nio.file.PathMatcher;
36 import java.nio.file.Paths;
37 import java.nio.file.SimpleFileVisitor;
38 import java.nio.file.StandardOpenOption;
39 import java.nio.file.attribute.BasicFileAttributes;
40 import java.util.ArrayList;
41 import java.util.HashMap;
42 import java.util.Iterator;
43 import java.util.List;
44 import java.util.Map;
45 import java.util.Objects;
46 import java.util.Properties;
47 import java.util.Set;
48 import java.util.TreeMap;
49 import java.util.TreeSet;
50 import java.util.concurrent.CompletableFuture;
51 import java.util.jar.Attributes;
52 import java.util.jar.JarEntry;
53 import java.util.jar.JarInputStream;
54 import java.util.jar.JarOutputStream;
55 import java.util.jar.Manifest;
56 import java.util.zip.Deflater;
57
58 import aQute.bnd.osgi.Analyzer;
59 import aQute.bnd.osgi.Jar;
60
61 /**
62 * Simple tool repackaging existing jar files into OSGi bundles in an A2
63 * repository.
64 */
65 public class Repackage {
66 final static Logger logger = System.getLogger(Repackage.class.getName());
67
68 /**
69 * Environment variable on whether sources should be packaged separately or
70 * integrated in the bundles.
71 */
72 final static String ENV_SOURCE_BUNDLES = "SOURCE_BUNDLES";
73
74 /** Whethere repackaging should run in parallel or sequentially. */
75 final static boolean parallel = true;
76
77 // cache
78 final static Map<String, Set<String>> licensesUsed = new TreeMap<>();
79
80 /** Main entry point. */
81 public static void main(String[] args) {
82 if (args.length < 2) {
83 System.err.println("Usage: <path to a2 output dir> <category1> <category2> ...");
84 System.exit(1);
85 }
86 Path a2Base = Paths.get(args[0]).toAbsolutePath().normalize();
87 Path descriptorsBase = Paths.get(".").toAbsolutePath().normalize();
88 Repackage factory = new Repackage(a2Base, descriptorsBase);
89
90 List<CompletableFuture<Void>> toDos = new ArrayList<>();
91 for (int i = 1; i < args.length; i++) {
92 Path p = Paths.get(args[i]);
93 if (parallel)
94 toDos.add(CompletableFuture.runAsync(() -> factory.processCategory(p)));
95 else
96 factory.processCategory(p);
97 }
98 CompletableFuture.allOf(toDos.toArray(new CompletableFuture[toDos.size()])).join();
99
100 logger.log(INFO, "# License summary:");
101 for (String licenseId : licensesUsed.keySet())
102 for (String name : licensesUsed.get(licenseId))
103 logger.log(INFO, licenseId + "\t" + name);
104 }
105
106 final static String COMMON_BND = "common.bnd";
107 final static String MERGE_BND = "merge.bnd";
108
109 /** Directory where to download archives */
110 Path originBase;
111 /** Directory where to download Maven artifacts */
112 Path mavenBase;
113
114 /** A2 repository base for binary bundles */
115 Path a2Base;
116 /** A2 repository base for source bundles */
117 Path a2SrcBase;
118 /** A2 base for native components */
119 Path a2LibBase;
120 /** Location of the descriptors driving the packaging */
121 Path descriptorsBase;
122 /** URIs of archives to download */
123 Properties uris = new Properties();
124 /** Mirrors for archive download. Key is URI prefix, value list of base URLs */
125 Map<String, List<String>> mirrors = new HashMap<String, List<String>>();
126
127 /** Whether sources should be packaged separately */
128 final boolean sourceBundles;
129
130 /** Constructor initialises the various variables */
131 public Repackage(Path a2Base, Path descriptorsBase) {
132 sourceBundles = Boolean.parseBoolean(System.getenv(ENV_SOURCE_BUNDLES));
133 if (sourceBundles)
134 logger.log(INFO, "Sources will be packaged separately");
135
136 Objects.requireNonNull(a2Base);
137 Objects.requireNonNull(descriptorsBase);
138 this.originBase = Paths.get(System.getProperty("user.home"), ".cache", "argeo/build/origin");
139 this.mavenBase = Paths.get(System.getProperty("user.home"), ".m2", "repository");
140
141 // TODO define and use a build base
142 this.a2Base = a2Base;
143 this.a2SrcBase = a2Base.getParent().resolve(a2Base.getFileName() + ".src");
144 this.a2LibBase = a2Base.resolve("lib");
145 this.descriptorsBase = descriptorsBase;
146 if (!Files.exists(this.descriptorsBase))
147 throw new IllegalArgumentException(this.descriptorsBase + " does not exist");
148
149 // URIs mapping
150 Path urisPath = this.descriptorsBase.resolve("uris.properties");
151 if (Files.exists(urisPath)) {
152 try (InputStream in = Files.newInputStream(urisPath)) {
153 uris.load(in);
154 } catch (IOException e) {
155 throw new IllegalStateException("Cannot load " + urisPath, e);
156 }
157 }
158
159 // Eclipse mirrors
160 Path eclipseMirrorsPath = this.descriptorsBase.resolve("eclipse.mirrors.txt");
161 List<String> eclipseMirrors = new ArrayList<>();
162 if (Files.exists(eclipseMirrorsPath)) {
163 try {
164 eclipseMirrors = Files.readAllLines(eclipseMirrorsPath, StandardCharsets.UTF_8);
165 } catch (IOException e) {
166 throw new IllegalStateException("Cannot load " + eclipseMirrorsPath, e);
167 }
168 for (Iterator<String> it = eclipseMirrors.iterator(); it.hasNext();) {
169 String value = it.next();
170 if (value.strip().equals(""))
171 it.remove();
172 }
173 }
174 mirrors.put("http://www.eclipse.org/downloads", eclipseMirrors);
175 }
176
177 /*
178 * MAVEN ORIGIN
179 */
180 /** Process a whole category/group id. */
181 void processCategory(Path categoryRelativePath) {
182 try {
183 Path targetCategoryBase = descriptorsBase.resolve(categoryRelativePath);
184 DirectoryStream<Path> bnds = Files.newDirectoryStream(targetCategoryBase,
185 (p) -> p.getFileName().toString().endsWith(".bnd") && !p.getFileName().toString().equals(COMMON_BND)
186 && !p.getFileName().toString().equals(MERGE_BND));
187 for (Path p : bnds) {
188 processSingleM2ArtifactDistributionUnit(p);
189 }
190
191 DirectoryStream<Path> dus = Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p));
192 for (Path duDir : dus) {
193 if (duDir.getFileName().toString().startsWith("eclipse-")) {
194 processEclipseArchive(duDir);
195 } else {
196 processM2BasedDistributionUnit(duDir);
197 }
198 }
199 } catch (IOException e) {
200 throw new RuntimeException("Cannot process category " + categoryRelativePath, e);
201 }
202 }
203
204 /** Process a standalone Maven artifact. */
205 void processSingleM2ArtifactDistributionUnit(Path bndFile) {
206 try {
207 Path categoryRelativePath = descriptorsBase.relativize(bndFile.getParent());
208 Path targetCategoryBase = a2Base.resolve(categoryRelativePath);
209
210 Properties fileProps = new Properties();
211 try (InputStream in = Files.newInputStream(bndFile)) {
212 fileProps.load(in);
213 }
214 String repoStr = fileProps.containsKey(ARGEO_ORIGIN_M2_REPO.toString())
215 ? fileProps.getProperty(ARGEO_ORIGIN_M2_REPO.toString())
216 : null;
217
218 if (!fileProps.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
219 // use file name as symbolic name
220 String symbolicName = bndFile.getFileName().toString();
221 symbolicName = symbolicName.substring(0, symbolicName.length() - ".bnd".length());
222 fileProps.put(BUNDLE_SYMBOLICNAME.toString(), symbolicName);
223 }
224
225 String m2Coordinates = fileProps.getProperty(ARGEO_ORIGIN_M2.toString());
226 if (m2Coordinates == null)
227 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile);
228 M2Artifact artifact = new M2Artifact(m2Coordinates);
229 URL url = M2ConventionsUtils.mavenRepoUrl(repoStr, artifact);
230 Path downloaded = downloadMaven(url, artifact);
231
232 Path targetBundleDir = processBndJar(downloaded, targetCategoryBase, fileProps, artifact);
233 downloadAndProcessM2Sources(repoStr, artifact, targetBundleDir);
234
235 createJar(targetBundleDir);
236 } catch (Exception e) {
237 throw new RuntimeException("Cannot process " + bndFile, e);
238 }
239 }
240
241 /** Process multiple Maven artifacts. */
242 void processM2BasedDistributionUnit(Path duDir) {
243 try {
244 Path categoryRelativePath = descriptorsBase.relativize(duDir.getParent());
245 Path targetCategoryBase = a2Base.resolve(categoryRelativePath);
246
247 Path mergeBnd = duDir.resolve(MERGE_BND);
248 if (Files.exists(mergeBnd)) // merge
249 mergeM2Artifacts(mergeBnd);
250
251 Path commonBnd = duDir.resolve(COMMON_BND);
252 if (!Files.exists(commonBnd))
253 return;
254
255 Properties commonProps = new Properties();
256 try (InputStream in = Files.newInputStream(commonBnd)) {
257 commonProps.load(in);
258 }
259
260 String m2Version = commonProps.getProperty(ARGEO_ORIGIN_M2.toString());
261 if (m2Version == null) {
262 logger.log(WARNING, "Ignoring " + duDir + " as it is not an M2-based distribution unit");
263 return;// ignore, this is probably an Eclipse archive
264 }
265 if (!m2Version.startsWith(":")) {
266 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version);
267 }
268 m2Version = m2Version.substring(1);
269
270 DirectoryStream<Path> ds = Files.newDirectoryStream(duDir,
271 (p) -> p.getFileName().toString().endsWith(".bnd") && !p.getFileName().toString().equals(COMMON_BND)
272 && !p.getFileName().toString().equals(MERGE_BND));
273 for (Path p : ds) {
274 Properties fileProps = new Properties();
275 try (InputStream in = Files.newInputStream(p)) {
276 fileProps.load(in);
277 }
278 String m2Coordinates = fileProps.getProperty(ARGEO_ORIGIN_M2.toString());
279 M2Artifact artifact = new M2Artifact(m2Coordinates);
280 artifact.setVersion(m2Version);
281
282 // prepare manifest entries
283 Properties mergeProps = new Properties();
284 mergeProps.putAll(commonProps);
285
286 fileEntries: for (Object key : fileProps.keySet()) {
287 if (ManifestConstants.ARGEO_ORIGIN_M2.toString().equals(key))
288 continue fileEntries;
289 String value = fileProps.getProperty(key.toString());
290 Object previousValue = mergeProps.put(key.toString(), value);
291 if (previousValue != null) {
292 logger.log(WARNING,
293 commonBnd + ": " + key + " was " + previousValue + ", overridden with " + value);
294 }
295 }
296 mergeProps.put(ManifestConstants.ARGEO_ORIGIN_M2.toString(), artifact.toM2Coordinates());
297 if (!mergeProps.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
298 // use file name as symbolic name
299 String symbolicName = p.getFileName().toString();
300 symbolicName = symbolicName.substring(0, symbolicName.length() - ".bnd".length());
301 mergeProps.put(BUNDLE_SYMBOLICNAME.toString(), symbolicName);
302 }
303
304 String repoStr = mergeProps.containsKey(ARGEO_ORIGIN_M2_REPO.toString())
305 ? mergeProps.getProperty(ARGEO_ORIGIN_M2_REPO.toString())
306 : null;
307
308 // download
309 URL url = M2ConventionsUtils.mavenRepoUrl(repoStr, artifact);
310 Path downloaded = downloadMaven(url, artifact);
311
312 Path targetBundleDir = processBndJar(downloaded, targetCategoryBase, mergeProps, artifact);
313 downloadAndProcessM2Sources(repoStr, artifact, targetBundleDir);
314 createJar(targetBundleDir);
315 }
316 } catch (IOException e) {
317 throw new RuntimeException("Cannot process " + duDir, e);
318 }
319 }
320
321 /** Merge multiple Maven artifacts. */
322 void mergeM2Artifacts(Path mergeBnd) throws IOException {
323 Path duDir = mergeBnd.getParent();
324 String category = duDir.getParent().getFileName().toString();
325 Path targetCategoryBase = a2Base.resolve(category);
326
327 Properties mergeProps = new Properties();
328 try (InputStream in = Files.newInputStream(mergeBnd)) {
329 mergeProps.load(in);
330 }
331
332 String m2Version = mergeProps.getProperty(ARGEO_ORIGIN_M2.toString());
333 if (m2Version == null) {
334 logger.log(WARNING, "Ignoring " + duDir + " as it is not an M2-based distribution unit");
335 return;// ignore, this is probably an Eclipse archive
336 }
337 if (!m2Version.startsWith(":")) {
338 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version);
339 }
340 m2Version = m2Version.substring(1);
341 mergeProps.put(ManifestConstants.BUNDLE_VERSION.toString(), m2Version);
342
343 String artifactsStr = mergeProps.getProperty(ManifestConstants.ARGEO_ORIGIN_M2_MERGE.toString());
344 if (artifactsStr == null)
345 throw new IllegalArgumentException(
346 mergeBnd + ": " + ManifestConstants.ARGEO_ORIGIN_M2_MERGE + " must be set");
347
348 String repoStr = mergeProps.containsKey(ARGEO_ORIGIN_M2_REPO.toString())
349 ? mergeProps.getProperty(ARGEO_ORIGIN_M2_REPO.toString())
350 : null;
351
352 String bundleSymbolicName = mergeProps.getProperty(ManifestConstants.BUNDLE_SYMBOLICNAME.toString());
353 if (bundleSymbolicName == null)
354 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd);
355 CategoryNameVersion nameVersion = new M2Artifact(category + ":" + bundleSymbolicName + ":" + m2Version);
356
357 Path targetBundleDir = targetCategoryBase.resolve(bundleSymbolicName + "." + nameVersion.getBranch());
358
359 String[] artifacts = artifactsStr.split(",");
360 artifacts: for (String str : artifacts) {
361 String m2Coordinates = str.trim();
362 if ("".equals(m2Coordinates))
363 continue artifacts;
364 M2Artifact artifact = new M2Artifact(m2Coordinates.trim());
365 if (artifact.getVersion() == null)
366 artifact.setVersion(m2Version);
367 URL url = M2ConventionsUtils.mavenRepoUrl(repoStr, artifact);
368 Path downloaded = downloadMaven(url, artifact);
369 JarEntry entry;
370 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(downloaded), false)) {
371 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
372 if (entry.isDirectory())
373 continue entries;
374 else if (entry.getName().endsWith(".RSA") || entry.getName().endsWith(".SF"))
375 continue entries;
376 else if (entry.getName().startsWith("META-INF/versions/"))
377 continue entries;
378 else if (entry.getName().startsWith("META-INF/maven/"))
379 continue entries;
380 else if (entry.getName().equals("module-info.class"))
381 continue entries;
382 else if (entry.getName().equals("META-INF/NOTICE"))
383 continue entries;
384 else if (entry.getName().equals("META-INF/NOTICE.txt"))
385 continue entries;
386 else if (entry.getName().equals("META-INF/LICENSE"))
387 continue entries;
388 else if (entry.getName().equals("META-INF/LICENSE.md"))
389 continue entries;
390 else if (entry.getName().equals("META-INF/LICENSE-notice.md"))
391 continue entries;
392 else if (entry.getName().equals("META-INF/DEPENDENCIES"))
393 continue entries;
394 if (entry.getName().startsWith(".cache/")) // Apache SSHD
395 continue entries;
396 Path target = targetBundleDir.resolve(entry.getName());
397 Files.createDirectories(target.getParent());
398 if (!Files.exists(target)) {
399 Files.copy(jarIn, target);
400 } else {
401 if (entry.getName().startsWith("META-INF/services/")) {
402 try (OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND)) {
403 out.write("\n".getBytes());
404 jarIn.transferTo(out);
405 logger.log(DEBUG, artifact.getArtifactId() + " - Appended " + entry.getName());
406 }
407 } else if (entry.getName().startsWith("org/apache/batik/")) {
408 logger.log(TRACE, "Skip " + entry.getName());
409 continue entries;
410 } else {
411 throw new IllegalStateException("File " + target + " from " + artifact + " already exists");
412 }
413 }
414 logger.log(TRACE, () -> "Copied " + target);
415 }
416
417 }
418 downloadAndProcessM2Sources(repoStr, artifact, targetBundleDir);
419 }
420
421 // additional service files
422 Path servicesDir = duDir.resolve("services");
423 if (Files.exists(servicesDir)) {
424 for (Path p : Files.newDirectoryStream(servicesDir)) {
425 Path target = targetBundleDir.resolve("META-INF/services/").resolve(p.getFileName());
426 try (InputStream in = Files.newInputStream(p);
427 OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND);) {
428 out.write("\n".getBytes());
429 in.transferTo(out);
430 logger.log(DEBUG, "Appended " + p);
431 }
432 }
433 }
434
435 Map<String, String> entries = new TreeMap<>();
436 try (Analyzer bndAnalyzer = new Analyzer()) {
437 bndAnalyzer.setProperties(mergeProps);
438 Jar jar = new Jar(targetBundleDir.toFile());
439 bndAnalyzer.setJar(jar);
440 Manifest manifest = bndAnalyzer.calcManifest();
441
442 keys: for (Object key : manifest.getMainAttributes().keySet()) {
443 Object value = manifest.getMainAttributes().get(key);
444
445 switch (key.toString()) {
446 case "Tool":
447 case "Bnd-LastModified":
448 case "Created-By":
449 continue keys;
450 }
451 if ("Require-Capability".equals(key.toString())
452 && value.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
453 continue keys;// hack for very old classes
454 entries.put(key.toString(), value.toString());
455 }
456 } catch (Exception e) {
457 throw new RuntimeException("Cannot process " + mergeBnd, e);
458 }
459
460 Manifest manifest = new Manifest();
461 Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
462 Files.createDirectories(manifestPath.getParent());
463 for (String key : entries.keySet()) {
464 String value = entries.get(key);
465 manifest.getMainAttributes().putValue(key, value);
466 }
467
468 try (OutputStream out = Files.newOutputStream(manifestPath)) {
469 manifest.write(out);
470 }
471 createJar(targetBundleDir);
472 }
473
474 /** Generate MANIFEST using BND. */
475 Path processBndJar(Path downloaded, Path targetCategoryBase, Properties fileProps, M2Artifact artifact) {
476
477 try {
478 Map<String, String> additionalEntries = new TreeMap<>();
479 boolean doNotModify = Boolean.parseBoolean(fileProps
480 .getOrDefault(ManifestConstants.ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED.toString(), "false").toString());
481
482 // we always force the symbolic name
483
484 if (doNotModify) {
485 fileEntries: for (Object key : fileProps.keySet()) {
486 if (ManifestConstants.ARGEO_ORIGIN_M2.toString().equals(key))
487 continue fileEntries;
488 String value = fileProps.getProperty(key.toString());
489 additionalEntries.put(key.toString(), value);
490 }
491 } else {
492 if (artifact != null) {
493 if (!fileProps.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
494 fileProps.put(BUNDLE_SYMBOLICNAME.toString(), artifact.getName());
495 }
496 if (!fileProps.containsKey(BUNDLE_VERSION.toString())) {
497 fileProps.put(BUNDLE_VERSION.toString(), artifact.getVersion());
498 }
499 }
500
501 if (!fileProps.containsKey(EXPORT_PACKAGE.toString())) {
502 fileProps.put(EXPORT_PACKAGE.toString(),
503 "*;version=\"" + fileProps.getProperty(BUNDLE_VERSION.toString()) + "\"");
504 }
505
506 try (Analyzer bndAnalyzer = new Analyzer()) {
507 bndAnalyzer.setProperties(fileProps);
508 Jar jar = new Jar(downloaded.toFile());
509 bndAnalyzer.setJar(jar);
510 Manifest manifest = bndAnalyzer.calcManifest();
511
512 keys: for (Object key : manifest.getMainAttributes().keySet()) {
513 Object value = manifest.getMainAttributes().get(key);
514
515 switch (key.toString()) {
516 case "Tool":
517 case "Bnd-LastModified":
518 case "Created-By":
519 continue keys;
520 }
521 if ("Require-Capability".equals(key.toString())
522 && value.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
523 continue keys;// !! hack for very old classes
524 additionalEntries.put(key.toString(), value.toString());
525 }
526 }
527 }
528 Path targetBundleDir = processBundleJar(downloaded, targetCategoryBase, additionalEntries);
529 logger.log(DEBUG, () -> "Processed " + downloaded);
530 return targetBundleDir;
531 } catch (Exception e) {
532 throw new RuntimeException("Cannot BND process " + downloaded, e);
533 }
534
535 }
536
537 /** Download and integrates sources for a single Maven artifact. */
538 void downloadAndProcessM2Sources(String repoStr, M2Artifact artifact, Path targetBundleDir) throws IOException {
539 try {
540 M2Artifact sourcesArtifact = new M2Artifact(artifact.toM2Coordinates(), "sources");
541 URL sourcesUrl = M2ConventionsUtils.mavenRepoUrl(repoStr, sourcesArtifact);
542 Path sourcesDownloaded = downloadMaven(sourcesUrl, artifact, true);
543 processM2SourceJar(sourcesDownloaded, targetBundleDir);
544 logger.log(TRACE, () -> "Processed source " + sourcesDownloaded);
545 } catch (Exception e) {
546 logger.log(ERROR, () -> "Cannot download source for " + artifact);
547 }
548
549 }
550
551 /** Integrate sources from a downloaded jar file. */
552 void processM2SourceJar(Path file, Path targetBundleDir) throws IOException {
553 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
554 Path targetSourceDir = sourceBundles
555 ? targetBundleDir.getParent().resolve(targetBundleDir.toString() + ".src")
556 : targetBundleDir.resolve("OSGI-OPT/src");
557
558 Files.createDirectories(targetSourceDir);
559 JarEntry entry;
560 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
561 if (entry.isDirectory())
562 continue entries;
563 if (entry.getName().startsWith("META-INF"))// skip META-INF entries
564 continue entries;
565 if (entry.getName().startsWith("module-info.java"))// skip META-INF entries
566 continue entries;
567 if (entry.getName().startsWith("/")) // absolute paths
568 continue entries;
569 Path target = targetSourceDir.resolve(entry.getName());
570 Files.createDirectories(target.getParent());
571 if (!Files.exists(target)) {
572 Files.copy(jarIn, target);
573 logger.log(TRACE, () -> "Copied source " + target);
574 } else {
575 logger.log(TRACE, () -> target + " already exists, skipping...");
576 }
577 }
578 }
579
580 }
581
582 /** Download a Maven artifact. */
583 Path downloadMaven(URL url, M2Artifact artifact) throws IOException {
584 return downloadMaven(url, artifact, false);
585 }
586
587 /** Download a Maven artifact. */
588 Path downloadMaven(URL url, M2Artifact artifact, boolean sources) throws IOException {
589 return download(url, mavenBase, artifact.getGroupId().replace(".", "/") //
590 + '/' + artifact.getArtifactId() + '/' + artifact.getVersion() //
591 + '/' + artifact.getArtifactId() + "-" + artifact.getVersion() + (sources ? "-sources" : "") + ".jar");
592 }
593
594 /*
595 * ECLIPSE ORIGIN
596 */
597 /** Process an archive in Eclipse format. */
598 void processEclipseArchive(Path duDir) {
599 try {
600 Path categoryRelativePath = descriptorsBase.relativize(duDir.getParent());
601 Path targetCategoryBase = a2Base.resolve(categoryRelativePath);
602 Files.createDirectories(targetCategoryBase);
603 // first delete all directories from previous builds
604 for (Path dir : Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p)))
605 deleteDirectory(dir);
606
607 Files.createDirectories(originBase);
608
609 Path commonBnd = duDir.resolve(COMMON_BND);
610 Properties commonProps = new Properties();
611 try (InputStream in = Files.newInputStream(commonBnd)) {
612 commonProps.load(in);
613 }
614 String url = commonProps.getProperty(ManifestConstants.ARGEO_ORIGIN_URI.toString());
615 if (url == null) {
616 url = uris.getProperty(duDir.getFileName().toString());
617 if (url == null)
618 throw new IllegalStateException("No url available for " + duDir);
619 commonProps.put(ManifestConstants.ARGEO_ORIGIN_URI.toString(), url);
620 }
621 Path downloaded = tryDownloadArchive(url, originBase);
622
623 FileSystem zipFs = FileSystems.newFileSystem(downloaded, (ClassLoader) null);
624
625 // filters
626 List<PathMatcher> includeMatchers = new ArrayList<>();
627 Properties includes = new Properties();
628 try (InputStream in = Files.newInputStream(duDir.resolve("includes.properties"))) {
629 includes.load(in);
630 }
631 for (Object pattern : includes.keySet()) {
632 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
633 includeMatchers.add(pathMatcher);
634 }
635
636 List<PathMatcher> excludeMatchers = new ArrayList<>();
637 Path excludeFile = duDir.resolve("excludes.properties");
638 if (Files.exists(excludeFile)) {
639 Properties excludes = new Properties();
640 try (InputStream in = Files.newInputStream(excludeFile)) {
641 excludes.load(in);
642 }
643 for (Object pattern : excludes.keySet()) {
644 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
645 excludeMatchers.add(pathMatcher);
646 }
647 }
648
649 Files.walkFileTree(zipFs.getRootDirectories().iterator().next(), new SimpleFileVisitor<Path>() {
650
651 @Override
652 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
653 includeMatchers: for (PathMatcher includeMatcher : includeMatchers) {
654 if (includeMatcher.matches(file)) {
655 for (PathMatcher excludeMatcher : excludeMatchers) {
656 if (excludeMatcher.matches(file)) {
657 logger.log(TRACE, "Skipping excluded " + file);
658 return FileVisitResult.CONTINUE;
659 }
660 }
661 if (file.getFileName().toString().contains(".source_")) {
662 processEclipseSourceJar(file, targetCategoryBase);
663 logger.log(DEBUG, () -> "Processed source " + file);
664 } else {
665 Map<String, String> map = new HashMap<>();
666 for (Object key : commonProps.keySet())
667 map.put(key.toString(), commonProps.getProperty(key.toString()));
668 processBundleJar(file, targetCategoryBase, map);
669 logger.log(DEBUG, () -> "Processed " + file);
670 }
671 break includeMatchers;
672 }
673 }
674 return FileVisitResult.CONTINUE;
675 }
676 });
677
678 DirectoryStream<Path> dirs = Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p)
679 && p.getFileName().toString().indexOf('.') >= 0 && !p.getFileName().toString().endsWith(".src"));
680 for (Path dir : dirs) {
681 createJar(dir);
682 }
683 } catch (IOException e) {
684 throw new RuntimeException("Cannot process " + duDir, e);
685 }
686
687 }
688
689 /** Process sources in Eclipse format. */
690 void processEclipseSourceJar(Path file, Path targetBase) throws IOException {
691 try {
692 Path targetBundleDir;
693 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
694 Manifest manifest = jarIn.getManifest();
695
696 String[] relatedBundle = manifest.getMainAttributes().getValue(ECLIPSE_SOURCE_BUNDLE.toString())
697 .split(";");
698 String version = relatedBundle[1].substring("version=\"".length());
699 version = version.substring(0, version.length() - 1);
700 NameVersion nameVersion = new NameVersion(relatedBundle[0], version);
701 targetBundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
702
703 Path targetSourceDir = sourceBundles
704 ? targetBundleDir.getParent().resolve(targetBundleDir.toString() + ".src")
705 : targetBundleDir.resolve("OSGI-OPT/src");
706
707 Files.createDirectories(targetSourceDir);
708 JarEntry entry;
709 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
710 if (entry.isDirectory())
711 continue entries;
712 if (entry.getName().startsWith("META-INF"))// skip META-INF entries
713 continue entries;
714 Path target = targetSourceDir.resolve(entry.getName());
715 Files.createDirectories(target.getParent());
716 Files.copy(jarIn, target);
717 logger.log(TRACE, () -> "Copied source " + target);
718 }
719 }
720 } catch (IOException e) {
721 throw new IllegalStateException("Cannot process " + file, e);
722 }
723 }
724
725 /*
726 * COMMON PROCESSING
727 */
728 /** Normalise a bundle. */
729 Path processBundleJar(Path file, Path targetBase, Map<String, String> entries) throws IOException {
730 NameVersion nameVersion;
731 Path targetBundleDir;
732 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
733 Manifest sourceManifest = jarIn.getManifest();
734 Manifest manifest = sourceManifest != null ? new Manifest(sourceManifest) : new Manifest();
735
736 // singleton
737 boolean isSingleton = false;
738 String rawSourceSymbolicName = manifest.getMainAttributes()
739 .getValue(ManifestConstants.BUNDLE_SYMBOLICNAME.toString());
740 if (rawSourceSymbolicName != null) {
741 // make sure there is no directive
742 String[] arr = rawSourceSymbolicName.split(";");
743 for (int i = 1; i < arr.length; i++) {
744 if (arr[i].trim().equals("singleton:=true"))
745 isSingleton = true;
746 logger.log(DEBUG, file.getFileName() + " is a singleton");
747 }
748 }
749 // remove problematic entries in MANIFEST
750 manifest.getEntries().clear();
751
752 String ourSymbolicName = entries.get(BUNDLE_SYMBOLICNAME.toString());
753 String ourVersion = entries.get(BUNDLE_VERSION.toString());
754
755 if (ourSymbolicName != null && ourVersion != null) {
756 nameVersion = new NameVersion(ourSymbolicName, ourVersion);
757 } else {
758 nameVersion = nameVersionFromManifest(manifest);
759 if (ourVersion != null && !nameVersion.getVersion().equals(ourVersion)) {
760 logger.log(WARNING,
761 "Original version is " + nameVersion.getVersion() + " while new version is " + ourVersion);
762 entries.put(BUNDLE_VERSION.toString(), ourVersion);
763 }
764 if (ourSymbolicName != null) {
765 // we always force our symbolic name
766 nameVersion.setName(ourSymbolicName);
767 }
768 }
769 targetBundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
770
771 // force Java 9 module name
772 entries.put(ManifestConstants.AUTOMATIC_MODULE_NAME.toString(), nameVersion.getName());
773
774 boolean isNative = false;
775 String os = null;
776 String arch = null;
777 if (targetBundleDir.startsWith(a2LibBase)) {
778 isNative = true;
779 Path libRelativePath = a2LibBase.relativize(targetBundleDir);
780 os = libRelativePath.getName(0).toString();
781 arch = libRelativePath.getName(1).toString();
782 }
783
784 // copy entries
785 JarEntry entry;
786 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
787 if (entry.isDirectory())
788 continue entries;
789 if (entry.getName().endsWith(".RSA") || entry.getName().endsWith(".SF"))
790 continue entries;
791 if (entry.getName().endsWith("module-info.class")) // skip Java 9 module info
792 continue entries;
793 if (entry.getName().startsWith("META-INF/versions/")) // skip multi-version
794 continue entries;
795 // skip file system providers as they cause issues with native image
796 if (entry.getName().startsWith("META-INF/services/java.nio.file.spi.FileSystemProvider"))
797 continue entries;
798 if (entry.getName().startsWith("OSGI-OPT/src/")) // skip embedded sources
799 continue entries;
800 Path target = targetBundleDir.resolve(entry.getName());
801 Files.createDirectories(target.getParent());
802 Files.copy(jarIn, target);
803
804 // native libraries
805 if (isNative && (entry.getName().endsWith(".so") || entry.getName().endsWith(".dll")
806 || entry.getName().endsWith(".jnilib"))) {
807 Path categoryDir = targetBundleDir.getParent();
808 boolean copyDll = false;
809 Path targetDll = categoryDir.resolve(targetBundleDir.relativize(target));
810 if (nameVersion.getName().equals("com.sun.jna")) {
811 if (arch.equals("x86_64"))
812 arch = "x86-64";
813 if (os.equals("macosx"))
814 os = "darwin";
815 if (target.getParent().getFileName().toString().equals(os + "-" + arch)) {
816 copyDll = true;
817 }
818 targetDll = categoryDir.resolve(target.getFileName());
819 } else {
820 copyDll = true;
821 }
822 if (copyDll) {
823 Files.createDirectories(targetDll.getParent());
824 if (Files.exists(targetDll))
825 Files.delete(targetDll);
826 Files.copy(target, targetDll);
827 }
828 Files.delete(target);
829 }
830 logger.log(TRACE, () -> "Copied " + target);
831 }
832
833 // copy MANIFEST
834 Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
835 Files.createDirectories(manifestPath.getParent());
836
837 if (isSingleton && entries.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
838 entries.put(BUNDLE_SYMBOLICNAME.toString(),
839 entries.get(BUNDLE_SYMBOLICNAME.toString()) + ";singleton:=true");
840 }
841
842 // Final MANIFEST decisions
843 // This also where we check the original OSGi metadata and compare with our
844 // changes
845 for (String key : entries.keySet()) {
846 String value = entries.get(key);
847 String previousValue = manifest.getMainAttributes().getValue(key);
848 boolean wasDifferent = previousValue != null && !previousValue.equals(value);
849 boolean keepPrevious = false;
850 if (wasDifferent) {
851 if (SPDX_LICENSE_IDENTIFIER.toString().equals(key) && previousValue != null)
852 keepPrevious = true;
853 else if (BUNDLE_VERSION.toString().equals(key) && wasDifferent)
854 if (previousValue.equals(value + ".0")) // typically a Maven first release
855 keepPrevious = true;
856
857 if (keepPrevious) {
858 if (logger.isLoggable(TRACE))
859 logger.log(TRACE, file.getFileName() + ": " + key + " was NOT modified, value kept is "
860 + previousValue + ", not overriden with " + value);
861 value = previousValue;
862 }
863 }
864
865 manifest.getMainAttributes().putValue(key, value);
866 if (wasDifferent && !keepPrevious) {
867 if (IMPORT_PACKAGE.toString().equals(key) || EXPORT_PACKAGE.toString().equals(key))
868 logger.log(TRACE, () -> file.getFileName() + ": " + key + " was modified");
869 else
870 logger.log(WARNING, file.getFileName() + ": " + key + " was " + previousValue
871 + ", overridden with " + value);
872 }
873
874 // !! hack to remove unresolvable
875 if (key.equals("Provide-Capability") || key.equals("Require-Capability"))
876 if (nameVersion.getName().equals("osgi.core") || nameVersion.getName().equals("osgi.cmpn")) {
877 manifest.getMainAttributes().remove(key);
878 }
879 }
880
881 // last checks
882 String spdxLicenceId = manifest.getMainAttributes().getValue(SPDX_LICENSE_IDENTIFIER.toString());
883 String bundleLicense = manifest.getMainAttributes().getValue(BUNDLE_LICENSE.toString());
884 if (spdxLicenceId == null) {
885 logger.log(WARNING, file.getFileName() + ": " + SPDX_LICENSE_IDENTIFIER + " not available, "
886 + BUNDLE_LICENSE + " is " + bundleLicense);
887 } else {
888 if (!licensesUsed.containsKey(spdxLicenceId))
889 licensesUsed.put(spdxLicenceId, new TreeSet<>());
890 licensesUsed.get(spdxLicenceId).add(file.getFileName().toString());
891 }
892
893 try (OutputStream out = Files.newOutputStream(manifestPath)) {
894 manifest.write(out);
895 }
896 }
897 return targetBundleDir;
898 }
899
900 /*
901 * UTILITIES
902 */
903 /** Recursively deletes a directory. */
904 static void deleteDirectory(Path path) throws IOException {
905 if (!Files.exists(path))
906 return;
907 Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
908 @Override
909 public FileVisitResult postVisitDirectory(Path directory, IOException e) throws IOException {
910 if (e != null)
911 throw e;
912 Files.delete(directory);
913 return CONTINUE;
914 }
915
916 @Override
917 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
918 Files.delete(file);
919 return CONTINUE;
920 }
921 });
922 }
923
924 /** Extract name/version from a MANIFEST. */
925 NameVersion nameVersionFromManifest(Manifest manifest) {
926 Attributes attrs = manifest.getMainAttributes();
927 // symbolic name
928 String symbolicName = attrs.getValue(ManifestConstants.BUNDLE_SYMBOLICNAME.toString());
929 if (symbolicName == null)
930 return null;
931 // make sure there is no directive
932 symbolicName = symbolicName.split(";")[0];
933
934 String version = attrs.getValue(ManifestConstants.BUNDLE_VERSION.toString());
935 return new NameVersion(symbolicName, version);
936 }
937
938 /** Try to download from an URI. */
939 Path tryDownloadArchive(String uri, Path dir) throws IOException {
940 // find mirror
941 List<String> urlBases = null;
942 String uriPrefix = null;
943 uriPrefixes: for (String uriPref : mirrors.keySet()) {
944 if (uri.startsWith(uriPref)) {
945 if (mirrors.get(uriPref).size() > 0) {
946 urlBases = mirrors.get(uriPref);
947 uriPrefix = uriPref;
948 break uriPrefixes;
949 }
950 }
951 }
952 if (urlBases == null)
953 try {
954 return downloadArchive(new URL(uri), dir);
955 } catch (FileNotFoundException e) {
956 throw new FileNotFoundException("Cannot find " + uri);
957 }
958
959 // try to download
960 for (String urlBase : urlBases) {
961 String relativePath = uri.substring(uriPrefix.length());
962 URL url = new URL(urlBase + relativePath);
963 try {
964 return downloadArchive(url, dir);
965 } catch (FileNotFoundException e) {
966 logger.log(WARNING, "Cannot download " + url + ", trying another mirror");
967 }
968 }
969 throw new FileNotFoundException("Cannot find " + uri);
970 }
971
972 /**
973 * Effectively download. Synchronised in order to avoid downloading twice in
974 * parallel.
975 */
976 synchronized Path downloadArchive(URL url, Path dir) throws IOException {
977 return download(url, dir, (String) null);
978 }
979
980 /** Effectively download. */
981 Path download(URL url, Path dir, String name) throws IOException {
982
983 Path dest;
984 if (name == null) {
985 // We use also use parent directory in case the archive itself has a fixed name
986 String[] segments = url.getPath().split("/");
987 name = segments.length > 1 ? segments[segments.length - 2] + '-' + segments[segments.length - 1]
988 : segments[segments.length - 1];
989 }
990
991 dest = dir.resolve(name);
992 if (Files.exists(dest)) {
993 logger.log(TRACE, () -> "File " + dest + " already exists for " + url + ", not downloading again");
994 return dest;
995 } else {
996 Files.createDirectories(dest.getParent());
997 }
998
999 try (InputStream in = url.openStream()) {
1000 Files.copy(in, dest);
1001 logger.log(DEBUG, () -> "Downloaded " + dest + " from " + url);
1002 }
1003 return dest;
1004 }
1005
1006 /** Create a JAR file from a directory. */
1007 Path createJar(Path bundleDir) throws IOException {
1008 // Create the jar
1009 Path jarPath = bundleDir.getParent().resolve(bundleDir.getFileName() + ".jar");
1010 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
1011 Manifest manifest;
1012 try (InputStream in = Files.newInputStream(manifestPath)) {
1013 manifest = new Manifest(in);
1014 }
1015 try (JarOutputStream jarOut = new JarOutputStream(Files.newOutputStream(jarPath), manifest)) {
1016 jarOut.setLevel(Deflater.DEFAULT_COMPRESSION);
1017 Files.walkFileTree(bundleDir, new SimpleFileVisitor<Path>() {
1018
1019 @Override
1020 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1021 if (file.getFileName().toString().equals("MANIFEST.MF"))
1022 return super.visitFile(file, attrs);
1023 JarEntry entry = new JarEntry(
1024 bundleDir.relativize(file).toString().replace(File.separatorChar, '/'));
1025 jarOut.putNextEntry(entry);
1026 Files.copy(file, jarOut);
1027 return super.visitFile(file, attrs);
1028 }
1029
1030 });
1031 }
1032 deleteDirectory(bundleDir);
1033
1034 if (sourceBundles) {
1035 Path bundleCategoryDir = bundleDir.getParent();
1036 Path sourceDir = bundleCategoryDir.resolve(bundleDir.toString() + ".src");
1037 if (!Files.exists(sourceDir)) {
1038 logger.log(WARNING, sourceDir + " does not exist, skipping...");
1039 return jarPath;
1040
1041 }
1042
1043 Path relPath = a2Base.relativize(bundleCategoryDir);
1044 Path srcCategoryDir = a2SrcBase.resolve(relPath);
1045 Path srcJarP = srcCategoryDir.resolve(sourceDir.getFileName() + ".jar");
1046 Files.createDirectories(srcJarP.getParent());
1047
1048 String bundleSymbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName").toString();
1049 // in case there are additional directives
1050 bundleSymbolicName = bundleSymbolicName.split(";")[0];
1051 Manifest srcManifest = new Manifest();
1052 srcManifest.getMainAttributes().put(MANIFEST_VERSION, "1.0");
1053 srcManifest.getMainAttributes().putValue(BUNDLE_SYMBOLICNAME.toString(), bundleSymbolicName + ".src");
1054 srcManifest.getMainAttributes().putValue(BUNDLE_VERSION.toString(),
1055 manifest.getMainAttributes().getValue(BUNDLE_VERSION.toString()).toString());
1056 srcManifest.getMainAttributes().putValue(ECLIPSE_SOURCE_BUNDLE.toString(), bundleSymbolicName
1057 + ";version=\"" + manifest.getMainAttributes().getValue(BUNDLE_VERSION.toString()));
1058
1059 try (JarOutputStream srcJarOut = new JarOutputStream(Files.newOutputStream(srcJarP), srcManifest)) {
1060 srcJarOut.setLevel(Deflater.BEST_COMPRESSION);
1061 Files.walkFileTree(sourceDir, new SimpleFileVisitor<Path>() {
1062
1063 @Override
1064 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
1065 if (file.getFileName().toString().equals("MANIFEST.MF"))
1066 return super.visitFile(file, attrs);
1067 JarEntry entry = new JarEntry(
1068 sourceDir.relativize(file).toString().replace(File.separatorChar, '/'));
1069 srcJarOut.putNextEntry(entry);
1070 Files.copy(file, srcJarOut);
1071 return super.visitFile(file, attrs);
1072 }
1073
1074 });
1075 }
1076 deleteDirectory(sourceDir);
1077 }
1078
1079 return jarPath;
1080 }
1081
1082 /** MANIFEST headers. */
1083 enum ManifestConstants {
1084 // OSGi
1085 /** OSGi bundle symbolic name. */
1086 BUNDLE_SYMBOLICNAME("Bundle-SymbolicName"), //
1087 /** OSGi bundle version. */
1088 BUNDLE_VERSION("Bundle-Version"), //
1089 /** OSGi bundle license. */
1090 BUNDLE_LICENSE("Bundle-License"), //
1091 /** OSGi exported packages list. */
1092 EXPORT_PACKAGE("Export-Package"), //
1093 /** OSGi imported packages list. */
1094 IMPORT_PACKAGE("Import-Package"), //
1095 // Java
1096 /** Java module name. */
1097 AUTOMATIC_MODULE_NAME("Automatic-Module-Name"), //
1098 // Eclipse
1099 /** Eclipse source bundle. */
1100 ECLIPSE_SOURCE_BUNDLE("Eclipse-SourceBundle"), //
1101 // SPDX
1102 /**
1103 * SPDX license identifier.
1104 *
1105 * @see https://spdx.org/licenses/
1106 */
1107 SPDX_LICENSE_IDENTIFIER("SPDX-License-Identifier"), //
1108 // Argeo Origin
1109 /**
1110 * Maven coordinates of the origin, possibly partial when using common.bnd or
1111 * merge.bnd.
1112 */
1113 ARGEO_ORIGIN_M2("Argeo-Origin-M2"), //
1114 /** List of Maven coordinates to merge. */
1115 ARGEO_ORIGIN_M2_MERGE("Argeo-Origin-M2-Merge"), //
1116 /** Maven repository if not the default one. */
1117 ARGEO_ORIGIN_M2_REPO("Argeo-Origin-M2-Repo"), //
1118 /**
1119 * Do not perform BND analysis of the origin component. Typically IMport_package
1120 * and Export-Package will be kept untouched.
1121 */
1122 ARGEO_ORIGIN_MANIFEST_NOT_MODIFIED("Argeo-Origin-ManifestNotModified"), //
1123 /**
1124 * Origin (non-Maven) URI of the component. It may be anything (jar, archive,
1125 * etc.).
1126 */
1127 ARGEO_ORIGIN_URI("Argeo-Origin-URI"), //
1128 ;
1129
1130 final String value;
1131
1132 private ManifestConstants(String value) {
1133 this.value = value;
1134 }
1135
1136 @Override
1137 public String toString() {
1138 return value;
1139 }
1140 }
1141 }
1142
1143 /** Simple representation of an M2 artifact. */
1144 class M2Artifact extends CategoryNameVersion {
1145 private String classifier;
1146
1147 M2Artifact(String m2coordinates) {
1148 this(m2coordinates, null);
1149 }
1150
1151 M2Artifact(String m2coordinates, String classifier) {
1152 String[] parts = m2coordinates.split(":");
1153 setCategory(parts[0]);
1154 setName(parts[1]);
1155 if (parts.length > 2) {
1156 setVersion(parts[2]);
1157 }
1158 this.classifier = classifier;
1159 }
1160
1161 String getGroupId() {
1162 return super.getCategory();
1163 }
1164
1165 String getArtifactId() {
1166 return super.getName();
1167 }
1168
1169 String toM2Coordinates() {
1170 return getCategory() + ":" + getName() + (getVersion() != null ? ":" + getVersion() : "");
1171 }
1172
1173 String getClassifier() {
1174 return classifier != null ? classifier : "";
1175 }
1176
1177 String getExtension() {
1178 return "jar";
1179 }
1180 }
1181
1182 /** Utilities around Maven (conventions based). */
1183 class M2ConventionsUtils {
1184 final static String MAVEN_CENTRAL_BASE_URL = "https://repo1.maven.org/maven2/";
1185
1186 /** The file name of this artifact when stored */
1187 static String artifactFileName(M2Artifact artifact) {
1188 return artifact.getArtifactId() + '-' + artifact.getVersion()
1189 + (artifact.getClassifier().equals("") ? "" : '-' + artifact.getClassifier()) + '.'
1190 + artifact.getExtension();
1191 }
1192
1193 /** Absolute path to the file */
1194 static String artifactPath(String artifactBasePath, M2Artifact artifact) {
1195 return artifactParentPath(artifactBasePath, artifact) + '/' + artifactFileName(artifact);
1196 }
1197
1198 /** Absolute path to the file */
1199 static String artifactUrl(String repoUrl, M2Artifact artifact) {
1200 if (repoUrl.endsWith("/"))
1201 return repoUrl + artifactPath("/", artifact).substring(1);
1202 else
1203 return repoUrl + artifactPath("/", artifact);
1204 }
1205
1206 /** Absolute path to the file */
1207 static URL mavenRepoUrl(String repoBase, M2Artifact artifact) {
1208 String url = artifactUrl(repoBase == null ? MAVEN_CENTRAL_BASE_URL : repoBase, artifact);
1209 try {
1210 return new URL(url);
1211 } catch (MalformedURLException e) {
1212 // it should not happen
1213 throw new IllegalStateException(e);
1214 }
1215 }
1216
1217 /** Absolute path to the directories where the files will be stored */
1218 static String artifactParentPath(String artifactBasePath, M2Artifact artifact) {
1219 return artifactBasePath + (artifactBasePath.endsWith("/") ? "" : "/") + artifactParentPath(artifact);
1220 }
1221
1222 /** Relative path to the directories where the files will be stored */
1223 static String artifactParentPath(M2Artifact artifact) {
1224 return artifact.getGroupId().replace('.', '/') + '/' + artifact.getArtifactId() + '/' + artifact.getVersion();
1225 }
1226
1227 /** Singleton */
1228 private M2ConventionsUtils() {
1229 }
1230 }
1231
1232 /** Combination of a category, a name and a version. */
1233 class CategoryNameVersion extends NameVersion {
1234 private String category;
1235
1236 CategoryNameVersion() {
1237 }
1238
1239 CategoryNameVersion(String category, String name, String version) {
1240 super(name, version);
1241 this.category = category;
1242 }
1243
1244 CategoryNameVersion(String category, NameVersion nameVersion) {
1245 super(nameVersion);
1246 this.category = category;
1247 }
1248
1249 String getCategory() {
1250 return category;
1251 }
1252
1253 void setCategory(String category) {
1254 this.category = category;
1255 }
1256
1257 @Override
1258 public String toString() {
1259 return category + ":" + super.toString();
1260 }
1261
1262 }
1263
1264 /** Combination of a name and a version. */
1265 class NameVersion implements Comparable<NameVersion> {
1266 private String name;
1267 private String version;
1268
1269 NameVersion() {
1270 }
1271
1272 /** Interprets string in OSGi-like format my.module.name;version=0.0.0 */
1273 NameVersion(String nameVersion) {
1274 int index = nameVersion.indexOf(";version=");
1275 if (index < 0) {
1276 setName(nameVersion);
1277 setVersion(null);
1278 } else {
1279 setName(nameVersion.substring(0, index));
1280 setVersion(nameVersion.substring(index + ";version=".length()));
1281 }
1282 }
1283
1284 NameVersion(String name, String version) {
1285 this.name = name;
1286 this.version = version;
1287 }
1288
1289 NameVersion(NameVersion nameVersion) {
1290 this.name = nameVersion.getName();
1291 this.version = nameVersion.getVersion();
1292 }
1293
1294 String getName() {
1295 return name;
1296 }
1297
1298 void setName(String name) {
1299 this.name = name;
1300 }
1301
1302 String getVersion() {
1303 return version;
1304 }
1305
1306 void setVersion(String version) {
1307 this.version = version;
1308 }
1309
1310 String getBranch() {
1311 String[] parts = getVersion().split("\\.");
1312 if (parts.length < 2)
1313 throw new IllegalStateException("Version " + getVersion() + " cannot be interpreted as branch.");
1314 return parts[0] + "." + parts[1];
1315 }
1316
1317 @Override
1318 public boolean equals(Object obj) {
1319 if (obj instanceof NameVersion) {
1320 NameVersion nameVersion = (NameVersion) obj;
1321 return name.equals(nameVersion.getName()) && version.equals(nameVersion.getVersion());
1322 } else
1323 return false;
1324 }
1325
1326 @Override
1327 public int hashCode() {
1328 return name.hashCode();
1329 }
1330
1331 @Override
1332 public String toString() {
1333 return name + ":" + version;
1334 }
1335
1336 public int compareTo(NameVersion o) {
1337 if (o.getName().equals(name))
1338 return version.compareTo(o.getVersion());
1339 else
1340 return name.compareTo(o.getName());
1341 }
1342 }