]> git.argeo.org Git - gpl/argeo-slc.git/blob - org.argeo.slc.factory/src/org/argeo/slc/factory/A2Factory.java
Move backup to SLC runtime.
[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/NOTICE.txt"))
304 continue entries;
305 if (entry.getName().equals("META-INF/LICENSE"))
306 continue entries;
307 Path target = targetBundleDir.resolve(entry.getName());
308 Files.createDirectories(target.getParent());
309 if (!Files.exists(target)) {
310 Files.copy(jarIn, target);
311 } else {
312 if (entry.getName().startsWith("META-INF/services/")) {
313 try (OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND)) {
314 out.write("\n".getBytes());
315 jarIn.transferTo(out);
316 if (logger.isLoggable(DEBUG))
317 logger.log(DEBUG, artifact.getArtifactId() + " - Appended " + entry.getName());
318 }
319 } else if (entry.getName().startsWith("org/apache/batik/")) {
320 logger.log(Level.WARNING, "Skip " + entry.getName());
321 continue entries;
322 } else {
323 throw new IllegalStateException("File " + target + " from " + artifact + " already exists");
324 }
325 }
326 logger.log(Level.TRACE, () -> "Copied " + target);
327 }
328
329 }
330 downloadAndProcessM2Sources(repoStr, artifact, targetBundleDir);
331 }
332
333 // additional service files
334 Path servicesDir = duDir.resolve("services");
335 if (Files.exists(servicesDir)) {
336 for (Path p : Files.newDirectoryStream(servicesDir)) {
337 Path target = targetBundleDir.resolve("META-INF/services/").resolve(p.getFileName());
338 try (InputStream in = Files.newInputStream(p);
339 OutputStream out = Files.newOutputStream(target, StandardOpenOption.APPEND);) {
340 out.write("\n".getBytes());
341 in.transferTo(out);
342 if (logger.isLoggable(DEBUG))
343 logger.log(DEBUG, "Appended " + p);
344 }
345 }
346 }
347
348 Map<String, String> entries = new TreeMap<>();
349 try (Analyzer bndAnalyzer = new Analyzer()) {
350 bndAnalyzer.setProperties(mergeProps);
351 Jar jar = new Jar(targetBundleDir.toFile());
352 bndAnalyzer.setJar(jar);
353 Manifest manifest = bndAnalyzer.calcManifest();
354
355 keys: for (Object key : manifest.getMainAttributes().keySet()) {
356 Object value = manifest.getMainAttributes().get(key);
357
358 switch (key.toString()) {
359 case "Tool":
360 case "Bnd-LastModified":
361 case "Created-By":
362 continue keys;
363 }
364 if ("Require-Capability".equals(key.toString())
365 && value.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
366 continue keys;// hack for very old classes
367 entries.put(key.toString(), value.toString());
368 // logger.log(DEBUG, () -> key + "=" + value);
369
370 }
371 } catch (Exception e) {
372 throw new RuntimeException("Cannot process " + mergeBnd, e);
373 }
374
375 Manifest manifest = new Manifest();
376 Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
377 Files.createDirectories(manifestPath.getParent());
378 for (String key : entries.keySet()) {
379 String value = entries.get(key);
380 manifest.getMainAttributes().putValue(key, value);
381 }
382
383 // // Use Maven version as Bundle-Version
384 // String bundleVersion = manifest.getMainAttributes().getValue(ManifestConstants.BUNDLE_VERSION.toString());
385 // if (bundleVersion == null || bundleVersion.trim().equals("0")) {
386 // // TODO check why it is sometimes set to "0"
387 // manifest.getMainAttributes().putValue(ManifestConstants.BUNDLE_VERSION.toString(), m2Version);
388 // }
389 try (OutputStream out = Files.newOutputStream(manifestPath)) {
390 manifest.write(out);
391 }
392
393 createJar(targetBundleDir);
394
395 }
396
397 /** Generate MANIFEST using BND. */
398 protected Path processBndJar(Path downloaded, Path targetCategoryBase, Properties fileProps,
399 DefaultArtifact artifact) {
400
401 try {
402 Map<String, String> additionalEntries = new TreeMap<>();
403 boolean doNotModify = Boolean.parseBoolean(fileProps
404 .getOrDefault(ManifestConstants.SLC_ORIGIN_MANIFEST_NOT_MODIFIED.toString(), "false").toString());
405
406 // we always force the symbolic name
407
408 if (doNotModify) {
409 fileEntries: for (Object key : fileProps.keySet()) {
410 if (ManifestConstants.SLC_ORIGIN_M2.toString().equals(key))
411 continue fileEntries;
412 String value = fileProps.getProperty(key.toString());
413 additionalEntries.put(key.toString(), value);
414 }
415 } else {
416 if (artifact != null) {
417 if (!fileProps.containsKey(BUNDLE_SYMBOLICNAME.toString())) {
418 fileProps.put(BUNDLE_SYMBOLICNAME.toString(), artifact.getName());
419 }
420 if (!fileProps.containsKey(BUNDLE_VERSION.toString())) {
421 fileProps.put(BUNDLE_VERSION.toString(), artifact.getVersion());
422 }
423 }
424
425 if (!fileProps.containsKey(EXPORT_PACKAGE.toString())) {
426 fileProps.put(EXPORT_PACKAGE.toString(),
427 "*;version=\"" + fileProps.getProperty(BUNDLE_VERSION.toString()) + "\"");
428 }
429 // if (!fileProps.contains(IMPORT_PACKAGE.toString())) {
430 // fileProps.put(IMPORT_PACKAGE.toString(), "*");
431 // }
432
433 try (Analyzer bndAnalyzer = new Analyzer()) {
434 bndAnalyzer.setProperties(fileProps);
435 Jar jar = new Jar(downloaded.toFile());
436 bndAnalyzer.setJar(jar);
437 Manifest manifest = bndAnalyzer.calcManifest();
438
439 keys: for (Object key : manifest.getMainAttributes().keySet()) {
440 Object value = manifest.getMainAttributes().get(key);
441
442 switch (key.toString()) {
443 case "Tool":
444 case "Bnd-LastModified":
445 case "Created-By":
446 continue keys;
447 }
448 if ("Require-Capability".equals(key.toString())
449 && value.toString().equals("osgi.ee;filter:=\"(&(osgi.ee=JavaSE)(version=1.1))\""))
450 continue keys;// hack for very old classes
451 additionalEntries.put(key.toString(), value.toString());
452 // logger.log(DEBUG, () -> key + "=" + value);
453
454 }
455 }
456
457 // try (Builder bndBuilder = new Builder()) {
458 // Jar jar = new Jar(downloaded.toFile());
459 // bndBuilder.addClasspath(jar);
460 // Path targetBundleDir = targetCategoryBase.resolve(artifact.getName() + "." + artifact.getBranch());
461 //
462 // Jar target = new Jar(targetBundleDir.toFile());
463 // bndBuilder.setJar(target);
464 // return targetBundleDir;
465 // }
466 }
467 Path targetBundleDir = processBundleJar(downloaded, targetCategoryBase, additionalEntries);
468 logger.log(Level.DEBUG, () -> "Processed " + downloaded);
469 return targetBundleDir;
470 } catch (Exception e) {
471 throw new RuntimeException("Cannot BND process " + downloaded, e);
472 }
473
474 }
475
476 /** Download and integrates sources for a single Maven artifact. */
477 protected void downloadAndProcessM2Sources(String repoStr, DefaultArtifact artifact, Path targetBundleDir)
478 throws IOException {
479 DefaultArtifact sourcesArtifact = new DefaultArtifact(artifact.toM2Coordinates(), "sources");
480 URL sourcesUrl = MavenConventionsUtils.mavenRepoUrl(repoStr, sourcesArtifact);
481 Path sourcesDownloaded = download(sourcesUrl, originBase, artifact, true);
482 processM2SourceJar(sourcesDownloaded, targetBundleDir);
483 logger.log(Level.TRACE, () -> "Processed source " + sourcesDownloaded);
484
485 }
486
487 /** Integrate sources from a downloaded jar file. */
488 protected void processM2SourceJar(Path file, Path targetBundleDir) throws IOException {
489 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
490 Path targetSourceDir = targetBundleDir.resolve("OSGI-OPT/src");
491
492 // TODO make it less dangerous?
493 if (Files.exists(targetSourceDir)) {
494 // deleteDirectory(targetSourceDir);
495 } else {
496 Files.createDirectories(targetSourceDir);
497 }
498
499 // copy entries
500 JarEntry entry;
501 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
502 if (entry.isDirectory())
503 continue entries;
504 if (entry.getName().startsWith("META-INF"))// skip META-INF entries
505 continue entries;
506 if (entry.getName().startsWith("module-info.java"))// skip META-INF entries
507 continue entries;
508 if (entry.getName().startsWith("/")) // absolute paths
509 continue entries;
510 Path target = targetSourceDir.resolve(entry.getName());
511 Files.createDirectories(target.getParent());
512 if (!Files.exists(target)) {
513 Files.copy(jarIn, target);
514 logger.log(Level.TRACE, () -> "Copied source " + target);
515 } else {
516 logger.log(Level.WARNING, () -> target + " already exists, skipping...");
517 }
518 }
519 }
520
521 }
522
523 /** Download a Maven artifact. */
524 protected Path download(URL url, Path dir, Artifact artifact) throws IOException {
525 return download(url, dir, artifact, false);
526 }
527
528 /** Download a Maven artifact. */
529 protected Path download(URL url, Path dir, Artifact artifact, boolean sources) throws IOException {
530 return download(url, dir, artifact.getGroupId() + '/' + artifact.getArtifactId() + "-" + artifact.getVersion()
531 + (sources ? "-sources" : "") + ".jar");
532 }
533
534 /*
535 * ECLIPSE ORIGIN
536 */
537
538 /** Process an archive in Eclipse format. */
539 public void processEclipseArchive(Path duDir) {
540 try {
541 String category = duDir.getParent().getFileName().toString();
542 Path targetCategoryBase = a2Base.resolve(category);
543 Files.createDirectories(targetCategoryBase);
544 // first delete all directories from previous builds
545 for (Path dir : Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p))) {
546 deleteDirectory(dir);
547 }
548
549 Files.createDirectories(originBase);
550
551 Path commonBnd = duDir.resolve(COMMON_BND);
552 Properties commonProps = new Properties();
553 try (InputStream in = Files.newInputStream(commonBnd)) {
554 commonProps.load(in);
555 }
556 String url = commonProps.getProperty(ManifestConstants.SLC_ORIGIN_URI.toString());
557 Path downloaded = tryDownload(url, originBase);
558
559 FileSystem zipFs = FileSystems.newFileSystem(downloaded, (ClassLoader) null);
560
561 // filters
562 List<PathMatcher> includeMatchers = new ArrayList<>();
563 Properties includes = new Properties();
564 try (InputStream in = Files.newInputStream(duDir.resolve("includes.properties"))) {
565 includes.load(in);
566 }
567 for (Object pattern : includes.keySet()) {
568 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
569 includeMatchers.add(pathMatcher);
570 }
571
572 List<PathMatcher> excludeMatchers = new ArrayList<>();
573 Path excludeFile = duDir.resolve("excludes.properties");
574 if (Files.exists(excludeFile)) {
575 Properties excludes = new Properties();
576 try (InputStream in = Files.newInputStream(excludeFile)) {
577 excludes.load(in);
578 }
579 for (Object pattern : excludes.keySet()) {
580 PathMatcher pathMatcher = zipFs.getPathMatcher("glob:/" + pattern);
581 excludeMatchers.add(pathMatcher);
582 }
583 }
584
585 Files.walkFileTree(zipFs.getRootDirectories().iterator().next(), new SimpleFileVisitor<Path>() {
586
587 @Override
588 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
589 includeMatchers: for (PathMatcher includeMatcher : includeMatchers) {
590 if (includeMatcher.matches(file)) {
591 for (PathMatcher excludeMatcher : excludeMatchers) {
592 if (excludeMatcher.matches(file)) {
593 logger.log(Level.WARNING, "Skipping excluded " + file);
594 return FileVisitResult.CONTINUE;
595 }
596 }
597 if (file.getFileName().toString().contains(".source_")) {
598 processEclipseSourceJar(file, targetCategoryBase);
599 logger.log(Level.DEBUG, () -> "Processed source " + file);
600
601 } else {
602 processBundleJar(file, targetCategoryBase, new HashMap<>());
603 logger.log(Level.DEBUG, () -> "Processed " + file);
604 }
605 break includeMatchers;
606 }
607 }
608 return FileVisitResult.CONTINUE;
609 }
610 });
611
612 DirectoryStream<Path> dirs = Files.newDirectoryStream(targetCategoryBase, (p) -> Files.isDirectory(p));
613 for (Path dir : dirs) {
614 createJar(dir);
615 }
616 } catch (IOException e) {
617 throw new RuntimeException("Cannot process " + duDir, e);
618 }
619
620 }
621
622 /** Process sources in Eclipse format. */
623 protected void processEclipseSourceJar(Path file, Path targetBase) throws IOException {
624 try {
625 Path targetBundleDir;
626 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
627 Manifest manifest = jarIn.getManifest();
628
629 String[] relatedBundle = manifest.getMainAttributes().getValue("Eclipse-SourceBundle").split(";");
630 String version = relatedBundle[1].substring("version=\"".length());
631 version = version.substring(0, version.length() - 1);
632 NameVersion nameVersion = new DefaultNameVersion(relatedBundle[0], version);
633 targetBundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
634
635 Path targetSourceDir = targetBundleDir.resolve("OSGI-OPT/src");
636
637 // TODO make it less dangerous?
638 if (Files.exists(targetSourceDir)) {
639 // deleteDirectory(targetSourceDir);
640 } else {
641 Files.createDirectories(targetSourceDir);
642 }
643
644 // copy entries
645 JarEntry entry;
646 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
647 if (entry.isDirectory())
648 continue entries;
649 if (entry.getName().startsWith("META-INF"))// skip META-INF entries
650 continue entries;
651 Path target = targetSourceDir.resolve(entry.getName());
652 Files.createDirectories(target.getParent());
653 Files.copy(jarIn, target);
654 logger.log(Level.TRACE, () -> "Copied source " + target);
655 }
656
657 // copy MANIFEST
658 // Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
659 // Files.createDirectories(manifestPath.getParent());
660 // try (OutputStream out = Files.newOutputStream(manifestPath)) {
661 // manifest.write(out);
662 // }
663 }
664 } catch (IOException e) {
665 throw new IllegalStateException("Cannot process " + file, e);
666 }
667
668 }
669
670 /*
671 * COMMON PROCESSING
672 */
673 /** Normalise a bundle. */
674 protected Path processBundleJar(Path file, Path targetBase, Map<String, String> entries) throws IOException {
675 DefaultNameVersion nameVersion;
676 Path targetBundleDir;
677 try (JarInputStream jarIn = new JarInputStream(Files.newInputStream(file), false)) {
678 Manifest sourceManifest = jarIn.getManifest();
679 Manifest manifest = sourceManifest != null ? new Manifest(sourceManifest) : new Manifest();
680
681 // remove problematic entries in MANIFEST
682 manifest.getEntries().clear();
683 // Set<String> entriesToDelete = new HashSet<>();
684 // for (String key : manifest.getEntries().keySet()) {
685 //// logger.log(DEBUG, "## " + key);
686 // Attributes attrs = manifest.getAttributes(key);
687 // for (Object attrName : attrs.keySet()) {
688 //// logger.log(DEBUG, attrName + "=" + attrs.get(attrName));
689 // if ("Specification-Version".equals(attrName.toString())
690 // || "Implementation-Version".equals(attrName.toString())) {
691 // entriesToDelete.add(key);
692 //
693 // }
694 // }
695 // }
696 // for (String key : entriesToDelete) {
697 // manifest.getEntries().remove(key);
698 // }
699
700 String symbolicNameFromEntries = entries.get(BUNDLE_SYMBOLICNAME.toString());
701 String versionFromEntries = entries.get(BUNDLE_VERSION.toString());
702
703 if (symbolicNameFromEntries != null && versionFromEntries != null) {
704 nameVersion = new DefaultNameVersion(symbolicNameFromEntries, versionFromEntries);
705 } else {
706 nameVersion = nameVersionFromManifest(manifest);
707 if (versionFromEntries != null && !nameVersion.getVersion().equals(versionFromEntries)) {
708 logger.log(Level.WARNING, "Original version is " + nameVersion.getVersion()
709 + " while new version is " + versionFromEntries);
710 }
711 if (symbolicNameFromEntries != null) {
712 // we always force our symbolic name
713 nameVersion.setName(symbolicNameFromEntries);
714 }
715 }
716 targetBundleDir = targetBase.resolve(nameVersion.getName() + "." + nameVersion.getBranch());
717
718 // TODO make it less dangerous?
719 // if (Files.exists(targetBundleDir)) {
720 // deleteDirectory(targetBundleDir);
721 // }
722
723 // copy entries
724 JarEntry entry;
725 entries: while ((entry = jarIn.getNextJarEntry()) != null) {
726 if (entry.isDirectory())
727 continue entries;
728 if (entry.getName().endsWith(".RSA") || entry.getName().endsWith(".SF"))
729 continue entries;
730 Path target = targetBundleDir.resolve(entry.getName());
731 Files.createDirectories(target.getParent());
732 Files.copy(jarIn, target);
733 logger.log(Level.TRACE, () -> "Copied " + target);
734 }
735
736 // copy MANIFEST
737 Path manifestPath = targetBundleDir.resolve("META-INF/MANIFEST.MF");
738 Files.createDirectories(manifestPath.getParent());
739 for (String key : entries.keySet()) {
740 String value = entries.get(key);
741 Object previousValue = manifest.getMainAttributes().putValue(key, value);
742 if (previousValue != null && !previousValue.equals(value)) {
743 if (ManifestConstants.IMPORT_PACKAGE.toString().equals(key)
744 || ManifestConstants.EXPORT_PACKAGE.toString().equals(key))
745 logger.log(Level.WARNING, file.getFileName() + ": " + key + " was modified");
746
747 else
748 logger.log(Level.WARNING, file.getFileName() + ": " + key + " was " + previousValue
749 + ", overridden with " + value);
750 }
751 }
752 try (OutputStream out = Files.newOutputStream(manifestPath)) {
753 manifest.write(out);
754 }
755 }
756 return targetBundleDir;
757 }
758
759 /*
760 * UTILITIES
761 */
762
763 /** Recursively deletes a directory. */
764 private static void deleteDirectory(Path path) throws IOException {
765 if (!Files.exists(path))
766 return;
767 Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
768 @Override
769 public FileVisitResult postVisitDirectory(Path directory, IOException e) throws IOException {
770 if (e != null)
771 throw e;
772 Files.delete(directory);
773 return FileVisitResult.CONTINUE;
774 }
775
776 @Override
777 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
778 Files.delete(file);
779 return FileVisitResult.CONTINUE;
780 }
781 });
782 }
783
784 /** Extract name/version from a MANIFEST. */
785 protected DefaultNameVersion nameVersionFromManifest(Manifest manifest) {
786 Attributes attrs = manifest.getMainAttributes();
787 // symbolic name
788 String symbolicName = attrs.getValue(ManifestConstants.BUNDLE_SYMBOLICNAME.toString());
789 if (symbolicName == null)
790 return null;
791 // make sure there is no directive
792 symbolicName = symbolicName.split(";")[0];
793
794 String version = attrs.getValue(ManifestConstants.BUNDLE_VERSION.toString());
795 return new DefaultNameVersion(symbolicName, version);
796 }
797
798 /** Try to download from an URI. */
799 protected Path tryDownload(String uri, Path dir) throws IOException {
800 // find mirror
801 List<String> urlBases = null;
802 String uriPrefix = null;
803 uriPrefixes: for (String uriPref : mirrors.keySet()) {
804 if (uri.startsWith(uriPref)) {
805 if (mirrors.get(uriPref).size() > 0) {
806 urlBases = mirrors.get(uriPref);
807 uriPrefix = uriPref;
808 break uriPrefixes;
809 }
810 }
811 }
812 if (urlBases == null)
813 try {
814 return download(new URL(uri), dir);
815 } catch (FileNotFoundException e) {
816 throw new FileNotFoundException("Cannot find " + uri);
817 }
818
819 // try to download
820 for (String urlBase : urlBases) {
821 String relativePath = uri.substring(uriPrefix.length());
822 URL url = new URL(urlBase + relativePath);
823 try {
824 return download(url, dir);
825 } catch (FileNotFoundException e) {
826 logger.log(Level.WARNING, "Cannot download " + url + ", trying another mirror");
827 }
828 }
829 throw new FileNotFoundException("Cannot find " + uri);
830 }
831
832 // protected String simplifyName(URL u) {
833 // String name = u.getPath().substring(u.getPath().lastIndexOf('/') + 1);
834 //
835 // }
836
837 /** Effectively download. */
838 protected Path download(URL url, Path dir) throws IOException {
839 return download(url, dir, (String) null);
840 }
841
842 /** Effectively download. */
843 protected Path download(URL url, Path dir, String name) throws IOException {
844
845 Path dest;
846 if (name == null) {
847 name = url.getPath().substring(url.getPath().lastIndexOf('/') + 1);
848 }
849
850 dest = dir.resolve(name);
851 if (Files.exists(dest)) {
852 logger.log(Level.TRACE, () -> "File " + dest + " already exists for " + url + ", not downloading again");
853 return dest;
854 } else {
855 Files.createDirectories(dest.getParent());
856 }
857
858 try (InputStream in = url.openStream()) {
859 Files.copy(in, dest);
860 logger.log(Level.DEBUG, () -> "Downloaded " + dest + " from " + url);
861 }
862 return dest;
863 }
864
865 /** Create a JAR file from a directory. */
866 protected Path createJar(Path bundleDir) throws IOException {
867 // Remove from source the resources already in the jar file
868 // Path srcDir = bundleDir.resolve("OSGI-OPT/src");
869 // Files.walkFileTree(srcDir, new SimpleFileVisitor<Path>() {
870 //
871 // @Override
872 // public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
873 // // always keep .java file
874 // if (file.getFileName().toString().endsWith(".java"))
875 // return super.visitFile(file, attrs);
876 //
877 // Path relPath = srcDir.relativize(file);
878 // Path bundlePath = bundleDir.resolve(relPath);
879 // if (Files.exists(bundlePath)) {
880 // Files.delete(file);
881 // logger.log(DEBUG, () -> "Removed " + file + " from sources.");
882 // }
883 // return super.visitFile(file, attrs);
884 // }
885 //
886 // });
887
888 // Create the jar
889 Path jarPath = bundleDir.getParent().resolve(bundleDir.getFileName() + ".jar");
890 Path manifestPath = bundleDir.resolve("META-INF/MANIFEST.MF");
891 Manifest manifest;
892 try (InputStream in = Files.newInputStream(manifestPath)) {
893 manifest = new Manifest(in);
894 }
895 try (JarOutputStream jarOut = new JarOutputStream(Files.newOutputStream(jarPath), manifest)) {
896 jarOut.setLevel(Deflater.DEFAULT_COMPRESSION);
897 Files.walkFileTree(bundleDir, new SimpleFileVisitor<Path>() {
898
899 @Override
900 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
901 if (file.getFileName().toString().equals("MANIFEST.MF"))
902 return super.visitFile(file, attrs);
903 JarEntry entry = new JarEntry(bundleDir.relativize(file).toString());
904 jarOut.putNextEntry(entry);
905 Files.copy(file, jarOut);
906 return super.visitFile(file, attrs);
907 }
908
909 });
910 }
911 deleteDirectory(bundleDir);
912 return jarPath;
913 }
914
915 /** For development purproses. */
916 public static void main(String[] args) {
917 Path factoryBase = Paths.get("../../output/a2").toAbsolutePath().normalize();
918 A2Factory factory = new A2Factory(factoryBase);
919
920 Path descriptorsBase = Paths.get("../tp").toAbsolutePath().normalize();
921
922 // factory.processSingleM2ArtifactDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache").resolve("org.apache.xml.resolver.bnd"));
923 factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.apache/apache-sshd"));
924 // factory.processM2BasedDistributionUnit(descriptorsBase.resolve("org.argeo.tp.jetty/jetty"));
925 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.jetty.websocket"));
926 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.eclipse.rcp"));
927 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp"));
928 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.apache"));
929 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.formats"));
930 // factory.processCategory(descriptorsBase.resolve("org.argeo.tp.gis"));
931 System.exit(0);
932
933 // Eclipse
934 factory.processEclipseArchive(
935 descriptorsBase.resolve("org.argeo.tp.eclipse.equinox").resolve("eclipse-equinox"));
936 factory.processEclipseArchive(descriptorsBase.resolve("org.argeo.tp.eclipse.rwt").resolve("eclipse-rwt"));
937 factory.processEclipseArchive(descriptorsBase.resolve("org.argeo.tp.eclipse.rap").resolve("eclipse-rap"));
938 factory.processEclipseArchive(descriptorsBase.resolve("org.argeo.tp.eclipse.swt").resolve("eclipse-swt"));
939 factory.processEclipseArchive(descriptorsBase.resolve("org.argeo.tp.eclipse.swt").resolve("eclipse-nebula"));
940 factory.processEclipseArchive(descriptorsBase.resolve("org.argeo.tp.eclipse.swt").resolve("eclipse-equinox"));
941 factory.processEclipseArchive(descriptorsBase.resolve("org.argeo.tp.eclipse.rcp").resolve("eclipse-rcp"));
942 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.eclipse.rcp"));
943
944 // Maven
945 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.sdk"));
946 factory.processCategory(descriptorsBase.resolve("org.argeo.tp"));
947 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.apache"));
948 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.jetty"));
949 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.jcr"));
950 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.formats"));
951 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.poi"));
952 factory.processCategory(descriptorsBase.resolve("org.argeo.tp.gis"));
953 }
954 }