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