]> git.argeo.org Git - gpl/argeo-slc.git/blob - org.argeo.slc.factory/src/org/argeo/slc/factory/A2Factory.java
5641687f7bbf79afefce003e876f56c6be5bf07e
[gpl/argeo-slc.git] / org.argeo.slc.factory / src / org / argeo / slc / factory / A2Factory.java
1 package org.argeo.slc.factory;
2
3 import static java.lang.System.Logger.Level.DEBUG;
4 import static org.argeo.slc.ManifestConstants.BUNDLE_SYMBOLICNAME;
5 import static org.argeo.slc.ManifestConstants.BUNDLE_VERSION;
6 import static org.argeo.slc.ManifestConstants.EXPORT_PACKAGE;
7 import static org.argeo.slc.ManifestConstants.SLC_ORIGIN_M2;
8 import static org.argeo.slc.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.URL;
17 import java.nio.file.DirectoryStream;
18 import java.nio.file.FileSystem;
19 import java.nio.file.FileSystems;
20 import java.nio.file.FileVisitResult;
21 import java.nio.file.Files;
22 import java.nio.file.Path;
23 import java.nio.file.PathMatcher;
24 import java.nio.file.Paths;
25 import java.nio.file.SimpleFileVisitor;
26 import java.nio.file.StandardOpenOption;
27 import java.nio.file.attribute.BasicFileAttributes;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Properties;
33 import java.util.TreeMap;
34 import java.util.jar.Attributes;
35 import java.util.jar.JarEntry;
36 import java.util.jar.JarInputStream;
37 import java.util.jar.JarOutputStream;
38 import java.util.jar.Manifest;
39 import java.util.zip.Deflater;
40
41 import org.argeo.slc.DefaultCategoryNameVersion;
42 import org.argeo.slc.DefaultNameVersion;
43 import org.argeo.slc.ManifestConstants;
44 import org.argeo.slc.NameVersion;
45 import org.argeo.slc.factory.m2.Artifact;
46 import org.argeo.slc.factory.m2.DefaultArtifact;
47 import org.argeo.slc.factory.m2.MavenConventionsUtils;
48
49 import aQute.bnd.osgi.Analyzer;
50 import aQute.bnd.osgi.Jar;
51
52 /** The central class for A2 packaging. */
53 public class A2Factory {
54 private final static Logger logger = System.getLogger(A2Factory.class.getName());
55
56 private final static String COMMON_BND = "common.bnd";
57 private final static String MERGE_BND = "merge.bnd";
58
59 private Path originBase;
60 private Path a2Base;
61
62 /** key is URI prefix, value list of base URLs */
63 private Map<String, List<String>> mirrors = new HashMap<String, List<String>>();
64
65 public A2Factory(Path a2Base) {
66 this.originBase = Paths.get(System.getProperty("user.home"), ".cache", "argeo/slc/origin");
67 this.a2Base = a2Base;
68
69 // TODO make it configurable
70 List<String> eclipseMirrors = new ArrayList<>();
71 eclipseMirrors.add("https://archive.eclipse.org/");
72 eclipseMirrors.add("http://ftp-stud.hs-esslingen.de/Mirrors/eclipse/");
73 eclipseMirrors.add("http://ftp.fau.de/eclipse/");
74
75 mirrors.put("http://www.eclipse.org/downloads", eclipseMirrors);
76 }
77
78 /*
79 * MAVEN ORIGIN
80 */
81
82 /** Process a whole category/group id. */
83 public void processCategory(Path targetCategoryBase) {
84 try {
85 DirectoryStream<Path> bnds = Files.newDirectoryStream(targetCategoryBase,
86 (p) -> p.getFileName().toString().endsWith(".bnd") && !p.getFileName().toString().equals(COMMON_BND)
87 && !p.getFileName().toString().equals(MERGE_BND));
88 for (Path p : bnds) {
89 processSingleM2ArtifactDistributionUnit(p);
90 }
91
92 DirectoryStream<Path> dus = Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p));
93 for (Path duDir : dus) {
94 processM2BasedDistributionUnit(duDir);
95 }
96 } catch (IOException e) {
97 throw new RuntimeException("Cannot process category " + targetCategoryBase, e);
98 }
99 }
100
101 /** Process a standalone Maven artifact. */
102 public void processSingleM2ArtifactDistributionUnit(Path bndFile) {
103 try {
104 String category = bndFile.getParent().getFileName().toString();
105 Path targetCategoryBase = a2Base.resolve(category);
106 Properties fileProps = new Properties();
107 try (InputStream in = Files.newInputStream(bndFile)) {
108 fileProps.load(in);
109 }
110 String repoStr = fileProps.containsKey(SLC_ORIGIN_M2_REPO.toString())
111 ? fileProps.getProperty(SLC_ORIGIN_M2_REPO.toString())
112 : null;
113
114 if (!fileProps.containsKey(BUNDLE_SYMBOLICNAME.toString())
115 && !fileProps.containsKey(ManifestConstants.SLC_ORIGIN_MANIFEST_NOT_MODIFIED.toString())) {
116 // use file name as symbolic name
117 String symbolicName = bndFile.getFileName().toString();
118 symbolicName = symbolicName.substring(0, symbolicName.length() - ".bnd".length());
119 fileProps.put(BUNDLE_SYMBOLICNAME.toString(), symbolicName);
120 }
121
122 String m2Coordinates = fileProps.getProperty(SLC_ORIGIN_M2.toString());
123 if (m2Coordinates == null)
124 throw new IllegalArgumentException("No M2 coordinates available for " + bndFile);
125 DefaultArtifact artifact = new DefaultArtifact(m2Coordinates);
126 URL url = MavenConventionsUtils.mavenRepoUrl(repoStr, artifact);
127 Path downloaded = download(url, originBase, artifact);
128
129 Path targetBundleDir = processBndJar(downloaded, targetCategoryBase, fileProps, artifact);
130
131 downloadAndProcessM2Sources(repoStr, artifact, targetBundleDir);
132
133 createJar(targetBundleDir);
134 } catch (Exception e) {
135 throw new RuntimeException("Cannot process " + bndFile, e);
136 }
137 }
138
139 /** Process multiple Maven artifacts. */
140 public void processM2BasedDistributionUnit(Path duDir) {
141 try {
142 String category = duDir.getParent().getFileName().toString();
143 Path targetCategoryBase = a2Base.resolve(category);
144
145 // merge
146 Path mergeBnd = duDir.resolve(MERGE_BND);
147 if (Files.exists(mergeBnd)) {
148 mergeM2Artifacts(mergeBnd);
149 // return;
150 }
151
152 Path commonBnd = duDir.resolve(COMMON_BND);
153 if (!Files.exists(commonBnd)) {
154 return;
155 }
156 Properties commonProps = new Properties();
157 try (InputStream in = Files.newInputStream(commonBnd)) {
158 commonProps.load(in);
159 }
160
161 String m2Version = commonProps.getProperty(SLC_ORIGIN_M2.toString());
162 if (m2Version == null) {
163 logger.log(Level.WARNING, "Ignoring " + duDir + " as it is not an M2-based distribution unit");
164 return;// ignore, this is probably an Eclipse archive
165 }
166 if (!m2Version.startsWith(":")) {
167 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version);
168 }
169 m2Version = m2Version.substring(1);
170
171 DirectoryStream<Path> ds = Files.newDirectoryStream(duDir,
172 (p) -> p.getFileName().toString().endsWith(".bnd") && !p.getFileName().toString().equals(COMMON_BND)
173 && !p.getFileName().toString().equals(MERGE_BND));
174 for (Path p : ds) {
175 Properties fileProps = new Properties();
176 try (InputStream in = Files.newInputStream(p)) {
177 fileProps.load(in);
178 }
179 String m2Coordinates = fileProps.getProperty(SLC_ORIGIN_M2.toString());
180 DefaultArtifact artifact = new DefaultArtifact(m2Coordinates);
181
182 // temporary rewrite, for migration
183 // String localLicense = fileProps.getProperty(BUNDLE_LICENSE.toString());
184 // if (localLicense != null || artifact.getVersion() != null) {
185 // fileProps.remove(BUNDLE_LICENSE.toString());
186 // fileProps.put(SLC_ORIGIN_M2.toString(), artifact.getGroupId() + ":" + artifact.getArtifactId());
187 // try (Writer writer = Files.newBufferedWriter(p)) {
188 // for (Object key : fileProps.keySet()) {
189 // String value = fileProps.getProperty(key.toString());
190 // writer.write(key + ": " + value + '\n');
191 // }
192 // logger.log(DEBUG, () -> "Migrated " + p);
193 // }
194 // }
195
196 artifact.setVersion(m2Version);
197
198 // prepare manifest entries
199 Properties mergeProps = new Properties();
200 mergeProps.putAll(commonProps);
201
202 fileEntries: for (Object key : fileProps.keySet()) {
203 if (ManifestConstants.SLC_ORIGIN_M2.toString().equals(key))
204 continue fileEntries;
205 String value = fileProps.getProperty(key.toString());
206 Object previousValue = mergeProps.put(key.toString(), value);
207 if (previousValue != null) {
208 logger.log(Level.WARNING,
209 commonBnd + ": " + key + " was " + previousValue + ", overridden with " + value);
210 }
211 }
212 mergeProps.put(ManifestConstants.SLC_ORIGIN_M2.toString(), artifact.toM2Coordinates());
213 if (!mergeProps.containsKey(BUNDLE_SYMBOLICNAME.toString())
214 && !mergeProps.containsKey(ManifestConstants.SLC_ORIGIN_MANIFEST_NOT_MODIFIED.toString())) {
215 // use file name as symbolic name
216 String symbolicName = p.getFileName().toString();
217 symbolicName = symbolicName.substring(0, symbolicName.length() - ".bnd".length());
218 mergeProps.put(BUNDLE_SYMBOLICNAME.toString(), symbolicName);
219 }
220
221 String repoStr = mergeProps.containsKey(SLC_ORIGIN_M2_REPO.toString())
222 ? mergeProps.getProperty(SLC_ORIGIN_M2_REPO.toString())
223 : null;
224
225 // download
226 URL url = MavenConventionsUtils.mavenRepoUrl(repoStr, artifact);
227 Path downloaded = download(url, originBase, artifact);
228
229 Path targetBundleDir = processBndJar(downloaded, targetCategoryBase, mergeProps, artifact);
230 // logger.log(Level.DEBUG, () -> "Processed " + downloaded);
231
232 // sources
233 downloadAndProcessM2Sources(repoStr, artifact, targetBundleDir);
234
235 createJar(targetBundleDir);
236 }
237 } catch (IOException e) {
238 throw new RuntimeException("Cannot process " + duDir, e);
239 }
240
241 }
242
243 /** Merge multiple Maven artifacts. */
244 protected void mergeM2Artifacts(Path mergeBnd) throws IOException {
245 Path duDir = mergeBnd.getParent();
246 String category = duDir.getParent().getFileName().toString();
247 Path targetCategoryBase = a2Base.resolve(category);
248
249 Properties mergeProps = new Properties();
250 try (InputStream in = Files.newInputStream(mergeBnd)) {
251 mergeProps.load(in);
252 }
253
254 // Version
255 String m2Version = mergeProps.getProperty(SLC_ORIGIN_M2.toString());
256 if (m2Version == null) {
257 logger.log(Level.WARNING, "Ignoring " + duDir + " as it is not an M2-based distribution unit");
258 return;// ignore, this is probably an Eclipse archive
259 }
260 if (!m2Version.startsWith(":")) {
261 throw new IllegalStateException("Only the M2 version can be specified: " + m2Version);
262 }
263 m2Version = m2Version.substring(1);
264 mergeProps.put(ManifestConstants.BUNDLE_VERSION.toString(), m2Version);
265
266 String artifactsStr = mergeProps.getProperty(ManifestConstants.SLC_ORIGIN_M2_MERGE.toString());
267 String repoStr = mergeProps.containsKey(SLC_ORIGIN_M2_REPO.toString())
268 ? mergeProps.getProperty(SLC_ORIGIN_M2_REPO.toString())
269 : null;
270
271 String bundleSymbolicName = mergeProps.getProperty(ManifestConstants.BUNDLE_SYMBOLICNAME.toString());
272 if (bundleSymbolicName == null)
273 throw new IllegalArgumentException("Bundle-SymbolicName must be set in " + mergeBnd);
274 DefaultCategoryNameVersion nameVersion = new DefaultArtifact(
275 category + ":" + bundleSymbolicName + ":" + m2Version);
276 Path targetBundleDir = targetCategoryBase.resolve(bundleSymbolicName + "." + nameVersion.getBranch());
277
278 String[] artifacts = artifactsStr.split(",");
279 artifacts: for (String str : artifacts) {
280 String m2Coordinates = str.trim();
281 if ("".equals(m2Coordinates))
282 continue artifacts;
283 DefaultArtifact artifact = new DefaultArtifact(m2Coordinates.trim());
284 if (artifact.getVersion() == null)
285 artifact.setVersion(m2Version);
286 URL url = MavenConventionsUtils.mavenRepoUrl(repoStr, artifact);
287 Path downloaded = download(url, originBase, artifact);
288 JarEntry entry;
289 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(downloaded), false)) {
290 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
291 if (entry.isDirectory())
292 continue entries;
293 if (entry.getName().endsWith(".RSA") || entry.getName().endsWith(".SF"))
294 continue entries;
295 if (entry.getName().startsWith("META-INF/versions/"))
296 continue entries;
297 if (entry.getName().startsWith("META-INF/maven/"))
298 continue entries;
299 if (entry.getName().equals("module-info.class"))
300 continue entries;
301 if (entry.getName().equals("META-INF/NOTICE"))
302 continue entries;
303 if (entry.getName().equals("META-INF/LICENSE"))
304 continue entries;
305 Path target = targetBundleDir.resolve(entry.getName());
306 Files.createDirectories(target.getParent());
307 if (!Files.exists(target)) {
308 Files.copy(jarIn, target);
309 } else {
310 if (entry.getName().startsWith("META-INF/services/")) {
311 try (OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND)) {
312 out.write("\n".getBytes());
313 jarIn.transferTo(out);
314 if (logger.isLoggable(DEBUG))
315 logger.log(DEBUG, artifact.getArtifactId() + " - Appended " + entry.getName());
316 }
317 } else if (entry.getName().startsWith("org/apache/batik/")) {
318 logger.log(Level.WARNING, "Skip " + entry.getName());
319 continue entries;
320 } else {
321 throw new IllegalStateException("File " + target + " from " + artifact + " already exists");
322 }
323 }
324 logger.log(Level.TRACE, () -> "Copied " + target);
325 }
326
327 }
328 downloadAndProcessM2Sources(repoStr, artifact, targetBundleDir);
329 }
330
331 // additional service files
332 Path servicesDir = duDir.resolve("services");
333 if (Files.exists(servicesDir)) {
334 for (Path p : Files.newDirectoryStream(servicesDir)) {
335 Path target = targetBundleDir.resolve("META-INF/services/").resolve(p.getFileName());
336 try (InputStream in = Files.newInputStream(p);
337 OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND);) {
338 out.write("\n".getBytes());
339 in.transferTo(out);
340 if (logger.isLoggable(DEBUG))
341 logger.log(DEBUG, "Appended " + p);
342 }
343 }
344 }
345
346 Map<String, String> entries = new TreeMap<>();
347 try (Analyzer bndAnalyzer = new Analyzer()) {
348 bndAnalyzer.setProperties(mergeProps);
349 Jar jar = new Jar(targetBundleDir.toFile());
350 bndAnalyzer.setJar(jar);
351 Manifest manifest = bndAnalyzer.calcManifest();
352
353 keys: for (Object key : manifest.getMainAttributes().keySet()) {
354 Object value = manifest.getMainAttributes().get(key);
355
356 switch (key.toString()) {
357 case "Tool":
358 case "Bnd-LastModified":
359 case "Created-By":
360 continue keys;
361 }
362 if ("Require-Capability".equals(key.toString())
363 && value.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
364 continue keys;// hack for very old classes
365 entries.put(key.toString(), value.toString());
366 // logger.log(DEBUG, () -> key + "=" + value);
367
368 }
369 } catch (Exception e) {
370 throw new RuntimeException("Cannot process " + mergeBnd, e);
371 }
372
373 Manifest manifest = new Manifest();
374 Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
375 Files.createDirectories(manifestPath.getParent());
376 for (String key : entries.keySet()) {
377 String value = entries.get(key);
378 manifest.getMainAttributes().putValue(key, value);
379 }
380
381 // // Use Maven version as Bundle-Version
382 // String bundleVersion = manifest.getMainAttributes().getValue(ManifestConstants.BUNDLE_VERSION.toString());
383 // if (bundleVersion == null || bundleVersion.trim().equals("0")) {
384 // // TODO check why it is sometimes set to "0"
385 // manifest.getMainAttributes().putValue(ManifestConstants.BUNDLE_VERSION.toString(), m2Version);
386 // }
387 try (OutputStream out = Files.newOutputStream(manifestPath)) {
388 manifest.write(out);
389 }
390
391 createJar(targetBundleDir);
392
393 }
394
395 /** Generate MANIFEST using BND. */
396 protected Path processBndJar(Path downloaded, Path targetCategoryBase, Properties fileProps,
397 DefaultArtifact artifact) {
398
399 try {
400 Map<String, String> additionalEntries = new TreeMap<>();
401 boolean doNotModify = Boolean.parseBoolean(fileProps
402 .getOrDefault(ManifestConstants.SLC_ORIGIN_MANIFEST_NOT_MODIFIED.toString(), "false").toString());
403
404 // we always force the symbolic name
405
406 if (doNotModify) {
407 fileEntries: for (Object key : fileProps.keySet()) {
408 if (ManifestConstants.SLC_ORIGIN_M2.toString().equals(key))
409 continue fileEntries;
410 String value = fileProps.getProperty(key.toString());
411 additionalEntries.put(key.toString(), value);
412 }
413 } else {
414 if (artifact != null) {
415 if (!fileProps.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
416 fileProps.put(BUNDLE_SYMBOLICNAME.toString(), artifact.getName());
417 }
418 if (!fileProps.containsKey(BUNDLE_VERSION.toString())) {
419 fileProps.put(BUNDLE_VERSION.toString(), artifact.getVersion());
420 }
421 }
422
423 if (!fileProps.containsKey(EXPORT_PACKAGE.toString())) {
424 fileProps.put(EXPORT_PACKAGE.toString(),
425 "*;version=\"" + fileProps.getProperty(BUNDLE_VERSION.toString()) + "\"");
426 }
427 // if (!fileProps.contains(IMPORT_PACKAGE.toString())) {
428 // fileProps.put(IMPORT_PACKAGE.toString(), "*");
429 // }
430
431 try (Analyzer bndAnalyzer = new Analyzer()) {
432 bndAnalyzer.setProperties(fileProps);
433 Jar jar = new Jar(downloaded.toFile());
434 bndAnalyzer.setJar(jar);
435 Manifest manifest = bndAnalyzer.calcManifest();
436
437 keys: for (Object key : manifest.getMainAttributes().keySet()) {
438 Object value = manifest.getMainAttributes().get(key);
439
440 switch (key.toString()) {
441 case "Tool":
442 case "Bnd-LastModified":
443 case "Created-By":
444 continue keys;
445 }
446 if ("Require-Capability".equals(key.toString())
447 && value.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
448 continue keys;// hack for very old classes
449 additionalEntries.put(key.toString(), value.toString());
450 // logger.log(DEBUG, () -> key + "=" + value);
451
452 }
453 }
454
455 // try (Builder bndBuilder = new Builder()) {
456 // Jar jar = new Jar(downloaded.toFile());
457 // bndBuilder.addClasspath(jar);
458 // Path targetBundleDir = targetCategoryBase.resolve(artifact.getName() + "." + artifact.getBranch());
459 //
460 // Jar target = new Jar(targetBundleDir.toFile());
461 // bndBuilder.setJar(target);
462 // return targetBundleDir;
463 // }
464 }
465 Path targetBundleDir = processBundleJar(downloaded, targetCategoryBase, additionalEntries);
466 logger.log(Level.DEBUG, () -> "Processed " + downloaded);
467 return targetBundleDir;
468 } catch (Exception e) {
469 throw new RuntimeException("Cannot BND process " + downloaded, e);
470 }
471
472 }
473
474 /** Download and integrates sources for a single Maven artifact. */
475 protected void downloadAndProcessM2Sources(String repoStr, DefaultArtifact artifact, Path targetBundleDir)
476 throws IOException {
477 DefaultArtifact sourcesArtifact = new DefaultArtifact(artifact.toM2Coordinates(), "sources");
478 URL sourcesUrl = MavenConventionsUtils.mavenRepoUrl(repoStr, sourcesArtifact);
479 Path sourcesDownloaded = download(sourcesUrl, originBase, artifact, true);
480 processM2SourceJar(sourcesDownloaded, targetBundleDir);
481 logger.log(Level.TRACE, () -> "Processed source " + sourcesDownloaded);
482
483 }
484
485 /** Integrate sources from a downloaded jar file. */
486 protected void processM2SourceJar(Path file, Path targetBundleDir) throws IOException {
487 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
488 Path targetSourceDir = targetBundleDir.resolve("OSGI-OPT/src");
489
490 // TODO make it less dangerous?
491 if (Files.exists(targetSourceDir)) {
492 // deleteDirectory(targetSourceDir);
493 } else {
494 Files.createDirectories(targetSourceDir);
495 }
496
497 // copy entries
498 JarEntry entry;
499 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
500 if (entry.isDirectory())
501 continue entries;
502 if (entry.getName().startsWith("META-INF"))// skip META-INF entries
503 continue entries;
504 if (entry.getName().startsWith("module-info.java"))// skip META-INF entries
505 continue entries;
506 if (entry.getName().startsWith("/")) // absolute paths
507 continue entries;
508 Path target = targetSourceDir.resolve(entry.getName());
509 Files.createDirectories(target.getParent());
510 if (!Files.exists(target)) {
511 Files.copy(jarIn, target);
512 logger.log(Level.TRACE, () -> "Copied source " + target);
513 } else {
514 logger.log(Level.WARNING, () -> target + " already exists, skipping...");
515 }
516 }
517 }
518
519 }
520
521 /** Download a Maven artifact. */
522 protected Path download(URL url, Path dir, Artifact artifact) throws IOException {
523 return download(url, dir, artifact, false);
524 }
525
526 /** Download a Maven artifact. */
527 protected Path download(URL url, Path dir, Artifact artifact, boolean sources) throws IOException {
528 return download(url, dir, artifact.getGroupId() + '/' + artifact.getArtifactId() + "-" + artifact.getVersion()
529 + (sources ? "-sources" : "") + ".jar");
530 }
531
532 /*
533 * ECLIPSE ORIGIN
534 */
535
536 /** Process an archive in Eclipse format. */
537 public void processEclipseArchive(Path duDir) {
538 try {
539 String category = duDir.getParent().getFileName().toString();
540 Path targetCategoryBase = a2Base.resolve(category);
541 Files.createDirectories(targetCategoryBase);
542 // first delete all directories from previous builds
543 for (Path dir : Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p))) {
544 deleteDirectory(dir);
545 }
546
547 Files.createDirectories(originBase);
548
549 Path commonBnd = duDir.resolve(COMMON_BND);
550 Properties commonProps = new Properties();
551 try (InputStream in = Files.newInputStream(commonBnd)) {
552 commonProps.load(in);
553 }
554 String url = commonProps.getProperty(ManifestConstants.SLC_ORIGIN_URI.toString());
555 Path downloaded = tryDownload(url, originBase);
556
557 FileSystem zipFs = FileSystems.newFileSystem(downloaded, (ClassLoader) null);
558
559 // filters
560 List<PathMatcher> includeMatchers = new ArrayList<>();
561 Properties includes = new Properties();
562 try (InputStream in = Files.newInputStream(duDir.resolve("includes.properties"))) {
563 includes.load(in);
564 }
565 for (Object pattern : includes.keySet()) {
566 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
567 includeMatchers.add(pathMatcher);
568 }
569
570 List<PathMatcher> excludeMatchers = new ArrayList<>();
571 Path excludeFile = duDir.resolve("excludes.properties");
572 if (Files.exists(excludeFile)) {
573 Properties excludes = new Properties();
574 try (InputStream in = Files.newInputStream(excludeFile)) {
575 excludes.load(in);
576 }
577 for (Object pattern : excludes.keySet()) {
578 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
579 excludeMatchers.add(pathMatcher);
580 }
581 }
582
583 Files.walkFileTree(zipFs.getRootDirectories().iterator().next(), new SimpleFileVisitor<Path>() {
584
585 @Override
586 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
587 includeMatchers: for (PathMatcher includeMatcher : includeMatchers) {
588 if (includeMatcher.matches(file)) {
589 for (PathMatcher excludeMatcher : excludeMatchers) {
590 if (excludeMatcher.matches(file)) {
591 logger.log(Level.WARNING, "Skipping excluded " + file);
592 return FileVisitResult.CONTINUE;
593 }
594 }
595 if (file.getFileName().toString().contains(".source_")) {
596 processEclipseSourceJar(file, targetCategoryBase);
597 logger.log(Level.DEBUG, () -> "Processed source " + file);
598
599 } else {
600 processBundleJar(file, targetCategoryBase, new HashMap<>());
601 logger.log(Level.DEBUG, () -> "Processed " + file);
602 }
603 break includeMatchers;
604 }
605 }
606 return FileVisitResult.CONTINUE;
607 }
608 });
609
610 DirectoryStream<Path> dirs = Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p));
611 for (Path dir : dirs) {
612 createJar(dir);
613 }
614 } catch (IOException e) {
615 throw new RuntimeException("Cannot process " + duDir, e);
616 }
617
618 }
619
620 /** Process sources in Eclipse format. */
621 protected void processEclipseSourceJar(Path file, Path targetBase) throws IOException {
622 try {
623 Path targetBundleDir;
624 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
625 Manifest manifest = jarIn.getManifest();
626
627 String[] relatedBundle = manifest.getMainAttributes().getValue("Eclipse-SourceBundle").split(";");
628 String version = relatedBundle[1].substring("version=\"".length());
629 version = version.substring(0, version.length() - 1);
630 NameVersion nameVersion = new DefaultNameVersion(relatedBundle[0], version);
631 targetBundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
632
633 Path targetSourceDir = targetBundleDir.resolve("OSGI-OPT/src");
634
635 // TODO make it less dangerous?
636 if (Files.exists(targetSourceDir)) {
637 // deleteDirectory(targetSourceDir);
638 } else {
639 Files.createDirectories(targetSourceDir);
640 }
641
642 // copy entries
643 JarEntry entry;
644 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
645 if (entry.isDirectory())
646 continue entries;
647 if (entry.getName().startsWith("META-INF"))// skip META-INF entries
648 continue entries;
649 Path target = targetSourceDir.resolve(entry.getName());
650 Files.createDirectories(target.getParent());
651 Files.copy(jarIn, target);
652 logger.log(Level.TRACE, () -> "Copied source " + target);
653 }
654
655 // copy MANIFEST
656 // Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
657 // Files.createDirectories(manifestPath.getParent());
658 // try (OutputStream out = Files.newOutputStream(manifestPath)) {
659 // manifest.write(out);
660 // }
661 }
662 } catch (IOException e) {
663 throw new IllegalStateException("Cannot process " + file, e);
664 }
665
666 }
667
668 /*
669 * COMMON PROCESSING
670 */
671 /** Normalise a bundle. */
672 protected Path processBundleJar(Path file, Path targetBase, Map<String, String> entries) throws IOException {
673 DefaultNameVersion nameVersion;
674 Path targetBundleDir;
675 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
676 Manifest sourceManifest = jarIn.getManifest();
677 Manifest manifest = sourceManifest != null ? new Manifest(sourceManifest) : new Manifest();
678
679 // remove problematic entries in MANIFEST
680 manifest.getEntries().clear();
681 // Set<String> entriesToDelete = new HashSet<>();
682 // for (String key : manifest.getEntries().keySet()) {
683 //// logger.log(DEBUG, "## " + key);
684 // Attributes attrs = manifest.getAttributes(key);
685 // for (Object attrName : attrs.keySet()) {
686 //// logger.log(DEBUG, attrName + "=" + attrs.get(attrName));
687 // if ("Specification-Version".equals(attrName.toString())
688 // || "Implementation-Version".equals(attrName.toString())) {
689 // entriesToDelete.add(key);
690 //
691 // }
692 // }
693 // }
694 // for (String key : entriesToDelete) {
695 // manifest.getEntries().remove(key);
696 // }
697
698 String symbolicNameFromEntries = entries.get(BUNDLE_SYMBOLICNAME.toString());
699 String versionFromEntries = entries.get(BUNDLE_VERSION.toString());
700
701 if (symbolicNameFromEntries != null && versionFromEntries != null) {
702 nameVersion = new DefaultNameVersion(symbolicNameFromEntries, versionFromEntries);
703 } else {
704 nameVersion = nameVersionFromManifest(manifest);
705 if (versionFromEntries != null && !nameVersion.getVersion().equals(versionFromEntries)) {
706 logger.log(Level.WARNING, "Original version is " + nameVersion.getVersion()
707 + " while new version is " + versionFromEntries);
708 }
709 if (symbolicNameFromEntries != null) {
710 // we always force our symbolic name
711 nameVersion.setName(symbolicNameFromEntries);
712 }
713 }
714 targetBundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
715
716 // TODO make it less dangerous?
717 // if (Files.exists(targetBundleDir)) {
718 // deleteDirectory(targetBundleDir);
719 // }
720
721 // copy entries
722 JarEntry entry;
723 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
724 if (entry.isDirectory())
725 continue entries;
726 if (entry.getName().endsWith(".RSA") || entry.getName().endsWith(".SF"))
727 continue entries;
728 Path target = targetBundleDir.resolve(entry.getName());
729 Files.createDirectories(target.getParent());
730 Files.copy(jarIn, target);
731 logger.log(Level.TRACE, () -> "Copied " + target);
732 }
733
734 // copy MANIFEST
735 Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
736 Files.createDirectories(manifestPath.getParent());
737 for (String key : entries.keySet()) {
738 String value = entries.get(key);
739 Object previousValue = manifest.getMainAttributes().putValue(key, value);
740 if (previousValue != null && !previousValue.equals(value)) {
741 if (ManifestConstants.IMPORT_PACKAGE.toString().equals(key)
742 || ManifestConstants.EXPORT_PACKAGE.toString().equals(key))
743 logger.log(Level.WARNING, file.getFileName() + ": " + key + " was modified");
744
745 else
746 logger.log(Level.WARNING, file.getFileName() + ": " + key + " was " + previousValue
747 + ", overridden with " + value);
748 }
749 }
750 try (OutputStream out = Files.newOutputStream(manifestPath)) {
751 manifest.write(out);
752 }
753 }
754 return targetBundleDir;
755 }
756
757 /*
758 * UTILITIES
759 */
760
761 /** Recursively deletes a directory. */
762 private static void deleteDirectory(Path path) throws IOException {
763 if (!Files.exists(path))
764 return;
765 Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
766 @Override
767 public FileVisitResult postVisitDirectory(Path directory, IOException e) throws IOException {
768 if (e != null)
769 throw e;
770 Files.delete(directory);
771 return FileVisitResult.CONTINUE;
772 }
773
774 @Override
775 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
776 Files.delete(file);
777 return FileVisitResult.CONTINUE;
778 }
779 });
780 }
781
782 /** Extract name/version from a MANIFEST. */
783 protected DefaultNameVersion nameVersionFromManifest(Manifest manifest) {
784 Attributes attrs = manifest.getMainAttributes();
785 // symbolic name
786 String symbolicName = attrs.getValue(ManifestConstants.BUNDLE_SYMBOLICNAME.toString());
787 if (symbolicName == null)
788 return null;
789 // make sure there is no directive
790 symbolicName = symbolicName.split(";")[0];
791
792 String version = attrs.getValue(ManifestConstants.BUNDLE_VERSION.toString());
793 return new DefaultNameVersion(symbolicName, version);
794 }
795
796 /** Try to download from an URI. */
797 protected Path tryDownload(String uri, Path dir) throws IOException {
798 // find mirror
799 List<String> urlBases = null;
800 String uriPrefix = null;
801 uriPrefixes: for (String uriPref : mirrors.keySet()) {
802 if (uri.startsWith(uriPref)) {
803 if (mirrors.get(uriPref).size() > 0) {
804 urlBases = mirrors.get(uriPref);
805 uriPrefix = uriPref;
806 break uriPrefixes;
807 }
808 }
809 }
810 if (urlBases == null)
811 try {
812 return download(new URL(uri), dir);
813 } catch (FileNotFoundException e) {
814 throw new FileNotFoundException("Cannot find " + uri);
815 }
816
817 // try to download
818 for (String urlBase : urlBases) {
819 String relativePath = uri.substring(uriPrefix.length());
820 URL url = new URL(urlBase + relativePath);
821 try {
822 return download(url, dir);
823 } catch (FileNotFoundException e) {
824 logger.log(Level.WARNING, "Cannot download " + url + ", trying another mirror");
825 }
826 }
827 throw new FileNotFoundException("Cannot find " + uri);
828 }
829
830 // protected String simplifyName(URL u) {
831 // String name = u.getPath().substring(u.getPath().lastIndexOf('/') + 1);
832 //
833 // }
834
835 /** Effectively download. */
836 protected Path download(URL url, Path dir) throws IOException {
837 return download(url, dir, (String) null);
838 }
839
840 /** Effectively download. */
841 protected Path download(URL url, Path dir, String name) throws IOException {
842
843 Path dest;
844 if (name == null) {
845 name = url.getPath().substring(url.getPath().lastIndexOf('/') + 1);
846 }
847
848 dest = dir.resolve(name);
849 if (Files.exists(dest)) {
850 logger.log(Level.TRACE, () -> "File " + dest + " already exists for " + url + ", not downloading again");
851 return dest;
852 } else {
853 Files.createDirectories(dest.getParent());
854 }
855
856 try (InputStream in = url.openStream()) {
857 Files.copy(in, dest);
858 logger.log(Level.DEBUG, () -> "Downloaded " + dest + " from " + url);
859 }
860 return dest;
861 }
862
863 /** Create a JAR file from a directory. */
864 protected Path createJar(Path bundleDir) throws IOException {
865 // Remove from source the resources already in the jar file
866 // Path srcDir = bundleDir.resolve("OSGI-OPT/src");
867 // Files.walkFileTree(srcDir, new SimpleFileVisitor<Path>() {
868 //
869 // @Override
870 // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
871 // // always keep .java file
872 // if (file.getFileName().toString().endsWith(".java"))
873 // return super.visitFile(file, attrs);
874 //
875 // Path relPath = srcDir.relativize(file);
876 // Path bundlePath = bundleDir.resolve(relPath);
877 // if (Files.exists(bundlePath)) {
878 // Files.delete(file);
879 // logger.log(DEBUG, () -> "Removed " + file + " from sources.");
880 // }
881 // return super.visitFile(file, attrs);
882 // }
883 //
884 // });
885
886 // Create the jar
887 Path jarPath = bundleDir.getParent().resolve(bundleDir.getFileName() + ".jar");
888 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
889 Manifest manifest;
890 try (InputStream in = Files.newInputStream(manifestPath)) {
891 manifest = new Manifest(in);
892 }
893 try (JarOutputStream jarOut = new JarOutputStream(Files.newOutputStream(jarPath), manifest)) {
894 jarOut.setLevel(Deflater.DEFAULT_COMPRESSION);
895 Files.walkFileTree(bundleDir, new SimpleFileVisitor<Path>() {
896
897 @Override
898 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
899 if (file.getFileName().toString().equals("MANIFEST.MF"))
900 return super.visitFile(file, attrs);
901 JarEntry entry = new JarEntry(bundleDir.relativize(file).toString());
902 jarOut.putNextEntry(entry);
903 Files.copy(file, jarOut);
904 return super.visitFile(file, attrs);
905 }
906
907 });
908 }
909 deleteDirectory(bundleDir);
910 return jarPath;
911 }
912
913 /** For development purproses. */
914 public static void main(String[] args) {
915 Path factoryBase = Paths.get("../../output/a2").toAbsolutePath().normalize();
916 A2Factory factory = new A2Factory(factoryBase);
917
918 Path descriptorsBase = Paths.get("../tp").toAbsolutePath().normalize();
919
920 // factory.processSingleM2ArtifactDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache").resolve("org.apache.xml.resolver.bnd"));
921 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache/apache-sshd"));
922 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.jetty/jetty"));
923 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.jetty/jetty-websocket"));
924 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.eclipse.rcp"));
925 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp"));
926 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.apache"));
927 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.formats"));
928 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.gis"));
929 System.exit(0);
930
931 // Eclipse
932 factory.processEclipseArchive(
933 descriptorsBase.resolve("org.argeo.tp.eclipse.equinox").resolve("eclipse-equinox"));
934 factory.processEclipseArchive(descriptorsBase.resolve("org.argeo.tp.eclipse.rwt").resolve("eclipse-rwt"));
935 factory.processEclipseArchive(descriptorsBase.resolve("org.argeo.tp.eclipse.rap").resolve("eclipse-rap"));
936 factory.processEclipseArchive(descriptorsBase.resolve("org.argeo.tp.eclipse.swt").resolve("eclipse-swt"));
937 factory.processEclipseArchive(descriptorsBase.resolve("org.argeo.tp.eclipse.swt").resolve("eclipse-nebula"));
938 factory.processEclipseArchive(descriptorsBase.resolve("org.argeo.tp.eclipse.swt").resolve("eclipse-equinox"));
939 factory.processEclipseArchive(descriptorsBase.resolve("org.argeo.tp.eclipse.rcp").resolve("eclipse-rcp"));
940 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.eclipse.rcp"));
941
942 // Maven
943 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.sdk"));
944 factory.processCategory(descriptorsBase.resolve("org.argeo.tp"));
945 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.apache"));
946 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.jetty"));
947 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.jcr"));
948 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.formats"));
949 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.poi"));
950 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.gis"));
951 }
952 }