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