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