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