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